<!--
Copyright 2009, Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
    * Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->

<!--
In this tutorial, we show how to create bitmaps and how to draw
images on both bitmaps and textures.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>
Bitmap Draw Image Demo
</title>
<script type="text/javascript" src="o3djs/base.js"></script>
<script type="text/javascript" id="o3dscript">
o3djs.require('o3djs.util');
o3djs.require('o3djs.math');
o3djs.require('o3djs.loader');
o3djs.require('o3djs.rendergraph');
o3djs.require('o3djs.primitives');
o3djs.require('o3djs.material');

// Events
// Run the init() once the page has finished loading.
window.onload = init;

// global variables
var g_o3d;
var g_math;
var g_client;
var g_pack;
var g_viewInfo;
var g_finished = false;  // for selenium testing
var g_eye;
var g_target;
var g_up;
var g_bitmaps = [];  // bitmaps by URL.

function makeShape(texture) {
  // Create a material.
  var myMaterial = o3djs.material.createMaterialFromFile(
      g_pack,
      'shaders/texture-only.shader',
      g_viewInfo.performanceDrawList);

  // Creates a quad.
  var myShape = o3djs.primitives.createPlane(g_pack,
                                             myMaterial,
                                             3,  // width
                                             3,  // height
                                             1,  // quads across
                                             1);  // quads down

  // Get the material's sampler parameter, get the sampler on it and set its
  // texture.
  var sampler_param = myMaterial.getParam('texSampler0');
  var sampler = sampler_param.value;

  // Set the texture to use.
  sampler.texture = texture;

  // adjust the scale of our transform to match the aspect ratio of
  // the texture. Of course we could also have waited until now to build
  // our plane and set its width and height to match instead of scaling
  // here.
  var textureWidth = texture.width;
  var textureHeight = texture.height;
  var hScale = 1;
  var vScale = 1;
  if (textureWidth > textureHeight) {
    vScale = textureHeight / textureWidth;
  } else if (textureHeight > textureWidth) {
    hScale = textureWidth / textureHeight;
  }
  // We now attach our quad to the root of the transform graph.
  // We do this after the texture has loaded, otherwise we'd be attempting
  // to display something invalid.

  // Make a transform for each quad.
  var transform = g_pack.createObject('Transform');
  transform.scale(hScale, 1, vScale);
  transform.addShape(myShape);
  transform.parent = g_client.root;
  g_finished = true;
  return myShape;
}

function loadBitmap(loader, url) {
  loader.loadBitmaps(g_pack, o3djs.util.getAbsoluteURI('assets/' + url),
                     function(bitmaps, exception) {
      if (!exception) {
        // We know we are only loading 2D images so there will only be 1 bitmap.
        g_bitmaps[url] = bitmaps[0];
      } else {
        alert(exception);
      }
  });

}

/**
 * Creates the client area.
 */
function init() {
  o3djs.util.makeClients(initStep2, 'NotAntiAliased');
}

/**
 * Initializes O3D, loads the effect, and loads a tar.gz archive containing
 * a bunch of image files.  We'll create bitmaps from them.
 * And use drawImage function to create texture as well as mipmaps.
 */
function initStep2(clientElements) {
  // Initialize global variables and libraries.
  var o3dElement = clientElements[0];
  g_o3d = o3dElement.o3d;
  g_math = o3djs.math;
  g_client = o3dElement.client;

  // Create a pack to manage our resources/assets
  g_pack = g_client.createPack();

  // Create the render graph for a view.
  g_viewInfo = o3djs.rendergraph.createBasicView(
      g_pack,
      g_client.root,
      g_client.renderGraphRoot);

  // Set up an perspective projection.
  var proj_matrix = g_math.matrix4.perspective(
      g_math.degToRad(90),
      g_client.width / g_client.height,
      0.1,
      100);

  // Create the view matrix which tells the camera which way to point to.
  g_eye = [0, 1.5, 0];
  g_target = [0, 0, 0];
  g_up = [0, 0, -1];
  var view_matrix = g_math.matrix4.lookAt(g_eye, g_target, g_up);

  g_viewInfo.drawContext.view = view_matrix;
  g_viewInfo.drawContext.projection = proj_matrix;

  var loader = o3djs.loader.createLoader(callback);
  loadBitmap(loader, 'shaving_cream_300x300.jpg');
  loadBitmap(loader, 'four_pixel.png');
  loadBitmap(loader, 'hi.jpg');
  loader.finish();

  // Callback that happens when loader.finish() is called and all of
  // our textures have finished loading.
  function callback() {
    // Because bitmaps have their origin at the upper left, and in
    // this sample our plane is oriented with the texture coordinate
    // origin on the lower left, we need to flip all the bitmaps
    // vertically to match coordinate systems.
    var kids = g_bitmaps['shaving_cream_300x300.jpg'];
    kids.flipVertically();
    var four_square = g_bitmaps['four_pixel.png'];
    four_square.flipVertically();
    var label = g_bitmaps['hi.jpg'];
    label.flipVertically();

    var texture = g_pack.createTexture2D(300, 300, g_o3d.Texture.XRGB8, 0,
                                         false);
    // Draw bitmaps on the texture.
    // Scale down entire image into on lower left corner.
    texture.drawImage(kids, 0, 0, 0, 300, 300, 0, 0, 0, 150, 150);

    // Crop and scale up into the lower right corner.
    texture.drawImage(kids, 0, 0, 156, 100, 100, 0, 150, 0, 150, 150);

    // Flip and draw part of the image in the top left corner (and
    // texture coords are not inclusive -- they go from 0-299 for a
    // 300 pixel texture).
    texture.drawImage(kids, 0, 150, 150, 150, 150, 0, 149, 299, -150, -150);

    // Crop and draw cropped area in upper right corner, but we're
    // using a width and height that go beyond the edges of the image.
    texture.drawImage(kids, 0, 150, 150, 400, 400, 0, 150, 150, 400, 400);

    // Draw "O3D" label.
    texture.drawImage(label, 0, 0, 0, 100, 50, 0, 100, 125, 100, 50);

    // Fill in different mip-map levels with images that show at
    // different distances.  (Scroll the mouse wheel to see).

    // Fill in medium level with whole image.
    texture.drawImage(kids, 0, 0, 0, 300, 300, 1, 0, 0, 150, 150);

    // Fill in smaller level with four pixel image.
    texture.drawImage(four_square, 0, 0, 0, 2, 2, 2, 0, 0, 75, 75);

    makeShape(texture);
  }
  o3djs.event.addEventListener(o3dElement, 'wheel', scrollMe);
}

function scrollMe(e) {
  g_eye = g_math.mulScalarVector((e.deltaY < 0 ? 11 : 13) / 12, g_eye);
  g_viewInfo.drawContext.view = g_math.matrix4.lookAt(g_eye, g_target, g_up);
}
</script>
</head>
<body>
<h1>Bitmap Draw Image Demo</h1>
This tutorial shows how to create bitmaps and how to draw images
on both bitmaps and texture mipmaps.
<br/>
Scroll wheel to see different mipmaps.
<br/>
<!-- Start of O3D plugin -->
<div id="o3d" style="width: 600px; height: 600px"></div>
<!-- End of O3D plugin -->
</body>
</html>