/////////////////////////////////////////////////////////////
//                                                         //
// Copyright (c) 2007-2014 by The University of Queensland //
// Centre for Geoscience Computing                         //
// http://earth.uq.edu.au/centre-geoscience-computing      //
//                                                         //
// Primary Business: Brisbane, Queensland, Australia       //
// Licensed under the Open Software License version 3.0    //
// http://www.opensource.org/licenses/osl-3.0.php          //
//                                                         //
/////////////////////////////////////////////////////////////

#include "TriPatchSet.h"

TriPatchSet::TriPatchSet()
{
  m_bbx_set=false;
}

/*!
  check if a line between the given points crosses the triangle
  and return the triangle tag, -1 otherwise

  \param p1
  \param p2
*/
int TriPatchSet::isCrossing(const Vector3& p1, const Vector3& p2) const
{
  int res=-1;

  vector<Triangle3D>::const_iterator iter=m_triangles.begin();
  while((iter!=m_triangles.end()) && (res==-1)){
    if(iter->crosses(p1,p2)) res=iter->getTag();
    iter++;
  }

  return res;
}

void TriPatchSet::addTriangle(const Vector3& p1, const Vector3& p2, const Vector3& p3,int tag)
{
  Triangle3D T=Triangle3D(p1,p2,p3,tag);
  Vector3 tmin=T.getMinPoint();
  Vector3 tmax=T.getMaxPoint();
  m_triangles.push_back(Triangle3D(p1,p2,p3,tag));
  // update bounding box
  if(m_bbx_set){ // already have bbx -> update
    m_pmin.X()=(m_pmin.X() < tmin.X()) ?  m_pmin.X() : tmin.X();
    m_pmin.Y()=(m_pmin.Y() < tmin.Y()) ?  m_pmin.Y() : tmin.Y();
    m_pmin.Z()=(m_pmin.Z() < tmin.Z()) ?  m_pmin.Z() : tmin.Z();
    m_pmax.X()=(m_pmax.X() > tmax.X()) ?  m_pmax.X() : tmax.X();
    m_pmax.Y()=(m_pmax.Y() > tmax.Y()) ?  m_pmax.Y() : tmax.Y();
    m_pmax.Z()=(m_pmax.Z() > tmax.Z()) ?  m_pmax.Z() : tmax.Z();
  } else { // no bbx yet -> initialize
    m_pmin=tmin;
    m_pmax=tmax;
    m_bbx_set=true;
  }
  //std::cout << "patch set size: " << m_triangles.size() 
  //<< " bbx: " << m_pmin << " - " << m_pmax << std::endl;
}
