DrawMesh.cc 47.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openflipper.org                             *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenFlipper.                                        *
 *                                                                           *
 *  OpenFlipper is free software: you can redistribute it and/or modify      *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenFlipper is distributed in the hope that it will be useful,           *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenFlipper. If not,                                  *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
*                                                                            *
*   $Revision$                                                       *
*   $LastChangedBy$                                                *
*   $Date$                     *
*                                                                            *
\*===========================================================================*/

#define ACG_DRAW_MESH_C

//=============================================================================

#include "DrawMesh.hh"
#include <ACG/Geometry/GPUCacheOptimizer.hh>
49
#include <ACG/GL/VertexDeclaration.hh>
50
51
52
53
54
55
56
#include <assert.h>
#include <math.h>
#include <vector>
#include <map>
#include <string.h>
#include <fstream>

57

58
59
60
61
//=============================================================================

#define DRAW_MESH_VERTEX_CMP_EPSILON 1e-4f

62
63
64
// print a memory usage report each draw call
//#define DEBUG_MEM_USAGE

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

namespace ACG
{

template <class Mesh>
DrawMeshT<Mesh>::Vertex::Vertex()
{
  for (int i = 0; i < 3; ++i)
  {
    pos[i] = 0.0f;
    n[i] = 0.0f;
//    tan[i] = 0.0f;

    if (i < 2)
      tex[i] = 0.0f;
  }

//  tan[3] = 0.0f;

  fcol = vcol = 0xFFFFFFFF;
}

template <class Mesh>
int DrawMeshT<Mesh>::Vertex::equals(const Vertex& r)
{
  float f = 0.0f; // difference
  for (int i = 0; i < 3; ++i)
  {
    f += fabsf(r.pos[i] - pos[i]);
    f += fabsf(r.n[i] - n[i]);
//    f += fabsf(r.tan[i] - tan[i]);

    if (i < 2)
      f += fabsf(r.tex[i] - tex[i]);
  }

//  f += fabsf(r.tan[3] - tan[3]);

  return (vcol == r.vcol && fcol == r.fcol) && (f < DRAW_MESH_VERTEX_CMP_EPSILON);
}

inline int intNextPowerOfTwo(int x)
{
  x--;
  x = (x >> 1) | x;
  x = (x >> 2) | x;
  x = (x >> 4) | x;
  x = (x >> 8) | x;
  x = (x >> 16) | x;
  x++;
  return x;
}

template <class Mesh>
DrawMeshT<Mesh>::DrawMeshT(Mesh& _mesh)
:  mesh_(_mesh),
   numTris_(0), numVerts_(0),
   indices_(0),
   vertices_(0),
   rebuild_(REBUILD_NONE),
   prevNumFaces_(0), prevNumVerts_(0),
   numSubsets_(0),
   subsets_(0),
   vbo_(0), ibo_(0),
   lineIBO_(0),
   indexType_(0),
   colorMode_(1),
   flatMode_(0), bVBOinFlatMode_(0),
   textureMode_(1), bVBOinHalfedgeTexMode_(1),
134
   halfedgeNormalMode_(0), bVBOinHalfedgeNormalMode_(0),
135
136
137
138
139
140
141
142
143
144
   triToFaceMap_(0),
   vertexMap_(0),
   invVertexMap_(0),
   indicesTmp_(0),
   verticesTmp_(0),
   textureIndexPropertyName_("Not Set"),
   perFaceTextureCoordinatePropertyName_("Not Set"),
   updatePerEdgeBuffers_(1),
  updatePerHalfedgeBuffers_(1)
{
145
146
147
  vertexDeclVCol_ = new VertexDeclaration;
  vertexDeclFCol_ = new VertexDeclaration;

148
149
150
151
152
153
154
155
156
  VertexElement elemArrayV[] = { {GL_FLOAT, 3, VERTEX_USAGE_POSITION, 0, {0} },
                                 {GL_FLOAT, 2, VERTEX_USAGE_TEXCOORD, 0, {0} },
                                 {GL_FLOAT, 3, VERTEX_USAGE_NORMAL, 0, {0} },
                                 {GL_UNSIGNED_BYTE, 4, VERTEX_USAGE_COLOR, 0, {0} } };

  VertexElement elemArrayF[] = { {GL_FLOAT, 3, VERTEX_USAGE_POSITION, 0, {0} },
                                 {GL_FLOAT, 2, VERTEX_USAGE_TEXCOORD, 0, {12} },
                                 {GL_FLOAT, 3, VERTEX_USAGE_NORMAL, 0, {20} },
                                 {GL_UNSIGNED_BYTE, 4, VERTEX_USAGE_COLOR, 0, {36} } };
157
158
159
160
161
162
163

  vertexDeclVCol_->addElements(4, elemArrayV);
  vertexDeclFCol_->addElements(4, elemArrayF);

  // VertexDeclaration computes a stride of 36 automatically
  // force 40 bytes instead!
  vertexDeclVCol_->setVertexStride(sizeof(Vertex)); // pad for Vertex::fcol
164
165
166
167
168
169
170
171
172
}


template <class Mesh>
void
DrawMeshT<Mesh>::rebuild()
{
  if (rebuild_ == REBUILD_NONE) return;

Christopher Tenter's avatar
Christopher Tenter committed
173
174
  if (!mesh_.n_vertices()) return;

175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
  // support for point clouds:
  if (mesh_.n_vertices() && mesh_.n_faces() == 0)
  {
    if (mesh_.n_vertices() > numVerts_)
    {
      delete [] vertexMap_; vertexMap_ = 0;
      delete [] invVertexMap_; invVertexMap_ = 0;
      delete [] vertices_; vertices_ = 0;
      delete [] verticesTmp_; verticesTmp_ = 0;

      numVerts_ = mesh_.n_vertices();
      vertices_ = new Vertex[numVerts_];
      verticesTmp_ = new Vertex[numVerts_];
    }

    numVerts_ = mesh_.n_vertices();

    // read all vertices
    for (unsigned int i = 0; i < numVerts_; ++i)
      readVertex(vertices_ + i,
                 mesh_.vertex_handle(i), 
                 (typename Mesh::HalfedgeHandle)(-1), 
                 (typename Mesh::FaceHandle)(-1));

    createVBO();

    return;
  }



  unsigned int maxFaceVertCount = 0;
  unsigned int newTriCount = countTris(&maxFaceVertCount);
  
  int bTriangleRebuild = 0; // what should be rebuild?
  int bVertexRebuild = 0;

  if (newTriCount > numTris_)
  {
    // index buffers too small
    // resize here
    delete [] indices_;
    delete [] indicesTmp_;
    delete [] triToFaceMap_;

220
    if (ibo_) glDeleteBuffers(1, &ibo_);
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
    ibo_ = 0;

    numTris_ = newTriCount;

    triToFaceMap_ = new unsigned int[numTris_];
    indices_ = new unsigned int[numTris_ * 3];
    indicesTmp_ = new unsigned int[numTris_ * 3];

    bTriangleRebuild = 1;
  }

  if (prevNumFaces_ != mesh_.n_faces())
  {
    bTriangleRebuild = 1;
    prevNumFaces_ = mesh_.n_faces();
  }

  if (prevNumVerts_ != mesh_.n_vertices())
  {
    if (prevNumVerts_ < mesh_.n_vertices())
    {
      // resize inverse vertex map
      delete [] invVertexMap_;
      invVertexMap_ = new unsigned int[mesh_.n_vertices()];
    }

    bVertexRebuild = 1;
    bTriangleRebuild = 1; // this may have caused changes in the topology!
    prevNumVerts_ = mesh_.n_vertices();
  }

  // support faster update by only updating vertices
  if (!bTriangleRebuild && !bVertexRebuild && rebuild_ == REBUILD_GEOMETRY)
  {
    // only update vertices, i.e. update values of vertices
    
    for (unsigned int i = 0; i < numVerts_; ++i)
    {
      unsigned int MeshHalfedge = vertexMap_[i];

//      Mesh::VertexHandle vh = mesh_.vertex_handle(MeshVertex);

      // just pick one face, srews up face colors here so color updates need a full rebuild
      typename Mesh::HalfedgeHandle hh = mesh_.halfedge_handle(MeshHalfedge);
      typename Mesh::VertexHandle vh = mesh_.to_vertex_handle(hh);
      typename Mesh::FaceHandle fh = mesh_.face_handle(hh);

      readVertex(vertices_ + i, vh, hh, fh);
    }

    createVBO();

    rebuild_ = REBUILD_NONE;
    return;
  }


  std::vector<unsigned int> tris(numTris_ * 3);


  //////////////////////////////////////////////////////////////////////////
  // convert from half_edge data structure to triangle index list


  numTris_ = convertToTriangleMesh(&tris[0], maxFaceVertCount);

  //////////////////////////////////////////////////////////////////////////
  // process vertices
  //  1. one vertex per triangle corner
  //  2. weld equal vertices

  unsigned int newNumVerts = 0;
  std::vector<Vertex> tmpVertexBuffer(3 * numTris_); // pre vertex welding
  std::vector<Vertex> dstVertexBuffer(3 * numTris_); // post vertex welding

  unsigned int* pVertexRemap = new unsigned int[3 * numTris_]; // keeps track of vertex origin (per-vertex attributes)

  createBigVertexBuf(&tmpVertexBuffer[0], pVertexRemap, &tris[0]);


  // minimize vertex buffer
  unsigned int* pTmpVertexRemap = new unsigned int[3 * numTris_];

Jan Möbius's avatar
Jan Möbius committed
304
  std::list< std::pair<unsigned int, unsigned int> > duplicatesMap;
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358

  newNumVerts = weldVertices(&dstVertexBuffer[0],
    &tmpVertexBuffer[0], &tris[0], &pTmpVertexRemap[0], pVertexRemap, duplicatesMap);

  std::swap(pTmpVertexRemap, pVertexRemap);
  delete [] pTmpVertexRemap; pTmpVertexRemap = 0;


  // end-of mesh extraction

  if (numVerts_ < newNumVerts)
  {
    // per vertex buffers too small
    delete [] vertices_;
    delete [] verticesTmp_;
    delete [] vertexMap_;
//    delete [] m_pVerticesC;

    numVerts_ = newNumVerts;

    vertices_ = new Vertex[numVerts_];
    verticesTmp_ = new Vertex[numVerts_];
    vertexMap_ = new unsigned int[numVerts_];
  }

 

  //////////////////////////////////////////////////////////////////////////
  // sort triangles by material

  sortTrisByMaterial(indices_, &tris[0]);

  //////////////////////////////////////////////////////////////////////////
  // optimize vcache
  //  by material subset

  // index buffer first

  optimizeTris(indices_, indices_);
  optimizeVerts(vertices_, &dstVertexBuffer[0], indices_, pVertexRemap);


  delete [] pVertexRemap;


  //////////////////////////////////////////////////////////////////////////
  // create the inverse vertex map

  for (unsigned int i = 0; i < numVerts_; ++i)
  {
    OpenMesh::HalfedgeHandle hh = mesh_.halfedge_handle(vertexMap_[i]);
    invVertexMap_[mesh_.to_vertex_handle(hh).idx()] = i;
  }

Jan Möbius's avatar
Jan Möbius committed
359
  std::list< std::pair<unsigned int, unsigned int> >::iterator duplIt;
360
361
362
363
364
365
366
367
368
369
370
371
372
  for (duplIt = duplicatesMap.begin(); duplIt != duplicatesMap.end(); ++duplIt)
  {
    unsigned int idx = invVertexMap_[duplIt->second]; // final vertex index in DrawMesh

    invVertexMap_[duplIt->first] = idx;
  }

  //////////////////////////////////////////////////////////////////////////
  // copy to GPU

  createVBO();
  createIBO();

373
  bVBOinHalfedgeNormalMode_ = halfedgeNormalMode_;
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437

  rebuild_ = REBUILD_NONE;

  // picking buffers update
}


template <class Mesh>
unsigned int
DrawMeshT<Mesh>::convertToTriangleMesh(unsigned int* _dstIndexBuf, unsigned int _maxFaceVertexCount)
{
  unsigned int triCounter = 0;
  unsigned int indexCounter = 0;

  unsigned int* pFaceVerts = new unsigned int[_maxFaceVertexCount];

  for (unsigned int i = 0; i < mesh_.n_faces(); ++i)
  {
    typename Mesh::FaceHandle fh =  mesh_.face_handle(i);
    // convert this face to triangles

	  typename Mesh::HalfedgeHandle hh_start = mesh_.halfedge_handle(fh);
 
  	// count vertices
  	unsigned int nPolyVerts = 0;

    // read all vertex indices of this face
    for (typename Mesh::FaceHalfedgeIter hh_it = mesh_.fh_iter(fh); hh_it; ++hh_it )
      pFaceVerts[nPolyVerts++] = mesh_.to_vertex_handle(hh_it).idx();

    //////////////////////////////////////////////////////////////////////////
    // convert to triangles

    triToFaceMap_[triCounter++] = i;
    for (int k = 0; k < 3; ++k) _dstIndexBuf[indexCounter++] = pFaceVerts[k];

    //  trivial fanning

    for (unsigned int k = 3; k < nPolyVerts; ++k)
    {
      triToFaceMap_[triCounter++] = i;

      _dstIndexBuf[indexCounter++] = pFaceVerts[0];
      _dstIndexBuf[indexCounter++] = pFaceVerts[k-1];
      _dstIndexBuf[indexCounter++] = pFaceVerts[k];
    }
  }

  delete [] pFaceVerts;

  return triCounter;
}

template <class Mesh>
void
DrawMeshT<Mesh>::readVertex(Vertex* _pV,
                            typename Mesh::VertexHandle _vh,
                            typename Mesh::HalfedgeHandle _hh,
                            typename Mesh::FaceHandle _fh)
{
  for (int m = 0; m < 3; ++m)
  {
    _pV->pos[m] = mesh_.point(_vh)[m];

438
    if (halfedgeNormalMode_ == 0 && mesh_.has_vertex_normals())
439
      _pV->n[m] = mesh_.normal(_vh)[m];
440
441
442
    else if (halfedgeNormalMode_ && 
      mesh_.has_halfedge_normals() && _hh != (typename Mesh::HalfedgeHandle)(-1))
      _pV->n[m] = mesh_.normal(_hh)[m];
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    else _pV->n[m] = 0.0f;

    if (m < 2)
    {
      if (mesh_.has_halfedge_texcoords2D())
      {
        if (_hh != (typename Mesh::HalfedgeHandle)(-1))
          _pV->tex[m] = mesh_.texcoord2D(_hh)[m];
      }
      else _pV->tex[m] = 0.0f;
    }
  }
  
  // per face & per vertex color
  unsigned int byteCol[2];
  for (int col = 0; col < 2; ++col)
  {
460
    typename Mesh::Color vecCol(255, 255, 255, 255);
461

462
    if (col == 0 && mesh_.has_vertex_colors()) vecCol = OpenMesh::color_cast<Vec4uc,typename Mesh::Color>(mesh_.color(_vh));
463
464
465
    if ((_fh != (typename Mesh::FaceHandle)(-1)))
    {
      if (col == 1 && mesh_.has_face_colors() && _fh.idx() >= 0) 
466
        vecCol = OpenMesh::color_cast<Vec4uc,typename Mesh::Color>(mesh_.color(_fh));
467
468
469
470
471
472
    }

    // OpenGL color format: A8B8G8R8
    byteCol[col] = (unsigned char)(vecCol[0]);
    byteCol[col] |= ((unsigned char)(vecCol[1])) << 8;
    byteCol[col] |= ((unsigned char)(vecCol[2])) << 16;
473
474
    byteCol[col] |= ((unsigned char)(vecCol[3])) << 24;
    //byteCol[col] |= 0xFF << 24; // if no alpha channel
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
  }

 _pV->vcol = byteCol[0];
//  _pV->vcol = 0xFFFF0000; // blue,  debug
 _pV->fcol = byteCol[1];
//  pV->fcol = 0xFF00FF00; // green, debug
}

template <class Mesh>
void
DrawMeshT<Mesh>::createBigVertexBuf(Vertex* _dstVertexBuf,
                                    unsigned int* _dstVertexMap,
                                    const unsigned int* _indexBuf)
{
  // fill 3 * NumTris vertex buffer
  for (unsigned int i = 0; i < numTris_; ++i)
  {
    typename Mesh::FaceHandle fh = mesh_.face_handle(triToFaceMap_[i]);

    for (int k = 0; k < 3; ++k)
    {
      typename Mesh::VertexHandle vh = mesh_.vertex_handle(_indexBuf[i * 3 + k]);

      // find corresponding halfedge and get per face attributes
      typename Mesh::HalfedgeHandle hh;

      for (typename Mesh::FaceHalfedgeIter hh_it = mesh_.fh_iter(fh); hh_it; ++hh_it )
      {
        if (mesh_.to_vertex_handle(hh_it).idx() == vh.idx())
        {
          hh = hh_it;
          break;
        }
      }

      _dstVertexMap[i * 3 + k] = hh.idx();


      Vertex* pV = _dstVertexBuf + i * 3 + k;

      readVertex(pV, vh, hh, fh);
    }
  }
}

template <class Mesh>
unsigned int 
DrawMeshT<Mesh>::weldVertices(Vertex* _dstVertexBuf,
                              const Vertex* _srcVertexBuf,
                              unsigned int* _dstIndexBuf, 
                              unsigned int* _dstVertexMap,
                              const unsigned int* _srcVertexMap,
Jan Möbius's avatar
Jan Möbius committed
527
                              std::list< std::pair<unsigned int, unsigned int> >& _duplicatesMap)
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
{
  unsigned int newCount = 0;
  unsigned int hashSize = intNextPowerOfTwo(3 * numTris_);

  // hash table + linked list for collision check
  std::vector<unsigned int> hashTable(hashSize + 3 * numTris_);
  unsigned int* pNext = &hashTable[hashSize];

  memset(&hashTable[0], 0xFFFFFFFF, hashSize * sizeof(unsigned int));

  for (unsigned int i = 0; i < 3 * numTris_; ++i)
  {
    const Vertex* pV = _srcVertexBuf + i;

    // float3 hash function, hash by position only
    unsigned int* ui = (unsigned int*)pV->pos;
    unsigned int f = (ui[0] - ui[1]*13 + ui[2]*23)&0x7ffffE00; // make unsigned, discard some high precision mantissa bits
    unsigned int hashVal = ((f>>22)^(f>>12)^(f)) & (hashSize - 1); //  modulo hashSize

    // check previous entries

    unsigned int offset = hashTable[hashVal];

    while ((offset != 0xFFFFFFFF) && (!_dstVertexBuf[offset].equals(*pV)))
      offset = pNext[offset];

    if (offset == 0xFFFFFFFF)
    {
      // create new vertex entry here:
      _dstIndexBuf[i] = newCount;

      _dstVertexMap[newCount] = _srcVertexMap[i];

      memcpy(&_dstVertexBuf[newCount], pV, sizeof(Vertex));

      pNext[newCount] = hashTable[hashVal];

      hashTable[hashVal] = newCount++;
    }
    else // duplicate vertex found, use previous index
    {
      _dstIndexBuf[i] = offset;


      // INCOMPLETE INVERSE VERTEX MAP FIX
      // create a multimap to get all pairs of duplicates
      typename Mesh::HalfedgeHandle h1 = mesh_.halfedge_handle(_dstVertexMap[offset]);
      typename Mesh::HalfedgeHandle h2 = mesh_.halfedge_handle(_srcVertexMap[i]);

      unsigned int idx1 = mesh_.to_vertex_handle(h1).idx();
      unsigned int idx2 = mesh_.to_vertex_handle(h2).idx();

      if (idx1 != idx2)
581
        _duplicatesMap.push_front(std::pair<unsigned int, unsigned int>(idx2, idx1));
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
    }
  }

  // nearly degenerate triangle fix
  if (newCount < 3)
  {
    // copy input buffer
    newCount = 3 * numTris_;
    memcpy(_dstVertexBuf, _srcVertexBuf, sizeof(Vertex) * newCount);
    for (unsigned int i = 0; i < newCount; ++i)
    {
      _dstIndexBuf[i] = i;
      _dstVertexMap[i] = _srcVertexMap[i];
    }
  }


  // PER-FACE-NORMAL FIX
  // welding is finished here, but we have to ensure that each
  // triangle has at least one unshared vertex
  //  this vertex must to be the last referenced vertex of the triangle
  //  when switching to flat-shading, this vertex holds the face normal

  // count # adjacent tris for each vertex
  unsigned int* pNumAdjTris = new unsigned int[newCount];
  memset(pNumAdjTris, 0, newCount * sizeof(unsigned int));

  unsigned int totalNumAdjTris = 0;

  for (unsigned int i = 0; i < numTris_; ++i)
  {
    for (unsigned int k = 0; k < 3; ++k)
    {
      ++pNumAdjTris[_dstIndexBuf[i * 3 + k]];
      ++totalNumAdjTris;
    }
  }

  // detect tris not owning a distinct vertex

  for (unsigned int t = 0; t < numTris_; ++t)
  {
    unsigned int unsharedVertex = 0xFFFFFFFF; // which vertex of this tri is unshared

    // count # shared vertices
    for (unsigned int i = 0; i < 3; ++i)
    {
      unsigned int V = _dstIndexBuf[t * 3 + i];

      if (pNumAdjTris[V] == 1)
      {
        unsharedVertex = V;
        break;
      }
    }

    if (unsharedVertex == 0xFFFFFFFF)
    {
      // this tri does not own a distinct vertex
      // add a seperate vertex for this triangle

      _dstVertexMap[newCount] = _dstVertexMap[_dstIndexBuf[t*3+2]];

      // optimization: only split when necessary, (no double split if NumAdjTris[V] = 2)
      --pNumAdjTris[_dstIndexBuf[t*3+2]];

      memcpy(&_dstVertexBuf[newCount], &_dstVertexBuf[_dstIndexBuf[t*3+2]], sizeof(Vertex));

      _dstIndexBuf[t*3+2] = newCount++;
    }
    else
    {
      // rotate references until the unshared vertex is the first one
      while (unsharedVertex != _dstIndexBuf[t * 3 + 2])
      {
        unsigned int tri[] = {_dstIndexBuf[t*3], _dstIndexBuf[t*3+1], _dstIndexBuf[t*3+2]};

        _dstIndexBuf[t*3] = tri[1];
        _dstIndexBuf[t*3+1] = tri[2];
        _dstIndexBuf[t*3+2] = tri[0];
      }
    }
  }

  delete [] pNumAdjTris;


  return newCount;
}


template <class Mesh>
int
DrawMeshT<Mesh>::getTextureIDofTri(unsigned int _tri)
{
  OpenMesh::FPropHandleT< int > textureIndexProperty;
  if (mesh_.get_property_handle(textureIndexProperty, textureIndexPropertyName_))
    return mesh_.property(textureIndexProperty, mesh_.face_handle(triToFaceMap_[_tri]));
  
  if (mesh_.has_face_texture_index())
    return mesh_.texture_index(mesh_.face_handle(triToFaceMap_[_tri]));
  
  return 0;
}

template<class Mesh>
void
DrawMeshT<Mesh>::sortTrisByMaterial(unsigned int* _dstIndexBuf, const unsigned int* _srcIndexBuf)
{
  delete [] subsets_;
  subsets_ = 0;
  numSubsets_ = 0;

  unsigned int* pTmpTriToFaceMap = new unsigned int[numTris_];

  std::map<int, unsigned int> MatIDs; // map[matid] = first tri

  for (unsigned int i = 0; i < numTris_; ++i)
  {
    int texID = getTextureIDofTri(i);
    if (MatIDs.find(texID) == MatIDs.end())
      MatIDs[texID] = i;
  }

  numSubsets_ = MatIDs.size();
  subsets_ = new Subset[numSubsets_];

  std::map<int, unsigned int>::const_iterator it = MatIDs.begin();

  unsigned int lastIndexOffset = 0;

  for (unsigned int i = 0; it != MatIDs.end(); ++i, ++it)
  {
    subsets_[i].materialID = it->first;

    // rearrange by subset chunks

    subsets_[i].startIndex = lastIndexOffset;
    subsets_[i].numTris = 0;

    for (unsigned int k = it->second; k < numTris_; ++k)
    {
      if (getTextureIDofTri(k) == subsets_[i].materialID)
      {
        pTmpTriToFaceMap[lastIndexOffset / 3] = triToFaceMap_[k];

        for (int v = 0; v < 3; ++v)
          _dstIndexBuf[lastIndexOffset++] = _srcIndexBuf[k * 3 + v];
      }
    }

    subsets_[i].numTris = (lastIndexOffset - subsets_[i].startIndex) / 3;

  }

  std::swap(triToFaceMap_, pTmpTriToFaceMap);

  delete [] pTmpTriToFaceMap;
}

template<class Mesh>
void
DrawMeshT<Mesh>::optimizeTris(unsigned int* _dstIndexBuf, unsigned int* _srcIndexBuf)
{
  unsigned int* pTmpTriToFaceMap = new unsigned int[numTris_];
  for (unsigned int i = 0; i < numSubsets_; ++i)
  {
    Subset* pSubset = subsets_ + i;

    GPUCacheOptimizerTipsify copt(24, pSubset->numTris, numVerts_, 4, _srcIndexBuf + pSubset->startIndex);
    copt.WriteIndexBuffer(4, _dstIndexBuf + pSubset->startIndex);

    // apply changes to trimap
    const unsigned int StartTri = pSubset->startIndex/3;
    for (unsigned int k = 0; k < pSubset->numTris; ++k)
    {
      unsigned int SrcTri = copt.GetTriangleMap()[k];
      pTmpTriToFaceMap[k + StartTri] = triToFaceMap_[SrcTri + StartTri];
    }
  }
  std::swap(triToFaceMap_, pTmpTriToFaceMap);
  delete [] pTmpTriToFaceMap;
}


template <class Mesh>
void
DrawMeshT<Mesh>::optimizeVerts(Vertex* _dstVertexBuf,
                               const Vertex* _srcVertexBuf,
                               unsigned int* _inOutIndexBuf, 
                               const unsigned int* _srcVertexMap)
{
  // vertices
  std::vector<unsigned int> vertexRemap(numVerts_);
  GPUCacheOptimizer::OptimizeVertices(numTris_, numVerts_, 4, _inOutIndexBuf, &vertexRemap[0]);

  for (unsigned int i = 0; i < numTris_ * 3; ++i) indices_[i] = vertexRemap[indices_[i]];

  // isolated vertices get sorted out here
  // it's crucial to set numVerts_ to the # referenced verts, to avoid problems 
  // with picking functions

  unsigned int numIsolates = 0;

  for (unsigned int i = 0; i < numVerts_; ++i)
  {
    if (vertexRemap[i] < numVerts_)
    {
      memcpy(_dstVertexBuf + vertexRemap[i], _srcVertexBuf + i, sizeof(Vertex));

//      vertexMap_[i] = _srcVertexMap[i];
      vertexMap_[vertexRemap[i]] = _srcVertexMap[i];
    }
    else
      ++numIsolates; // isolated vertex
  }

  numVerts_ -= numIsolates;
}


template <class Mesh>
void
DrawMeshT<Mesh>::createVBO()
{
  // data read from vertices_
  if (!vbo_)
    glGenBuffersARB(1, &vbo_);

811
  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, vbo_);
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826

