<!--

/*
** Copyright (c) 2012 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/

-->

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../../resources/js-test-style.css"/>
<script src="../../resources/js-test-pre.js"></script>
<script src="../resources/webgl-test-utils.js"></script>
</head>
<body>
<canvas id="example" width="16" height="16"></canvas>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
description('Verifies texImage2D and texSubImage2D code paths taking ArrayBufferView');

var wtu = WebGLTestUtils;
var gl = null;
var textureLoc = null;
var successfullyParsed = false;

function roundUpToAlignment(value, alignment) {
  return Math.floor((value + alignment - 1) / alignment) * alignment;
}

function generateRGBAData(type, unpackAlignment, sourceData, width, height)
{
    var numColors = sourceData.length / 4;
    var colorOffset = function(y) {
      return 4 * Math.floor(y * numColors / height);
    };

    switch (type) {
    case gl.UNSIGNED_BYTE: {
        var rowWidth = roundUpToAlignment(width * 4, unpackAlignment);
        var data = new Uint8Array(height * rowWidth);
        for (var y = 0; y < height; ++y) {
            var index = y * rowWidth;
            var offset = colorOffset(y);
            for (var element = 0; element < width * 4; ++element) {
                data[index + element] = sourceData[offset + element % 4];
            }
        }
        return data;
    }
    case gl.UNSIGNED_SHORT_4_4_4_4: {
        var rowWidth = roundUpToAlignment(width * 2, unpackAlignment) / 2;
        var data = new Uint16Array(height * rowWidth);
        for (var y = 0; y < height; ++y) {
            var offset = colorOffset(y);
            for (var x = 0; x < width; ++x) {
                var index = y * rowWidth + x;
                data[index] = (((sourceData[offset + 0] & 0xF0) << 8)
                             | ((sourceData[offset + 1] & 0xF0) << 4)
                             | ((sourceData[offset + 2] & 0xF0) >> 0)
                             | ((sourceData[offset + 3] & 0xF0) >> 4));
            }
        }
        return data;
    }
    case gl.UNSIGNED_SHORT_5_5_5_1: {
        var rowWidth = roundUpToAlignment(width * 2, unpackAlignment) / 2;
        var data = new Uint16Array(height * rowWidth);
        for (var y = 0; y < height; ++y) {
            var offset = colorOffset(y);
            for (var x = 0; x < width; ++x) {
                var index = y * rowWidth + x;
                data[index] = (((sourceData[offset + 0] & 0xF8) << 8)
                             | ((sourceData[offset + 1] & 0xF8) << 3)
                             | ((sourceData[offset + 2] & 0xF8) >> 2)
                             | ((sourceData[offset + 3] & 0x80) >> 7));
            }
        }
        return data;
    }
    }
}

function typeToString(type)
{
    switch (type) {
    case gl.UNSIGNED_BYTE:           return 'UNSIGNED_BYTE';
    case gl.UNSIGNED_SHORT_5_5_5_1:  return 'UNSIGNED_SHORT_5_5_5_1';
    case gl.UNSIGNED_SHORT_4_4_4_4:  return 'UNSIGNED_SHORT_4_4_4_4';
    }
    return 'Unknown type ' + type;
}

function runOneIteration(useTexSubImage2D, type, unpackAlignment, flipY, premultiplyAlpha, topColor, bottomColor, extraColor)
{
    debug('Testing ' + (useTexSubImage2D ? 'texSubImage2D' : 'texImage2D') +
          ' with type=' + typeToString(type) +
          ', unpackAlignment=' + unpackAlignment +
          ', flipY=' + flipY + ', premultiplyAlpha=' + premultiplyAlpha);
    gl.colorMask(true, true, true, true);
    gl.clearColor(0, 0, 0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    // Enable writes to the RGB channels
    gl.colorMask(true, true, true, false);
    var texture = gl.createTexture();
    // Bind the texture to texture unit 0
    gl.bindTexture(gl.TEXTURE_2D, texture);
    // Set up texture parameters
    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);
    // Set up pixel store parameters
    gl.pixelStorei(gl.UNPACK_ALIGNMENT, unpackAlignment);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
    gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha);
    // Generate the data
    var sourceData = [ 255,   0,   0, 255,
                       0,   255,   0,   0 ];
    var texWidth = 5;   // this must be mod 4 + 1 to test unpackAlignment
    var texHeight = 16;
    var data = generateRGBAData(type, unpackAlignment, sourceData, texWidth, texHeight);
    if (gl.getError() != gl.NO_ERROR)
        testFailed("GL error before texture upload");
    // Upload the image into the texture
    if (useTexSubImage2D) {
        // Initialize the texture to black first
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texWidth, texHeight, 0,
                      gl.RGBA, type, null);
        if (gl.getError() != gl.NO_ERROR)
            testFailed("GL error after texImage2D(null)");
        gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, texWidth, texHeight, gl.RGBA, type, data);
        if (gl.getError() != gl.NO_ERROR)
            testFailed("GL error after texSubImage2D");
    } else {
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texWidth, texHeight, 0, gl.RGBA, type, data);
        if (gl.getError() != gl.NO_ERROR)
            testFailed("GL error after texImage2D");
    }

    // Point the uniform sampler to texture unit 0
    gl.uniform1i(textureLoc, 0);
    // Draw the triangles
    wtu.clearAndDrawUnitQuad(gl, [0, 0, 0, 255]);

    // Check the top pixel and bottom pixel and make sure they have
    // the right color.
    var testWidth  = gl.drawingBufferWidth;
    var testHeight = gl.drawingBufferHeight / 2;
    wtu.checkCanvasRect(gl, 0, 0, testWidth, testHeight, bottomColor, "bottom pixel should be " + bottomColor);
    wtu.checkCanvasRect(gl, 0, testHeight, testWidth, testHeight, topColor, "top pixel should be " + topColor);

    // Change part of the texture.
    var partWidth = 8;
    var partHeight = 16;
    // make texture double res of part.
    var data = generateRGBAData(type, unpackAlignment, sourceData, partWidth * 2, partHeight * 2);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, partWidth * 2, partHeight * 2, 0, gl.RGBA, type, data);
    // set part.
    var extraData = [
      255,   0,   0, 255,
        0,   0, 255,   0
    ];
    var data = generateRGBAData(type, unpackAlignment, extraData, partWidth, partHeight);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, partWidth, partHeight, gl.RGBA, type, data);
    wtu.clearAndDrawUnitQuad(gl, [0, 0, 0, 255]);
    var halfWidth  = gl.drawingBufferWidth / 2;
    var halfHeight = gl.drawingBufferHeight / 2;
    var quarterHeight = gl.drawingBufferHeight / 4;
    var red = [255, 0, 0, 255];
    var tcolor0 = flipY ? extraColor : red;
    var tcolor1 = flipY ? red : extraColor;
    wtu.checkCanvasRect(gl, 0, 0, halfWidth, quarterHeight, tcolor0, "bottom left bottom pixels should be " + tcolor0);
    wtu.checkCanvasRect(gl, 0, quarterHeight, halfWidth, quarterHeight, tcolor1, "bottom left top pixels should be " + tcolor1);
    wtu.checkCanvasRect(gl, halfWidth, 0, halfWidth, halfHeight, bottomColor, "bottom right pixels should be " + bottomColor);
    wtu.checkCanvasRect(gl, 0, halfHeight, testWidth, halfHeight, topColor, "top pixels should be " + topColor);
    // set far corner.
    gl.texSubImage2D(gl.TEXTURE_2D, 0, partWidth, partHeight, partWidth, partHeight, gl.RGBA, type, data);
    wtu.clearAndDrawUnitQuad(gl, [0, 0, 0, 255]);
    wtu.checkCanvasRect(gl, 0, 0, halfWidth, quarterHeight, tcolor0, "bottom left bottom pixels should be " + tcolor0);
    wtu.checkCanvasRect(gl, 0, quarterHeight, halfWidth, quarterHeight, tcolor1, "bottom left top pixels should be " + tcolor1);
    wtu.checkCanvasRect(gl, halfWidth, 0, halfWidth, halfHeight, bottomColor, "bottom left pixels should be " + bottomColor);
    wtu.checkCanvasRect(gl, 0, halfHeight, halfWidth, halfHeight, topColor, "top right pixels should be " + topColor);
    wtu.checkCanvasRect(gl, halfWidth, halfHeight, halfWidth, quarterHeight, tcolor0, "top right bottom pixels should be " + tcolor0);
    wtu.checkCanvasRect(gl, halfWidth, halfHeight + quarterHeight, halfWidth, quarterHeight, tcolor1, "top right top pixels should be " + tcolor1);
}

function runTest()
{
    var red = [255, 0, 0, 255];
    var green = [0, 255, 0, 255];
    var blue = [0, 0, 255, 255];
    var redPremultiplyAlpha = [255, 0, 0, 255];
    var greenPremultiplyAlpha = [0, 0, 0, 255];
    var bluePremultiplyAlpha = [0, 0, 0, 255];

    var types = [ gl.UNSIGNED_BYTE, gl.UNSIGNED_SHORT_5_5_5_1, gl.UNSIGNED_SHORT_4_4_4_4 ];
    var unpackAlignments = [ 1, 2, 4, 8 ];

    for (var i = 0; i < types.length; ++i) {
        var type = types[i];
        for (var j = 0; j < unpackAlignments.length; ++j) {
            var unpackAlignment = unpackAlignments[j];
            runOneIteration(false, type, unpackAlignment, true, false,
                            red, green, blue);
            runOneIteration(false, type, unpackAlignment, false, false,
                            green, red, blue);
            runOneIteration(false, type, unpackAlignment, true, true,
                            redPremultiplyAlpha, greenPremultiplyAlpha, bluePremultiplyAlpha);
            runOneIteration(false, type, unpackAlignment, false, true,
                            greenPremultiplyAlpha, redPremultiplyAlpha, bluePremultiplyAlpha);
            runOneIteration(true, type, unpackAlignment, true, false,
                            red, green, blue);
            runOneIteration(true, type, unpackAlignment, false, false,
                            green, red, blue);
            runOneIteration(true, type, unpackAlignment, true, true,
                            redPremultiplyAlpha, greenPremultiplyAlpha, bluePremultiplyAlpha);
            runOneIteration(true, type, unpackAlignment, false, true,
                            greenPremultiplyAlpha, redPremultiplyAlpha, bluePremultiplyAlpha);
        }
    }

}

var gl = wtu.create3DContext("example");
var program = wtu.setupTexturedQuad(gl);

textureLoc = gl.getUniformLocation(program, "tex");

runTest();
wtu.glErrorShouldBe(gl, gl.NO_ERROR, "should be no errors");
var successfullyParsed = true;
</script>
<script src="../../resources/js-test-post.js"></script>
</body>
</html>
