/** Counts the number of virtual indices of a DrawCall. */
 int countIndices() const
 {
   int count = 0;
   for( IndexIterator it = indexIterator(); !it.isEnd(); it.next() )
     count++;
   return count;
 }
//-----------------------------------------------------------------------------
void DoubleVertexRemover::removeDoubles(Geometry* geom)
{
  mMapNewToOld.clear();
  mMapOldToNew.clear();

  std::vector<unsigned int> verti;
  verti.resize(geom->vertexArray()->size());
  mMapOldToNew.resize(verti.size());
  for(unsigned int i=0; i<verti.size(); ++i)
  {
    verti[i] = i;
    mMapOldToNew[i] = 0xFFFFFFFF;
  }
  mMapNewToOld.reserve(verti.size());

  std::sort(verti.begin(), verti.end(), CompareVertex(geom));

  if (verti.empty())
    return;

  unsigned int unique_vert_idx = 0;
  for(unsigned i=1; i<verti.size(); ++i)
  {
    if ( !CompareVertex(geom).equals(verti[unique_vert_idx],verti[i]) )
    {
      for(unsigned j=unique_vert_idx; j<i; ++j)
        mMapOldToNew[verti[j]] = mMapNewToOld.size();
      mMapNewToOld.push_back(verti[unique_vert_idx]);
      unique_vert_idx = i;
    }
  }
  for(unsigned j=unique_vert_idx; j<verti.size(); ++j)
  {
    mMapOldToNew[verti[j]] = mMapNewToOld.size();
    mMapNewToOld.push_back(verti[unique_vert_idx]);
  }

  // regenerate vertices

  geom->regenerateVertices(mMapNewToOld);

  // regenerate DrawCall

  std::vector< ref<DrawCall> > draw_cmd;
  for(int idraw=0; idraw<geom->drawCalls()->size(); ++idraw)
    draw_cmd.push_back( geom->drawCalls()->at(idraw) );
  geom->drawCalls()->clear();

  for(size_t idraw=0; idraw<draw_cmd.size(); ++idraw)
  {
    ref<DrawElementsUInt> tris = new DrawElementsUInt( draw_cmd[idraw]->primitiveType() );
    geom->drawCalls()->push_back(tris.get());
    const int idx_count = draw_cmd[idraw]->countIndices();
    tris->indices()->resize(idx_count);
    int i=0;
    for(IndexIterator it = draw_cmd[idraw]->indexIterator(); !it.isEnd(); it.next(), ++i)
      tris->indices()->at(i) = mMapOldToNew[it.index()];
  }

  #if 0
    printf("DoubleVertexRemover = %d/%d, saved = %d, shrink=%.2f\n", (int)mMapNewToOld.size(), (int)verti.size(), (int)verti.size()-(int)mMapNewToOld.size(), (float)mMapNewToOld.size()/verti.size() );
  #endif
}