  if (!flatMode_ && textureMode_)
  {
    glBufferDataARB(GL_ARRAY_BUFFER_ARB, numVerts_ * sizeof(Vertex), vertices_, GL_STATIC_DRAW_ARB);
    bVBOinFlatMode_ = 0;
  }
  else
  {
    // use per face normals
    memcpy(verticesTmp_, vertices_, sizeof(Vertex) * numVerts_);

    if (flatMode_)
    {
      for (unsigned int i = 0; i < numTris_; ++i)
      {
827
828
        // get face normal
        ACG::Vec3d n = mesh_.normal(mesh_.face_handle(triToFaceMap_[i]));
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854

        // store face normal in last tri vertex
        for (unsigned int k = 0; k < 3; ++k)
        {
          verticesTmp_[indices_[i*3+2]].n[k] = n[k];
        }
      }
      bVBOinFlatMode_ = 1;
    }
    if (!textureMode_)
    {
      for (unsigned int i = 0; i < numVerts_; ++i)
      {
        for (int k = 0; k < 2; ++k)
        {
          verticesTmp_[i].tex[k] = mesh_.texcoord2D(
            mesh_.to_vertex_handle(mesh_.halfedge_handle(vertexMap_[i])))[k];
        }
      }
      bVBOinHalfedgeTexMode_ = 0;
    }

    glBufferDataARB(GL_ARRAY_BUFFER_ARB, numVerts_ * sizeof(Vertex), verticesTmp_, GL_STATIC_DRAW_ARB);

  }

855
  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
856
857
858
859
860
861
862
863
864
865
866
867
868
}

