<!--
Copyright (c) 2019 The Khronos Group Inc.
Use of this source code is governed by an MIT-style license that can be
found in the LICENSE.txt file.
-->

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebGL OES_texture_half_float Conformance Tests</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>
<script src="../../js/js-test-pre.js"></script>
<script src="../../js/webgl-test-utils.js"></script>
</head>
<body>
<div id="description"></div>
<canvas id="canvas" style="width: 50px; height: 50px;"> </canvas>
<canvas id="canvas2d" style="width: 50px; height: 50px;"> </canvas>
<div id="console"></div>
<script id="testFragmentShader" type="x-shader/x-fragment">
precision mediump float;
uniform sampler2D tex;
uniform vec4 subtractor;
varying vec2 texCoord;
void main()
{
    vec4 color = texture2D(tex, texCoord);
    if (abs(color.r - subtractor.r) +
        abs(color.g - subtractor.g) +
        abs(color.b - subtractor.b) +
        abs(color.a - subtractor.a) < 8.0) {
        gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
    } else {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
}
</script>
<!-- Shaders for testing half-floating-point render targets -->
<script id="floatingPointFragmentShader" type="x-shader/x-fragment">
void main()
{
    gl_FragColor = vec4(10000.0, 10000.0, 10000.0, 10000.0);
}
</script>
<script>
"use strict"
description("This test verifies the functionality of OES_texture_half_float with null/non-null ArrayBufferView");

debug("");
var wtu = WebGLTestUtils;
var canvas = document.getElementById("canvas");
var colorCanvas = document.getElementById("canvas2d");
colorCanvas.width = 2;
colorCanvas.height = 2;
var ctx = colorCanvas.getContext("2d");
ctx.fillStyle = "rgb(255,0,0)";
ctx.fillRect(0, 0, 2, 2);
var gl = wtu.create3DContext(canvas);
// This constant must be defined in order to run the texture creation test without the extension enabled.
var halfFloatOESEnum = 0x8D61;
var ext = null;


if (!gl) {
    testFailed("WebGL context does not exists");
} else {
    testPassed("WebGL context exists");

    // Verify that allocation of texture fails if extension is not enabled
    runTextureCreationTest(false);
    ext = gl.getExtension("OES_texture_half_float")
    if (!ext) {
        testPassed("No OES_texture_half_float support. This is legal");
    } else {
        testPassed("Successfully enabled OES_texture_half_float extension");

        var program = wtu.setupTexturedQuad(gl);

        // Check if creation of texture succeed's with various formats and null ArrayBufferView
        var formats = [
          { format: gl.RGBA,            expected: [255,   0,   0, 255], },
          { format: gl.RGB,             expected: [255,   0,   0, 255], },
          { format: gl.LUMINANCE,       expected: [255, 255, 255, 255], },
          { format: gl.ALPHA,           expected: [  0,   0,   0, 255], },
          { format: gl.LUMINANCE_ALPHA, expected: [255, 255, 255, 255], },
        ];
        formats.forEach(function(f) {
            runTextureCreationTest(true, f.format, null, f.expected);
        });

        // Texture creation should fail when passed with non-null, non-Uint16 ArrayBufferView
        formats.forEach(function(f) {
            var width = 2;
            var height = 2;
            var format = f.format;

            // Float32Array
            var float32Data = new Float32Array(width * height * getNumberOfChannels(format));
            for (var ii = 0; ii < float32Data.length; ii++) {
                float32Data[ii] = 1000;
            }
            runTextureCreationTest(true, format, float32Data, null);

            // Int16Array
            var int16Data = new Int16Array(width * height * getNumberOfChannels(format));
            for (var ii = 0; ii <  int16Data.length; ii++) {
                int16Data[ii] = 1000;
            }
            runTextureCreationTest(true, format, int16Data, null);
        });

        // Test that Uint16 encoded half float values can be used as texture data.

        // First test that values in the 0-1 range can be written and read.
        var halfFloatOneThird = 0x3555; // Half float 1/3
        var uint16Formats = [
          { format: gl.RGBA,            expected: [85, 85, 85,  85], },
          { format: gl.RGB,             expected: [85, 85, 85, 255], },
          { format: gl.LUMINANCE,       expected: [85, 85, 85, 255], },
          { format: gl.ALPHA,           expected: [ 0,  0,  0,  85], },
          { format: gl.LUMINANCE_ALPHA, expected: [85, 85, 85,  85], },
        ];

        uint16Formats.forEach(function(f) {
            var width = 2;
            var height = 2;
            var format = f.format;

            var uint16Data = new Uint16Array(width * height * getNumberOfChannels(format));
            for (var ii = 0; ii <  uint16Data.length; ii++) {
                uint16Data[ii] = halfFloatOneThird;
            }
            runTextureCreationTest(true, format, uint16Data, f.expected);
        });

        // Next check that values outside the 0-1 range can be written.
        var halfFloatTenK = 0x70E2; // Half float 10000
        var uint16Formats2 = [
          { format: gl.RGBA, subtractor: [10000, 10000, 10000, 10000], requireRenderable: true},
          { format: gl.RGB,  subtractor: [10000, 10000, 10000, 1], requireRenderable: false},
        ];

        uint16Formats2.forEach(function(f) {
            var width = 2;
            var height = 2;
            var format = f.format;

            var uint16Data = new Uint16Array(width * height * getNumberOfChannels(format));
            for (var ii = 0; ii <  uint16Data.length; ii++) {
                uint16Data[ii] = halfFloatTenK;
            }
            runRenderTest(format, f.subtractor, uint16Data, f.requireRenderable);
        });

        (function() {
            debug("");
            var renderable = isRenderable(gl, ext);
            var renderableExtName = "EXT_color_buffer_half_float";
            var supported = gl.getSupportedExtensions().includes(renderableExtName);
            if (renderable && !supported) {
                testFailed("RGBA/HALF_FLOAT_OES is color renderable but " + renderableExtName + " not exposed");
            } else if (supported && !renderable) {
                testFailed(renderableExtName + " is exposed but RGBA/HALF_FLOAT_OES is not color renderable");
            }
            if (supported) {
                runRenderTest(gl.RGBA, [10000, 10000, 10000, 10000], null, true);
                runRenderTest(gl.RGB, [10000, 10000, 10000, 1], null, false);
                runFramebufferTest();
            }
        })();

        // Check of getExtension() returns same object
        runUniqueObjectTest();
    }
}

function isRenderable(gl, ext) {
    var tex = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, ext.HALF_FLOAT_OES, null);

    var fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);

    var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
    gl.deleteFramebuffer(fb);
    gl.deleteTexture(tex);

    return status == gl.FRAMEBUFFER_COMPLETE;
}

