/* PhBBumpMap.C: PhBBumpMap nodes (public source) */

#include "PhBBumpMap.H"

namespace xrml {

void PhBBumpMap::render(void)
{
  if (texture) {
    texture->render();

    long nrChannels = (texture) ? texture->nrChannels() : 0;
    if(dX == NULL) dX = new float [nrChannels];
    if(dY == NULL) dY = new float [nrChannels];
    if(dZ == NULL) dZ = new float [nrChannels];
  }
  if(transform) transform->render();
}

Mat3 PhBBumpMap::distort(const Vec3 point)
{
  long nrChannels = (texture) ? texture->nrChannels() : 0;

  if (nrChannels == 0) return Mat3();

  // get d values
  Vec3 texco = point;
  if (transform) texco *= transform->xf;
  texture->Dvalues(texco.x, texco.y, dX, dY, dZ);

  // only use first channels as heightmap and calc axis
  Vec3 Xi = Vec3(1. , 0. , height * dX[0]).normalize();
  Vec3 Yi = Vec3(0. , 1. , height * dY[0]).normalize();
  Vec3 Z = (Xi ^ Yi).normalize();
  Vec3 X = ((Yi ^ Z) + Xi).normalize();
  Vec3 Y = ((Z ^ Xi) + Yi).normalize();

  // return
  return Mat3( X, Y, Z);
}

}  // namespace xrml