template <class Mesh>
void
DrawMeshT<Mesh>::createIBO()
{
  // data read from indices_

  // create triangle index buffer

  if (!ibo_)
    glGenBuffersARB(1, &ibo_);

869
  ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, ibo_);
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910

  indexType_ = GL_UNSIGNED_INT;
  if (numVerts_ <= 0xFFFF)
  {
    // use 2 byte indices
    unsigned short* pwIndices = (unsigned short*)indicesTmp_;
    indexType_ = GL_UNSIGNED_SHORT;

    for (unsigned int i = 0; i < numTris_ * 3; ++i)
      pwIndices[i] = (unsigned short)indices_[i];

    glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, numTris_ * 3 * sizeof(unsigned short), pwIndices, GL_STATIC_DRAW_ARB);
  }
  else
    glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, numTris_ * 3 * sizeof(unsigned int), indices_, GL_STATIC_DRAW_ARB);


  // line index buffer:
  if (mesh_.n_edges())
  {
    unsigned int* pLineBuffer = new unsigned int[mesh_.n_edges() * 2];

    if (!lineIBO_)
      glGenBuffersARB(1, &lineIBO_);

    for (unsigned int i = 0; i < mesh_.n_edges(); ++i)
    {
      OpenMesh::HalfedgeHandle hh = mesh_.halfedge_handle(mesh_.edge_handle(i), 0);

      if (indexType_ == GL_UNSIGNED_SHORT)
      {
        ((unsigned short*)pLineBuffer)[2*i] = (unsigned short)invVertexMap_[mesh_.from_vertex_handle(hh).idx()];
        ((unsigned short*)pLineBuffer)[2*i+1] = (unsigned short)invVertexMap_[mesh_.to_vertex_handle(hh).idx()];
      }
      else
      {
        pLineBuffer[2*i] = invVertexMap_[mesh_.from_vertex_handle(hh).idx()];
        pLineBuffer[2*i+1] = invVertexMap_[mesh_.to_vertex_handle(hh).idx()];
      }
    }

911
    ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER, lineIBO_);