function getNumberOfChannels(format)
{
    if (format == gl.RGBA)
        return 4;
    else if (format == gl.RGB)
        return 3;
    else if (format == gl.LUMINANCE || format == gl.ALPHA)
        return 1;
    else if (format == gl.LUMINANCE_ALPHA)
        return 2;
}

function allocateTexture()
{
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    wtu.glErrorShouldBe(gl, gl.NO_ERROR, "texture parameter setup should succeed");
    return texture;
}

function runTextureCreationTest(extensionEnabled, opt_format, opt_data, opt_expected)
{
    var format = opt_format || gl.RGBA;
    var data = opt_data || null;
    var expectSuccess = true;

    if (!extensionEnabled || !opt_expected)
        expectSuccess = false;
    debug("Testing texture creation with extension " + (extensionEnabled ? "enabled" : "disabled") +
          ", format " + wtu.glEnumToString(gl, format) + ", and data " + (data ? "non-null" : "null") +
          ". Expect " + (expectSuccess ? "Success" : "Failure"));

    var texture = allocateTexture();
    var width = 2;
    var height = 2;
    gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, halfFloatOESEnum, data);
    if(!extensionEnabled) {
        wtu.glErrorShouldBe(gl, gl.INVALID_ENUM, "Half floating point texture must be disallowed if OES_texture_half_float isn't enabled");
        return;
    } else if (!opt_expected) {
        wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION, "Half floating point texture allocation must be disallowed when ArrayBufferView is not-null and not-Uint16");
        return;
    } else {
        wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Half floating point texture allocation should succeed if OES_texture_half_float is enabled");

        if (!data) {
            gl.texImage2D(gl.TEXTURE_2D, 0, format, format, halfFloatOESEnum, colorCanvas);
        }
        wtu.clearAndDrawUnitQuad(gl);
        wtu.checkCanvas(gl, opt_expected);
        // Check that linear fails.
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
        wtu.clearAndDrawUnitQuad(gl);
        wtu.checkCanvas(gl, [0, 0, 0, 255], "should be black");
    }

}

function checkRenderingResults()
{
    wtu.checkCanvas(gl, [0, 255, 0, 255], "should be green");
}

function runRenderTest(format, subtractor, data, requireRenderable)
{
    var formatString = wtu.glEnumToString(gl, format);

    debug("");

    if (!data) {
        debug("Testing half floating point " + formatString + " render target");
    } else {
        debug("Testing half floating point " + formatString + " from a Uint16Array");
    }

    var texture = allocateTexture();
    var width = 2;
    var height = 2;

    gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, ext.HALF_FLOAT_OES, data);
    wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Half floating point texture allocation should succeed if OES_texture_half_float is enabled");

    if (!data) {
        // Try to use this texture as render target
        var fbo = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
        gl.bindTexture(gl.TEXTURE_2D, null);

        // It is legal for a WebGL implementation exposing the OES_texture_half_float extension to
        // support half floating point textures but not as attachments to framebuffer objects.
        if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE) {
            if (requireRenderable) {
                testFailed(formatString + " render targets not supported.");
            } else {
                debug(formatString + " render targets not supported -- this is legal");
            }
            return;
        }

        var renderProgram =
            wtu.setupProgram(gl,
                             [wtu.simpleVertexShader, "floatingPointFragmentShader"],
                             ['vPosition'],
                             [0]);
        wtu.drawUnitQuad(gl);
        wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Rendering to half floating point texture should succeed");
    }

    // Now sample from the half floating-point texture and verify we got the correct values.
    var texturedShaders = [
          wtu.simpleTextureVertexShader,
          "testFragmentShader"
      ];
    var testProgram =
        wtu.setupProgram(gl,
                        [wtu.simpleTextureVertexShader, "testFragmentShader"],
                        ['vPosition', 'texCoord0'],
                        [0, 1]);
    var quadParameters = wtu.setupUnitQuad(gl, 0, 1);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.useProgram(testProgram);
    gl.uniform4fv(gl.getUniformLocation(testProgram, "subtractor"), subtractor);
    wtu.drawUnitQuad(gl);
    wtu.glErrorShouldBe(gl, gl.NO_ERROR, "rendering from half floating point texture should succeed");
    checkRenderingResults();
}

function runUniqueObjectTest()
{
    debug("");
    debug("Testing that getExtension() returns the same object each time");
    ext = null;
    gl.getExtension("OES_texture_half_float").myProperty = 2;
    webglHarnessCollectGarbage();
    shouldBe('gl.getExtension("OES_texture_half_float").myProperty', '2');
}

// Make sure we can call readPixels with the passed in arrayBufferConstructor and that the color
// channels are the ones we expect. If there is a mismatch between the glType and arrayBuffer type,
// fail the test.
function verifyReadPixelsColors(red, green, blue, alpha, alphaRGB, glFormat, glType, arrayBufferConstructor) {
    var typeName = wtu.glEnumToString(gl, glType);

    debug(wtu.glEnumToString(gl, glFormat) + " framebuffer with " + typeName + " readback.");

    var arrayBuffer = new arrayBufferConstructor(4);
    gl.readPixels(0, 0, 1, 1, gl.RGBA, glType, arrayBuffer);
    wtu.glErrorShouldBe(gl, gl.NO_ERROR, "readPixels should return NO_ERROR when reading " + typeName + " data.");

    assertMsg(arrayBuffer[0] === red, "Red channel should be " + red + " for " + typeName + " readPixels. Received: " + arrayBuffer[0]);
    assertMsg(arrayBuffer[1] === green, "Green channel should be " + green + " for " + typeName + " readPixels. Received: " + arrayBuffer[1]);
    assertMsg(arrayBuffer[2] === blue, "Blue channel should be " + blue + " for " + typeName + " readPixels. Received: " + arrayBuffer[2]);
    if (glFormat === gl.RGBA) {
        assertMsg(arrayBuffer[3] === alpha, "Alpha channel should be " + alpha + " for " + typeName + " readPixels. Received: " + arrayBuffer[3]);
    } else if (glFormat === gl.RGB) {
        assertMsg(arrayBuffer[3] === alphaRGB, "Alpha channel should be " + alphaRGB + " for " + typeName + " readPixels. Received: " + arrayBuffer[3]);
    }

    // Make sure any arrayBuffer types that are not equal to arrayBufferConstructor fail readPixels.
    if (arrayBufferConstructor !== Uint8Array) {
        arrayBuffer = new Uint8Array(4);
        gl.readPixels(0, 0, 1, 1, gl.RGBA, glType, arrayBuffer);
        wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION, "readPixels should return INVALID_OPERATION when reading mismatched types. " + Uint8Array.toString());
    }
    if (arrayBufferConstructor !== Float32Array) {
        arrayBuffer = new Float32Array(4);
        gl.readPixels(0, 0, 1, 1, gl.RGBA, glType, arrayBuffer);
        wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION, "readPixels should return INVALID_OPERATION when reading mismatched types. " + Float32Array.toString());
    }
    if (arrayBufferConstructor !== Uint16Array) {
        arrayBuffer = new Uint16Array(4);
        gl.readPixels(0, 0, 1, 1, gl.RGBA, glType, arrayBuffer);
        wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION, "readPixels should return INVALID_OPERATION when reading mismatched types. " + Uint16Array.toString());
    }
}