912
913
914
915
916
917
918
919
920
921
922
923
924
925

    // 2 or 4 byte indices:
    if (indexType_ == GL_UNSIGNED_SHORT)
      glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 
                   mesh_.n_edges() * 2 * sizeof(unsigned short), 
                   pLineBuffer, GL_STATIC_DRAW_ARB);
    else
      glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 
                   mesh_.n_edges() * 2 * sizeof(unsigned int),
                   pLineBuffer, GL_STATIC_DRAW_ARB);

    delete [] pLineBuffer;
  }

926
  ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
}

template <class Mesh>
DrawMeshT<Mesh>::~DrawMeshT(void)
{
  delete [] indices_;
  delete [] indicesTmp_;
  delete [] vertices_;
  delete [] verticesTmp_;
//  delete [] m_pVerticesC;

  delete [] subsets_;

  delete [] vertexMap_;

  delete [] triToFaceMap_;

  delete [] invVertexMap_;

946
947
948
  delete vertexDeclFCol_;
  delete vertexDeclVCol_;

949
950
951
952
953
  if (vbo_) glDeleteBuffersARB(1, &vbo_);
  if (ibo_) glDeleteBuffersARB(1, &ibo_);
  if (lineIBO_) glDeleteBuffersARB(1, &lineIBO_);
}

954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000


template <class Mesh>
unsigned int DrawMeshT<Mesh>::getMemoryUsage(bool _printReport)
{
  unsigned int res = 0;
  unsigned int sysBufSize = 0;

  // index buffer
  if (indices_)
    sysBufSize += numTris_ * 3 * 4;

  // vertex buffer
  if (vertices_)
    sysBufSize += sizeof(Vertex) * numVerts_;

  // temp buffers
  if (indicesTmp_)
    sysBufSize += numTris_ * 3 * 4;

  if (verticesTmp_)
    sysBufSize += sizeof(Vertex) * numVerts_;

  
  
  res += sysBufSize;

  // mappings
  unsigned int mapsSize = 0;
 
  if (vertexMap_)
    mapsSize += numVerts_ * 4;

  if (triToFaceMap_)
    res += numTris_ * 4;

  if (invVertexMap_)
    res += mesh_.n_vertices() * 4;

  res += mapsSize;


  // picking buffers
  unsigned int pickBufSize = 0;

  pickBufSize += pickVertBuf_.capacity() * sizeof(ACG::Vec3f);
  pickBufSize += pickVertColBuf_.capacity() * sizeof(ACG::Vec4uc);
For faster browsing, not all history is shown. View entire blame