// Verify that half float textures attached to frame buffers function correctly with regard to framebuffer
// completness, IMPLEMENTATION_COLOR_READ_FORMAT/TYPE and readPixels
function runFramebufferTest() {
    debug("");
    debug("Framebuffer Tests");

    var texture = allocateTexture();
    gl.bindTexture(gl.TEXTURE_2D, texture);

    var fbo = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);

    debug("Ensure non-color-renderable formats [LUMINANCE, LUMINANCE_ALPHA, ALPHA] fail.");
    var arrayBufferFloatOutput = new Float32Array(4); // 4 color channels
    [gl.LUMINANCE, gl.LUMINANCE_ALPHA, gl.ALPHA].forEach(function(badFormat) {
        debug(wtu.glEnumToString(gl, badFormat) + " framebuffer");

        gl.texImage2D(gl.TEXTURE_2D, 0, badFormat, 1, 1, 0, badFormat, ext.HALF_FLOAT_OES, null);
        shouldBe("gl.checkFramebufferStatus(gl.FRAMEBUFFER)", "gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT");

        shouldBeNull("gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)");
        wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION, "IMPLEMENTATION_COLOR_READ_FORMAT should fail for incomplete framebuffers.");

        shouldBeNull("gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE)");
        wtu.glErrorShouldBe(gl, gl.INVALID_OPERATION, "IMPLEMENTATION_COLOR_READ_TYPE should fail for incomplete framebuffers.");

        gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.FLOAT, arrayBufferFloatOutput);
        wtu.glErrorShouldBe(gl, gl.INVALID_FRAMEBUFFER_OPERATION , "readPixels should fail on incomplete framebuffers.");
        debug("");
    });

    debug("Ensure color renderable formats [RGBA, RGB] succeed.");
    var arrayBufferHalfFloatInput = new Uint16Array(4); // 4 color channels
    arrayBufferHalfFloatInput[0] = 0;      // 0 in half float
    arrayBufferHalfFloatInput[1] = 0x3400; // 0.25 in half float
    arrayBufferHalfFloatInput[2] = 0x3800; // 0.50 in half float
    arrayBufferHalfFloatInput[3] = 0x3A00; // 0.75 in half float

    [gl.RGBA, gl.RGB].forEach(function(goodFormat) {
        debug(wtu.glEnumToString(gl, goodFormat) + " framebuffer tests");
        debug("");

        gl.texImage2D(gl.TEXTURE_2D, 0, goodFormat, 1, 1, 0, goodFormat, ext.HALF_FLOAT_OES, arrayBufferHalfFloatInput);
        if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) == gl.FRAMEBUFFER_COMPLETE) {
            // Per the OES_color_buffer_half_float, RGBA/FLOAT should always succeed for readPixels
            verifyReadPixelsColors(
                0.00, // red
                0.25, // green
                0.50, // blue
                0.75, // alpha
                1.0,  // alphaRGB
                goodFormat,
                gl.FLOAT,
                Float32Array);

            var implementationColorReadFormat = gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT);
            assertMsg(implementationColorReadFormat === gl.RGBA || implementationColorReadFormat === gl.RGB,
                "IMPLEMENTATION_COLOR_READ_FORMAT should be color renderable: RGBA or RGB. Received: " + wtu.glEnumToString(gl, implementationColorReadFormat));

            var implementationColorReadType = gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE);

            // There is nothing in the specifications that keeps the
            // implementation color read format and type from being the
            // same as the implicitly supported one. For this reason, keep
            // gl.FLOAT as one of the valid options.
            assertMsg(implementationColorReadType === gl.UNSIGNED_BYTE ||
                      implementationColorReadType === gl.FLOAT ||
                      implementationColorReadType === ext.HALF_FLOAT_OES ||
                      implementationColorReadType === gl.UNSIGNED_SHORT_4_4_4_4 ||
                      implementationColorReadType === gl.UNSIGNED_SHORT_5_5_5_1 ||
                      implementationColorReadType === gl.UNSIGNED_SHORT_5_6_5,
                      "IMPLEMENTATION_COLOR_READ_TYPE must be one of UNSIGNED_BYTE, UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_5_5_5_1, UNSIGNED_SHORT_5_6_5, FLOAT, or HALF_FLOAT_OES. " +
                      "Received: " + wtu.glEnumToString(gl, implementationColorReadType));

            // Test the RGBA/HALF_FLOAT_OES combination
            if (implementationColorReadFormat === gl.RGBA && implementationColorReadType === ext.HALF_FLOAT_OES) {
                verifyReadPixelsColors(
                    0,      // red
                    0x3400, // green
                    0x3800, // blue
                    0x3A00, // alpha
                    0x3C00, // alphaRGB
                    goodFormat,
                    ext.HALF_FLOAT_OES,
                    Uint16Array);
            }
        }
        debug("");
    });
}

debug("");
var successfullyParsed = true;
</script>
<script src="../../js/js-test-post.js"></script>

</body>
</html>
