DrawMeshT.cc 77.6 KB
Newer Older
1
2
3
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
Jan Möbius's avatar
Jan Möbius committed
4
5
6
7
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
8
9
 *                                                                           *
 *---------------------------------------------------------------------------*
Jan Möbius's avatar
Jan Möbius committed
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
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. 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.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder 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 HOLDER *
 * 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.              *
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 *                                                                           *
\*===========================================================================*/

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

#define ACG_DRAW_MESH_TCC

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

#include "DrawMesh.hh"

56
#include <ACG/GL/gl.hh>
57
58
59
60
61
62
63
64
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
#include <ACG/Geometry/GPUCacheOptimizer.hh>
#include <ACG/GL/VertexDeclaration.hh>
#include <ACG/GL/ShaderCache.hh>
#include <cassert>
#include <cmath>
#include <vector>
#include <map>
#include <cstring>
#include <fstream>

#ifdef USE_OPENMP
#include <omp.h>
#endif

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

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


namespace ACG
{

template <class Mesh>
DrawMeshT<Mesh>::DrawMeshT(Mesh& _mesh)
:  mesh_(_mesh),
   rebuild_(REBUILD_NONE),
   prevNumFaces_(0), prevNumVerts_(0),
   colorMode_(1),
   curVBOColorMode_(1),
   flatMode_(0), bVBOinFlatMode_(0),
   textureMode_(1), bVBOinHalfedgeTexMode_(1),
   halfedgeNormalMode_(0), bVBOinHalfedgeNormalMode_(0),
   invVertexMap_(0),
   offsetPos_(0), offsetNormal_(20), offsetTexc_(12), offsetColor_(32),
   textureIndexPropertyName_("Not Set"),
   perFaceTextureCoordinatePropertyName_("Not Set"),
Christopher Tenter's avatar
Christopher Tenter committed
94
   updateFullVBO_(true),
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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
220
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
   updatePerEdgeBuffers_(1),
  updatePerHalfedgeBuffers_(1)
{

  pickVertexMethod_ = 1;
  pickVertexShader_ = 0;

  pickFaceShader_ = 0;
  pickEdgeShader_ = 0;

  createVertexDeclaration();
}

template<class Mesh>
template<class T>
const void* DrawMeshT<Mesh>::testMeshPropertyTypeT( const OpenMesh::BaseProperty* _prop, unsigned int* _outSize ) const
{
  if (_outSize)
    *_outSize = 0;
  const void* dataPtr = 0;

  // rtti - detect type of property from openmesh via dynamic_cast
  typedef OpenMesh::PropertyT< T > Prop1;
  typedef OpenMesh::PropertyT< OpenMesh::VectorT<T, 1> > PropVec1;
  typedef OpenMesh::PropertyT< OpenMesh::VectorT<T, 2> > PropVec2;
  typedef OpenMesh::PropertyT< OpenMesh::VectorT<T, 3> > PropVec3;
  typedef OpenMesh::PropertyT< OpenMesh::VectorT<T, 4> > PropVec4;

  const Prop1* p1 = dynamic_cast<const Prop1*>(_prop);
  const PropVec1* pv1 = dynamic_cast<const PropVec1*>(_prop);
  const PropVec2* pv2 = dynamic_cast<const PropVec2*>(_prop);
  const PropVec3* pv3 = dynamic_cast<const PropVec3*>(_prop);
  const PropVec4* pv4 = dynamic_cast<const PropVec4*>(_prop);
  
  if (p1 || pv1)
  {
    if (_outSize)
      *_outSize = 1;
    if (p1)
      dataPtr = p1->data();
    else
      dataPtr = pv1->data();
  }
  else if (pv2)
  {
    if (_outSize)
      *_outSize = 2;
    dataPtr = pv2->data();
  }
  else if (pv3)
  {
    if (_outSize)
      *_outSize = 3;
    dataPtr = pv3->data();
  }
  else if (pv4)
  {
    if (_outSize)
      *_outSize = 4;
    dataPtr = pv4->data();
  }

  return dataPtr;
}


template<class Mesh>
const void* DrawMeshT<Mesh>::getMeshPropertyType( OpenMesh::BaseProperty* _prop, GLuint* _outType, unsigned int* _outSize ) const
{
  const void* dataPtr = 0;

  // try float
  dataPtr = testMeshPropertyTypeT<float>(_prop, _outSize);
  if (dataPtr)
  {
    if (_outType) *_outType = GL_FLOAT;
    return dataPtr;
  }

  // try byte
  dataPtr = testMeshPropertyTypeT<char>(_prop, _outSize);
  if (dataPtr)
  {
    if (_outType) *_outType = GL_BYTE;
    return dataPtr;
  }

  // try ubyte
  dataPtr = testMeshPropertyTypeT<unsigned char>(_prop, _outSize);
  if (dataPtr)
  {
    if (_outType) *_outType = GL_UNSIGNED_BYTE;
    return dataPtr;
  }

  // try double
  dataPtr = testMeshPropertyTypeT<double>(_prop, _outSize);

  if (dataPtr)
  {
    if (_outType) *_outType = GL_DOUBLE;
    return dataPtr;
  }

  // try int
  dataPtr = testMeshPropertyTypeT<int>(_prop, _outSize);

  if (dataPtr)
  {
    if (_outType) *_outType = GL_INT;
    return dataPtr;
  }

  // try uint
  dataPtr = testMeshPropertyTypeT<unsigned int>(_prop, _outSize);

  if (dataPtr)
  {
    if (_outType) *_outType = GL_UNSIGNED_INT;
    return dataPtr;
  }

  // try short
  dataPtr = testMeshPropertyTypeT<short>(_prop, _outSize);

  if (dataPtr)
  {
    if (_outType) *_outType = GL_SHORT;
    return dataPtr;
  }

  // try ushort
  dataPtr = testMeshPropertyTypeT<unsigned short>(_prop, _outSize);

  if (dataPtr)
  {
    if (_outType) *_outType = GL_UNSIGNED_SHORT;
    return dataPtr;
  }


  // unknown data type
  if (_outSize)
    *_outSize = 0;

  if (_outType)
    *_outType = 0;

  return 0;
}



template<class Mesh>
class DrawMeshFaceInput : public MeshCompilerFaceInput
{

public:

  DrawMeshFaceInput(Mesh& _mesh) :
  mesh_(_mesh)
  {
  };

  // map[attrID] -> use per halfedge/vertex attribute (true/false)
  std::vector<int> attributeStoredPerHalfedge_;


Jan Möbius's avatar
Jan Möbius committed
263
  int getNumFaces() const { return mesh_.n_faces(); }
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
304
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456

  // compute number of indices later automatically
  int getNumIndices() const { return 0; };

  /** Get number of vertices per face.
   * @param _faceID face index
  */
  int getFaceSize(const int _faceID) const
  {
    return mesh_.valence( mesh_.face_handle(_faceID) );
  }

  /** Get a single vertex-index entry of a face.
   *
   * @param _faceID face index
   * @param _faceCorner vertex corner of the face
   * @param _attrID attribute channel 
   * @return index-data if successful, -1 otherwise
  */
  int getSingleFaceAttr(const int _faceID, const int _faceCorner, const int _attrID) const
  {
    const typename Mesh::FaceHandle fh =  mesh_.face_handle(_faceID);

    typename Mesh::ConstFaceHalfedgeIter fh_it = mesh_.cfh_iter(fh);

    // ========================================================================================
    // Optimization for triangular meshes (use previous halfedge to skip part of the iteration)
    // ========================================================================================
    if ( mesh_.is_trimesh()) {
      if ( attributeStoredPerHalfedge_[_attrID] != 0 ) {
        switch (_faceCorner) {
          case 0 : return fh_it->idx();
          break;
          case 1 : return (mesh_.next_halfedge_handle(*fh_it)).idx();
          break;
          case 2 : return (mesh_.prev_halfedge_handle(*fh_it)).idx();
          break;
          default :   std::cerr << " Index error!" << _faceCorner << std::endl; return -1;
          break;
        }
      } else {
        switch (_faceCorner) {
          case 0 : return mesh_.to_vertex_handle(*fh_it).idx();
          break;
          case 1 : return (mesh_.to_vertex_handle(mesh_.next_halfedge_handle(*fh_it))).idx();
          break;
          case 2 : return (mesh_.to_vertex_handle(mesh_.prev_halfedge_handle(*fh_it))).idx();
          break;
          default :   std::cerr << " Index error!" << _faceCorner << std::endl; return -1;
          break;
        }
      }
    }

    // ========================================================================================
    // Poly Meshes
    // ========================================================================================
    if ( attributeStoredPerHalfedge_[_attrID] != 0 ) {

      for (int i = 0; fh_it.is_valid() && i <= _faceCorner; ++fh_it, ++i )
        if (i == _faceCorner)
          return fh_it->idx();

    } else {

      for (int i = 0; fh_it.is_valid() && i <= _faceCorner; ++fh_it, ++i )
        if (i == _faceCorner)
          return mesh_.to_vertex_handle(*fh_it).idx();

    }

    // Not found -> return -1 as error
    return -1;
  }

  /** Get an index buffer of a face for a specific attribute channel.
   * @param _faceID face index
   * @param _attrID attribute channel
   * @param _out pointer to output buffer, use getFaceSize(_faceID) to get the size needed to store face data
   * @return true if successful, false otherwise
  */
  bool getFaceAttr(const int _faceID, const int _attrID, int* _out) const
  {
    const typename Mesh::FaceHandle fh =  mesh_.face_handle(_faceID);

    const bool usePerHalfedge = (attributeStoredPerHalfedge_[_attrID] != 0);

    // read all vertex indices of this face
    typename Mesh::ConstFaceHalfedgeIter hh_it = mesh_.cfh_iter(fh);
    for (int i = 0; hh_it.is_valid(); ++hh_it, ++i )
    {
      _out[i] = usePerHalfedge ? hh_it->idx() : mesh_.to_vertex_handle(*hh_it).idx();
    }

    return true;
  }

  /** Get an index buffer of a face for a specific attribute channel.
   * @param _faceID face index
   * @param _attrID attribute channel
   * @return array data of size "getFaceSize(_faceID)", allowed to return 0 when array data not permanently available in memory
  */
  int* getFaceAttr(const int _faceID, const int _attrID) const
  {
    // cannot be implemented with OpenMesh data structure
    return 0;
  }



  int getVertexAdjCount(const int _vertexID) const
  {
    const typename Mesh::VertexHandle vh =  mesh_.vertex_handle(_vertexID);

    int counter = 0;

    // read all vertex indices of this face
    typename Mesh::ConstVertexFaceIter adj_it = mesh_.cvf_iter(vh);
    for (;adj_it.is_valid(); ++adj_it)
      ++counter;

    return counter;
  }

  int getVertexAdjFace(const int _vertexID, const int _k) const
  {
    const typename Mesh::VertexHandle vh =  mesh_.vertex_handle(_vertexID);

    // read all vertex indices of this face
    typename Mesh::ConstVertexFaceIter adj_it = mesh_.cvf_iter(vh);
    for (int i = 0; adj_it.is_valid() && i < _k; ++adj_it, ++i);

    return adj_it->idx();
  }

private:
  Mesh& mesh_;
};



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

  if (!mesh_.n_vertices())
  {
    numVerts_ = 0;
    numTris_ = 0;
    return;
  }



  // --------------------------------------------
  // debug - request properties
/*
  if (additionalElements_.empty() && (mesh_._get_hprop("inTangent") || mesh_._get_vprop("inTangent")))
  {
    //     VertexProperty tmp;
    //     tmp.name_ = "inTangent";
    //     tmp.source_ = 0;
    // 
    //     additionalElements_.push_back(tmp);

//    scanVertexShaderForInput( "c:/dbg/nm_VS.tpl" );
    scanVertexShaderForInput( "/home/tenter/dbg/nm_VS.tpl" );
  }
*/
  // --------------------------------------------

  // todo: check if vertex layout has been changed and eventually force a full rebuild


  // update layout declaration
  createVertexDeclaration();

  // support for point clouds:
  if (mesh_.n_vertices() && mesh_.n_faces() == 0)
  {
    if (mesh_.n_vertices() > numVerts_)
    {
      delete [] invVertexMap_; 
      invVertexMap_ = 0;
    }
    numVerts_ = mesh_.n_vertices();
    vertices_.resize(numVerts_ * vertexDecl_->getVertexStride());

    // read all vertices
    for (size_t i = 0; i < numVerts_; ++i)
      readVertex(i,
Jan Möbius's avatar
Jan Möbius committed
457
                 mesh_.vertex_handle(static_cast<unsigned int>(i)),
458
459
460
461
462
463
464
465
                 (typename Mesh::HalfedgeHandle)(-1), 
                 (typename Mesh::FaceHandle)(-1));

    createVBO();
    rebuild_ = REBUILD_NONE;
    return;
  }

466
  invalidateFullVBO();
467
468
469
470
471
472
473
474
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


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

  if (newTriCount > numTris_)
  {
    // index buffer too small
    deleteIbo();

    numTris_ = newTriCount;

    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 (do a complete update if the textures have to be rebuild)
  if (!bTriangleRebuild && !bVertexRebuild && (rebuild_ & REBUILD_GEOMETRY) && !(rebuild_ & REBUILD_TEXTURES))
  {
    // only update vertices, i.e. update values of vertices

    #ifndef WIN32
      #ifdef USE_OPENMP
        #pragma omp parallel for
      #endif
    #endif
Jan Möbius's avatar
Jan Möbius committed
516
    for (size_t i = 0; i < numVerts_; ++i)
517
518
519
520
521
522
523
524
525
526
527
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
    {
      // just pick one face, srews up face colors here so color updates need a full rebuild
      const typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);
      typename Mesh::VertexHandle   vh(-1);
      typename Mesh::FaceHandle     fh(-1);

      if (hh.is_valid())
      {
        vh = mesh_.to_vertex_handle(hh);
        fh = mesh_.face_handle(hh);
      }
      else
      {
        int f_id, c_id;
        int posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);
        vh = mesh_.vertex_handle(posID);
      }

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

    createVBO();

    rebuild_ = REBUILD_NONE;
    return;
  }


  // full rebuild:
  delete meshComp_;
  meshComp_ = new MeshCompiler(*vertexDecl_);


  // search for convenient attribute indices
  int attrIDNorm = -1, attrIDPos = -1, attrIDTexC = -1;

  for (int i = 0; i < (int)meshComp_->getVertexDeclaration()->getNumElements(); ++i)
  {
    const VertexElement* e = meshComp_->getVertexDeclaration()->getElement(i);

    switch (e->usage_)
    {
    case VERTEX_USAGE_POSITION: attrIDPos = i; break;
    case VERTEX_USAGE_NORMAL: attrIDNorm = i; break;
    case VERTEX_USAGE_TEXCOORD: attrIDTexC = i; break;
    default: break;
    }
  }


  // pass face data to mesh compiler
  DrawMeshFaceInput<Mesh>* faceInput = new DrawMeshFaceInput<Mesh>(mesh_);
  faceInput->attributeStoredPerHalfedge_.resize(meshComp_->getVertexDeclaration()->getNumElements(), 0);
  faceInput->attributeStoredPerHalfedge_[attrIDPos]  = 0;
  faceInput->attributeStoredPerHalfedge_[attrIDNorm] = ( (halfedgeNormalMode_ && mesh_.has_halfedge_normals()) ? 1 : 0 );
  faceInput->attributeStoredPerHalfedge_[attrIDTexC] = ( mesh_.has_halfedge_texcoords2D() ? 1 : 0);

  // index source for custom attributes
  for (size_t i = 0; i < additionalElements_.size(); ++i)
  {
    const VertexProperty* prop = &additionalElements_[i];

    if (prop->declElementID_ >= 0)
      faceInput->attributeStoredPerHalfedge_[prop->declElementID_] = (prop->source_ == PROPERTY_SOURCE_HALFEDGE) ? 1 : 0;
  }

  meshComp_->setFaceInput(faceInput);

  // set textures
  for (unsigned int i = 0; i < mesh_.n_faces(); ++i)
    meshComp_->setFaceGroup(i, getTextureIDofFace(i));

  // pass vertex data to mesh compiler


  // points
  meshComp_->setVertices(mesh_.n_vertices(), mesh_.points(), 24, false, GL_DOUBLE, 3);
  
  // normals
596
  if (halfedgeNormalMode_ && mesh_.has_halfedge_normals())
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
    meshComp_->setNormals(mesh_.n_halfedges(), mesh_.property(mesh_.halfedge_normals_pph()).data(), 24, false, GL_DOUBLE, 3);
  else if (mesh_.has_vertex_normals())
    meshComp_->setNormals(mesh_.n_vertices(), mesh_.vertex_normals(), 24, false, GL_DOUBLE, 3);

  if (mesh_.has_halfedge_texcoords2D())
    meshComp_->setTexCoords(mesh_.n_halfedges(), mesh_.htexcoords2D(), 8, false, GL_FLOAT, 2);

  // add more requested custom attribtues to mesh compiler here..

  for (size_t i = 0; i < additionalElements_.size(); ++i)
  {
    VertexProperty* propDesc = &additionalElements_[i];

    if (propDesc->declElementID_ >= 0)
    {
      const VertexElement* el = vertexDecl_->getElement((unsigned int)propDesc->declElementID_);

      if (el->usage_ == VERTEX_USAGE_SHADER_INPUT)
      {
        // get openmesh property handle
        OpenMesh::BaseProperty* baseProp = 0;
        
        switch (propDesc->source_)
        {
        case PROPERTY_SOURCE_VERTEX: baseProp = mesh_._get_vprop(propDesc->name_); break;
        case PROPERTY_SOURCE_FACE: baseProp = mesh_._get_fprop(propDesc->name_); break;
        case PROPERTY_SOURCE_HALFEDGE: baseProp = mesh_._get_hprop(propDesc->name_); break;
        default: baseProp = mesh_._get_vprop(propDesc->name_); break;
        }

        if (baseProp)
        {
Jan Möbius's avatar
Jan Möbius committed
629
          size_t numAttribs = baseProp->n_elements();
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
          const void* attribData = propDesc->propDataPtr_; 

          meshComp_->setAttribVec( propDesc->declElementID_, numAttribs, attribData );
        }
        

      }
    }

    
  }


  // compile draw buffers
  meshComp_->build(true, true, true, true);


  // create inverse vertex map
  for (int i = 0; i < (int)mesh_.n_faces(); ++i)
  {
    typename Mesh::FaceHandle fh =  mesh_.face_handle(i);

    int corner = 0;

    for (typename Mesh::FaceHalfedgeIter hh_it = mesh_.fh_iter(fh); hh_it.is_valid(); ++hh_it )
    {
      int vertexId = mesh_.to_vertex_handle(*hh_it).idx();
      invVertexMap_[vertexId] = meshComp_->mapToDrawVertexID(i, corner++);
    }
  }


  // get vertex buffer
  numTris_ = meshComp_->getNumTriangles();
  numVerts_ = meshComp_->getNumVertices();

  vertices_.resize(numVerts_ * vertexDecl_->getVertexStride());
  meshComp_->getVertexBuffer(&vertices_[0]);

  // copy colors
  for (int i = 0; i < (int)numVerts_; ++i)
  {
    typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);

    unsigned int col = 0;

    if (hh.is_valid())
      col = getVertexColor(mesh_.to_vertex_handle(hh));
    else
    {
      // isolated vertex
      int f_id, c_id;
      int posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);
      col = getVertexColor( mesh_.vertex_handle(posID) );
    }

    writeColor(i, col);
  }

  // vbo stores per vertex colors
  curVBOColorMode_ = 1; 

  // copy face colors to provoking id
  if (colorMode_ == 2)
  {
    const int provokingId = meshComp_->getProvokingVertex();
    assert(provokingId >= 0 && provokingId < 3);

    for (int i = 0; i < (int)numTris_; ++i)
    {
      int idx = meshComp_->getIndex(i*3+provokingId);

      int faceId = meshComp_->mapToOriginalFaceID(i);
      unsigned int fcolor = getFaceColor(mesh_.face_handle(faceId));

      writeColor(idx, fcolor);
    }

#ifdef _DEBUG
    // debug check

    for (int i = 0; i < (int)numTris_; ++i)
    {
      int idx = meshComp_->getIndex(i*3+provokingId);

      int faceId = meshComp_->mapToOriginalFaceID(i);
      unsigned int fcolor = getFaceColor(mesh_.face_handle(faceId));

      unsigned int storedColor = *(unsigned int*)(&vertices_[idx * vertexDecl_->getVertexStride() + offsetColor_]);

      if (storedColor != fcolor)
      {
        std::cout << "warning: possibly found provoking vertex shared by more than one face, writing report to ../../meshcomp_provoking.txt" << std::endl;

        // could also be caused by multi-threading, where one thread calls rebuild() 
        // and the other thread updates face colors between previous for-loop and debug-check

        // check for errors
        meshComp_->dbgVerify("../../meshcomp_provoking.txt");
        
        break; // verify and dump report only once
      }
    }
#endif // _DEBUG

    curVBOColorMode_ = colorMode_;
  }


 

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

  createVBO();
  createIBO();

  bVBOinHalfedgeNormalMode_ = halfedgeNormalMode_;

  rebuild_ = REBUILD_NONE;
}


template <class Mesh>
void
Jan Möbius's avatar
Jan Möbius committed
755
DrawMeshT<Mesh>::readVertex(size_t _vertex,
Jan Möbius's avatar
Jan Möbius committed
756
757
758
                            const typename Mesh::VertexHandle&   _vh,
                            const typename Mesh::HalfedgeHandle& _hh,
                            const typename Mesh::FaceHandle&     _fh)
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
{
  static const typename Mesh::HalfedgeHandle invalidHEH(-1);
  static const typename Mesh::FaceHandle     invalidFH(-1);


  ACG::Vec3d n(0.0, 0.0, 1.0);
  ACG::Vec2f texc(0.0f, 0.0f);
  unsigned int col(0);

  // read normal
  if (halfedgeNormalMode_ == 0 && mesh_.has_vertex_normals())
    n = mesh_.normal(_vh);
  else if (halfedgeNormalMode_ &&  mesh_.has_halfedge_normals() && _hh != invalidHEH)
    n = mesh_.normal(_hh);

  // read texcoord
  if (mesh_.has_halfedge_texcoords2D())
  {
    if (_hh != invalidHEH && textureMode_ == 1)
      texc = mesh_.texcoord2D(_hh);
    else if (mesh_.has_vertex_texcoords2D())
      texc = mesh_.texcoord2D(_vh);
  }
  else if (mesh_.has_vertex_texcoords2D())
    texc = mesh_.texcoord2D(_vh);

  // read per face or per vertex color
  unsigned int byteCol[2];
  for (int col = 0; col < 2; ++col)
  {
    Vec4uc vecCol(255, 255, 255, 255);

    if (col == 0 && mesh_.has_vertex_colors()) 
      vecCol = OpenMesh::color_cast<Vec4uc, typename Mesh::Color>(mesh_.color(_vh));
    if (_fh != invalidFH)
    {
      if (col == 1 && mesh_.has_face_colors() && _fh.idx() >= 0) 
        vecCol = OpenMesh::color_cast<Vec4uc,typename Mesh::Color>(mesh_.color(_fh));
    }

    // OpenGL color format: A8B8G8R8
    byteCol[col] = (unsigned char)(vecCol[0]);
    byteCol[col] |= ((unsigned char)(vecCol[1])) << 8;
    byteCol[col] |= ((unsigned char)(vecCol[2])) << 16;
    byteCol[col] |= ((unsigned char)(vecCol[3])) << 24;
    //byteCol[col] |= 0xFF << 24; // if no alpha channel
  }

  if (colorMode_ != 2)
    col = byteCol[0]; // vertex colors
  else
    col = byteCol[1]; // face colors


  // store vertex attributes in vbo
  writePosition(_vertex, mesh_.point(_vh));
  writeNormal(_vertex, n);
  writeTexcoord(_vertex, texc);
  writeColor(_vertex, col);
  

  // read/write custom attributes

  for (size_t i = 0; i < additionalElements_.size(); ++i)
  {
    std::cout << "not implemented!" << std::endl;


  }

  
}

template <class Mesh>
unsigned int
Jan Möbius's avatar
Jan Möbius committed
834
DrawMeshT<Mesh>::getVertexColor(const typename Mesh::VertexHandle& _vh)
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
{
  static const typename Mesh::VertexHandle     invalidVH(-1);

  unsigned int byteCol;
  
  Vec4uc vecCol(255, 255, 255, 255);

  if ( _vh != invalidVH && mesh_.has_vertex_colors() )
    vecCol = OpenMesh::color_cast<Vec4uc, typename Mesh::Color>(mesh_.color(_vh));

  // OpenGL color format: A8B8G8R8
  byteCol  = (unsigned char)(vecCol[0]);
  byteCol |= ((unsigned char)(vecCol[1])) << 8;
  byteCol |= ((unsigned char)(vecCol[2])) << 16;
  byteCol |= ((unsigned char)(vecCol[3])) << 24;

  return byteCol;
}

template <class Mesh>
unsigned int
Jan Möbius's avatar
Jan Möbius committed
856
DrawMeshT<Mesh>::getFaceColor(const typename Mesh::FaceHandle& _fh)
857
858
859
860
861
862
863
864
865
866
867
868
869
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
{
  static const typename Mesh::FaceHandle     invalidFH(-1);

  unsigned int byteCol;
  Vec4uc vecCol(255, 255, 255, 255);

  if ( _fh != invalidFH && mesh_.has_face_colors() && _fh.idx() >= 0 ) 
    vecCol = OpenMesh::color_cast<Vec4uc,typename Mesh::Color>(mesh_.color(_fh));

  // OpenGL color format: A8B8G8R8
  byteCol  = (unsigned char)(vecCol[0]);
  byteCol |= ((unsigned char)(vecCol[1])) << 8;
  byteCol |= ((unsigned char)(vecCol[2])) << 16;
  byteCol |= ((unsigned char)(vecCol[3])) << 24;

  return byteCol;
}


template <class Mesh>
int
DrawMeshT<Mesh>::getTextureIDofFace(unsigned int _face)
{
  OpenMesh::FPropHandleT< int > textureIndexProperty;
  if (mesh_.get_property_handle(textureIndexProperty, textureIndexPropertyName_))
    return mesh_.property(textureIndexProperty, mesh_.face_handle(_face));

  if (mesh_.has_face_texture_index())
    return mesh_.texture_index(mesh_.face_handle(_face));

  return 0;
}

template <class Mesh>
int
DrawMeshT<Mesh>::getTextureIDofTri(unsigned int _tri)
{
  return getTextureIDofFace(meshComp_->mapToOriginalFaceID(_tri));
}


template <class Mesh>
void
DrawMeshT<Mesh>::createVBO()
{
  bindVbo();

  // toggle between normal source and texcoord source
  // (per vertex, per halfedge, per face)

  if (flatMode_ && meshComp_)
  {
    for (unsigned int i = 0; i < numTris_; ++i)
    {
      int faceId = meshComp_->mapToOriginalFaceID(i);

      // get face normal
      ACG::Vec3d n = mesh_.normal(mesh_.face_handle(faceId));

      // store face normal in last tri vertex
//      for (unsigned int k = 0; k < 3; ++k)
      {
        int idx = meshComp_->getIndex(i*3 + meshComp_->getProvokingVertex());
//        vertices_[idx].n[k] = n[k];
        writeNormal(idx, n);
      }

    }
    bVBOinFlatMode_ = 1;
  }
  else
  {
    for (unsigned int i = 0; i < numVerts_; ++i)
    {
      typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);

      // get halfedge normal

      if (hh.is_valid())
      {
        ACG::Vec3d n;
        if (halfedgeNormalMode_ == 1 && mesh_.has_halfedge_normals())
          n = mesh_.normal( hh );
        else
          n = mesh_.normal( mesh_.to_vertex_handle(hh) );

//         for (int k = 0; k < 3; ++k)
//           vertices_[i].n[k] = n[k];
        writeNormal(i, n);
      }
      else
      {
        // isolated vertex
        int posID = i;


        if (meshComp_) {
          int f_id, c_id;
          posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);
        }

//         for (int k = 0; k < 3; ++k)
//           vertices_[i].tex[k] = mesh_.normal( mesh_.vertex_handle(posID) )[k];
        writeNormal(i, mesh_.normal( mesh_.vertex_handle(posID) ));
      }
    }

    bVBOinFlatMode_ = 0;
  }

  if (textureMode_ == 0)
  {
    // per vertex texcoords
    if (mesh_.has_vertex_texcoords2D())
    {
      for (unsigned int i = 0; i < numVerts_; ++i)
      {
        typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);

        if (hh.is_valid())
        {
          // copy texcoord
//           for (int k = 0; k < 2; ++k)
//             vertices_[i].tex[k] = mesh_.texcoord2D( mesh_.to_vertex_handle(hh) )[k];

          writeTexcoord(i, mesh_.texcoord2D( mesh_.to_vertex_handle(hh) ) );
        }
        else
        {
          // isolated vertex
          int posID = i;

          if (meshComp_) {
            int f_id, c_id;
            posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);
          }

//           for (int k = 0; k < 2; ++k)
//             vertices_[i].tex[k] = mesh_.texcoord2D( mesh_.vertex_handle(posID) )[k];

          writeTexcoord(i, mesh_.texcoord2D( mesh_.vertex_handle(posID) ) );

        }
      }
    }
    
    bVBOinHalfedgeTexMode_ = 0;
  }
  else
  {
    if (mesh_.has_vertex_texcoords2D() || mesh_.has_halfedge_texcoords2D())
    {
      // per halfedge texcoords
      for (unsigned int i = 0; i < numVerts_; ++i)
      {
        typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);

        if (hh.is_valid())
        {
          // copy texcoord
          if (mesh_.has_halfedge_texcoords2D())
          {
//             for (int k = 0; k < 2; ++k)
//               vertices_[i].tex[k] = mesh_.texcoord2D( hh )[k];

            writeTexcoord(i, mesh_.texcoord2D( hh ) );
          }

        }
        else if (mesh_.has_vertex_texcoords2D())
        {
          // isolated vertex
          int posID = i;


          if (meshComp_) {
            int f_id, c_id;
            posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);
          }

//           for (int k = 0; k < 2; ++k)
//             vertices_[i].tex[k] = mesh_.texcoord2D( mesh_.vertex_handle(posID) )[k];

          writeTexcoord(i, mesh_.texcoord2D( mesh_.vertex_handle(posID) ) );

        }
      }
    }
    
    bVBOinHalfedgeTexMode_ = 1;
  }

  if (colorMode_ && colorMode_ != curVBOColorMode_)
  {
    if (colorMode_ == 1)
    {
      // use vertex colors

      for (int i = 0; i < (int)numVerts_; ++i)
      {
        typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(i);

        unsigned int col;

        if (hh.is_valid())
          col = getVertexColor(mesh_.to_vertex_handle(hh));
        else
        {
          // isolated vertex
          int f_id, c_id;
          int posID = meshComp_->mapToOriginalVertexID(i, f_id, c_id);
          col = getVertexColor( mesh_.vertex_handle(posID) );
        }

        writeColor(i, col);
      }
    }
    else if (colorMode_ == 2)
    {
      // use face colors

      const int provokingId = meshComp_->getProvokingVertex();
      assert(provokingId >= 0 && provokingId < 3);

      for (int i = 0; i < (int)numTris_; ++i)
      {
        int idx = meshComp_->getIndex(i*3+provokingId);

        int faceId = meshComp_->mapToOriginalFaceID(i);
        unsigned int fcolor = getFaceColor(mesh_.face_handle(faceId));

//        vertices_[idx].col = fcolor;
        writeColor(idx, fcolor);
      }
    }

    // vbo colors updated
    curVBOColorMode_ = colorMode_;
  }

  fillVertexBuffer();

  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
1100
1101
1102

  // non indexed vbo needs updating now
  invalidateFullVBO();
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
}

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

  bindIbo();

  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
  createIndexBuffer();


  // line index buffer:
  if (mesh_.n_edges())
  {
1132
    std::vector<unsigned int> lineBuffer(mesh_.n_edges() * 2);
1133
1134
1135
1136
1137
1138
1139

    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)
      {
1140
1141
1142
        // put two words in a dword
        unsigned int combinedIdx = invVertexMap_[mesh_.from_vertex_handle(hh).idx()] | (invVertexMap_[mesh_.to_vertex_handle(hh).idx()] << 16);
        lineBuffer[i] = combinedIdx;
1143
1144
1145
      }
      else
      {
1146
1147
        lineBuffer[2 * i] = invVertexMap_[mesh_.from_vertex_handle(hh).idx()];
        lineBuffer[2 * i + 1] = invVertexMap_[mesh_.to_vertex_handle(hh).idx()];
1148
1149
1150
1151
1152
      }
    }

    bindLineIbo();

1153
    fillLineBuffer(mesh_.n_edges(), &lineBuffer[0]);
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
  }

  ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
}

template <class Mesh>
DrawMeshT<Mesh>::~DrawMeshT(void)
{
  delete [] invVertexMap_;
}



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

  sysBufSize += meshComp_->getMemoryUsage();

  // vertex buffer
  if (!vertices_.empty())
    sysBufSize += vertexDecl_->getVertexStride() * numVerts_;

  
  
  res += sysBufSize;

  // mappings
  unsigned int mapsSize = 0;
 
  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);

  pickBufSize += pickEdgeBuf_.capacity() * sizeof(ACG::Vec4uc);

  pickBufSize += pickFaceVertexBuf_.capacity() * sizeof(ACG::Vec3f);
  pickBufSize += pickFaceColBuf_.capacity() * sizeof(ACG::Vec4uc);


  pickBufSize += pickAnyFaceColBuf_.capacity() * sizeof(ACG::Vec4uc);
  pickBufSize += pickAnyEdgeColBuf_.capacity() * sizeof(ACG::Vec4uc);
  pickBufSize += pickAnyVertexColBuf_.capacity() * sizeof(ACG::Vec4uc);

  res += pickBufSize;


  // edge and halfedge vertex buffers (glDraw from sysmem)
  unsigned int edgeBufSize = 0;

  edgeBufSize += perEdgeVertexBuf_.capacity() * sizeof(ACG::Vec3f);
  edgeBufSize += perEdgeColorBuf_.capacity() * sizeof(ACG::Vec4uc);

  edgeBufSize += perHalfedgeVertexBuf_.capacity() * sizeof(ACG::Vec3f);
  edgeBufSize += perHalfedgeColorBuf_.capacity() * sizeof(ACG::Vec4uc);


  res += edgeBufSize;


  unsigned int gpuBufSize = 0;

  if (ibo_)
    gpuBufSize += numTris_ * 3 * (indexType_ == GL_UNSIGNED_INT ? 4 : 2);

  if (vbo_)
    gpuBufSize += numVerts_ * vertexDecl_->getVertexStride();

  if (_printReport)
  {
    std::cout << "\nDrawMesh memory usage in MB:\n";
    std::cout << "Vertex+IndexBuffer (SYSMEM only): " << float(sysBufSize) / (1024 * 1024);
    std::cout << "\nMappings: " << float(mapsSize) / (1024 * 1024);
    std::cout << "\nPicking Buffers: " << float(pickBufSize) / (1024 * 1024);
    std::cout << "\nEdge Buffers: " << float(edgeBufSize) / (1024 * 1024);
    std::cout << "\nTotal SYSMEM: " << float(res) / (1024 * 1024);
    std::cout << "\nTotal GPU: " << float(gpuBufSize) / (1024 * 1024) << std::endl;
  }
  
  return res;
}


template <class Mesh>
void DrawMeshT<Mesh>::updateGPUBuffers()
{
  // rebuild if necessary
  if ((!numTris_ && mesh_.n_faces())|| ! numVerts_ || (!meshComp_ && mesh_.n_faces()))
  {
    rebuild_ = REBUILD_FULL;
  }

  if (bVBOinHalfedgeNormalMode_ != halfedgeNormalMode_) rebuild_ = REBUILD_FULL;

  // if no rebuild necessary, check for smooth / flat shading switch 
  // to update normals
  if (rebuild_ == REBUILD_NONE)
  {
    if (bVBOinFlatMode_ != flatMode_ || bVBOinHalfedgeTexMode_ != textureMode_ || (colorMode_ && curVBOColorMode_ != colorMode_))
      createVBO();
  }
  else
  {
    rebuild();
  }
}


template <class Mesh>
GLuint DrawMeshT<Mesh>::getVBO()
{
  updateGPUBuffers();
  return vbo_;
}

template <class Mesh>
GLuint DrawMeshT<Mesh>::getIBO()
{
  updateGPUBuffers();
  return ibo_;
}

template <class Mesh>
unsigned int DrawMeshT<Mesh>::mapVertexToVBOIndex(unsigned int _v)
{
  if (_v < mesh_.n_vertices())
  {
    if (invVertexMap_)
      return invVertexMap_[_v];
    else //if mesh is a point cloud
      return _v;
  }

  return (unsigned int)-1;
}

template <class Mesh>
void DrawMeshT<Mesh>::bindBuffers()
{
  updateGPUBuffers();

  ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, vbo_);

  // prepare color mode
  if (colorMode_)
  {
    ACG::GLState::colorPointer(4, GL_UNSIGNED_BYTE, vertexDecl_->getVertexStride(), (char*)offsetColor_);
    ACG::GLState::enableClientState(GL_COLOR_ARRAY);
  }

  // vertex decl
  ACG::GLState::vertexPointer(3, GL_FLOAT, vertexDecl_->getVertexStride(), (char*)offsetPos_);
  ACG::GLState::enableClientState(GL_VERTEX_ARRAY);

  glClientActiveTexture(GL_TEXTURE0);
  ACG::GLState::texcoordPointer(2, GL_FLOAT, vertexDecl_->getVertexStride(), (char*)offsetTexc_);
  ACG::GLState::enableClientState(GL_TEXTURE_COORD_ARRAY);

  ACG::GLState::normalPointer(GL_FLOAT, vertexDecl_->getVertexStride(), (char*)offsetNormal_);
  ACG::GLState::enableClientState(GL_NORMAL_ARRAY);

//  ACG::GLState::normalPointerEXT(3, GL_FLOAT, sizeof(Vertex), (char*)(20));  // ACG::GLState::normalPointerEXT crashes sth. in OpenGL

  ACG::GLState::bindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, ibo_);
}

template <class Mesh>
void DrawMeshT<Mesh>::bindBuffersToRenderObject(RenderObject* _obj)
{
  updateGPUBuffers();

  _obj->vertexBuffer = vbo_;
  _obj->indexBuffer = ibo_;

  _obj->indexType = indexType_;

  // assign correct vertex declaration
  _obj->vertexDecl = vertexDecl_;
}

template <class Mesh>
void DrawMeshT<Mesh>::unbindBuffers()
{
  ACG::GLState::disableClientState(GL_VERTEX_ARRAY);
  ACG::GLState::disableClientState(GL_TEXTURE_COORD_ARRAY);
  ACG::GLState::disableClientState(GL_NORMAL_ARRAY);

  if (colorMode_)
    ACG::GLState::disableClientState(GL_COLOR_ARRAY);

  ACG::GLState::bindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
  ACG::GLState::bindBuffer(GL_ARRAY_BUFFER_ARB, 0);
}

template <class Mesh>
1359
void DrawMeshT<Mesh>::draw(std::map< int, GLuint>* _textureMap, bool _nonindexed)
1360
{
1361
1362
1363
1364
1365
1366
1367
1368
  if (!_nonindexed)
    bindBuffers();
  else
  {
    updateFullVBO();
    vboFull_.bind();
    vertexDecl_->activateFixedFunction();
  }
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390

#ifdef DEBUG_MEM_USAGE
  getMemoryUsage(true);
#endif

  if (numTris_)
  {
    if (_textureMap)
    {
      // textured mode

      for (int i = 0; i < meshComp_->getNumSubsets(); ++i)
      {
        const MeshCompiler::Subset* sub = meshComp_->getSubset(i);

        if ( _textureMap->find(sub->id) == _textureMap->end() ) {
          std::cerr << "Illegal texture index ... trying to access " << sub->id << std::endl;
          ACG::GLState::bindTexture(GL_TEXTURE_2D, 0);
        }
        else
          ACG::GLState::bindTexture(GL_TEXTURE_2D, (*_textureMap)[sub->id]);

1391
        if (!_nonindexed)
1392
          glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(sub->numTris * 3), indexType_,
1393
1394
            (GLvoid*)( (size_t)sub->startIndex * (indexType_ == GL_UNSIGNED_INT ? 4 : 2))); // offset in bytes
        else
1395
          glDrawArrays(GL_TRIANGLES, sub->startIndex, static_cast<GLsizei>(sub->numTris * 3));
1396
1397
1398
      }
    }
    else
1399
1400
    {
      if (!_nonindexed)
1401
        glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(numTris_ * 3), indexType_, 0);
1402
      else
1403
        glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(numTris_ * 3));
1404
    }
1405
1406
1407
1408
1409
1410
1411
  }

  unbindBuffers();
}


template <class Mesh>
1412
void ACG::DrawMeshT<Mesh>::addTriRenderObjects(IRenderer* _renderer, const RenderObject* _baseObj, std::map< int, GLuint>* _textureMap, bool _nonindexed)
1413
1414
1415
1416
{
  if (numTris_)
  {
    RenderObject ro = *_baseObj;
1417
1418
1419
1420
1421
1422
1423
1424
1425
    if (!_nonindexed)
      bindBuffersToRenderObject(&ro);
    else
    {
      updateFullVBO();

      ro.vertexBuffer = vboFull_.id();
      ro.vertexDecl = vertexDecl_;
    }
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449

    if (_baseObj->shaderDesc.textured())
    {
      // textured mode

      for (int i = 0; i < meshComp_->getNumSubsets(); ++i)
      {
        const MeshCompiler::Subset* sub = meshComp_->getSubset(i);

        if ( _textureMap )
        {
          if ( _textureMap->find(sub->id) == _textureMap->end() ) {
            std::cerr << "Illegal texture index ... trying to access " << sub->id << std::endl;
          }
          else
          {
            RenderObject::Texture tex;
            tex.type = GL_TEXTURE_2D;
            tex.id = (*_textureMap)[sub->id];
            ro.addTexture(tex,0);
          }
        }
        else // no texture map specified, use whatever texture is currently bound to the first texture stage
        {
1450
          glActiveTextureARB(GL_TEXTURE0);
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
          GLint textureID = 0;
          glGetIntegerv(GL_TEXTURE_BINDING_2D, &textureID);

          RenderObject::Texture tex;
          tex.type = GL_TEXTURE_2D;
          tex.id = textureID;
          ro.addTexture(tex,0);
        }

        

1462
        if (!_nonindexed)
1463
          ro.glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(sub->numTris * 3), indexType_,
1464
1465
            (GLvoid*)((size_t)sub->startIndex * (indexType_ == GL_UNSIGNED_INT ? 4 : 2))); // offset in bytes
        else
1466
          ro.glDrawArrays(GL_TRIANGLES, sub->startIndex, static_cast<GLsizei>(sub->numTris * 3) );
1467
1468
1469
1470
1471
1472
        
        _renderer->addRenderObject(&ro);
      }
    }
    else
    {
1473
      if (!_nonindexed)
1474
        ro.glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(numTris_ * 3), indexType_, 0);
1475
      else
1476
        ro.glDrawArrays(GL_TRIANGLES,0,  static_cast<GLsizei>(numTris_ * 3));
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
      _renderer->addRenderObject(&ro);
    }
  }
}


template <class Mesh>
void DrawMeshT<Mesh>::drawLines()
{
  bindBuffers();

  if (mesh_.n_edges())
  {
    ACG::GLState::bindBuffer(GL_ELEMENT_ARRAY_BUFFER, lineIBO_);

1492
    glDrawElements(GL_LINES, static_cast<GLsizei>(mesh_.n_edges() * 2), indexType_, 0);
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
  }

  unbindBuffers();
}


template <class Mesh>
void DrawMeshT<Mesh>::addLineRenderObjects(IRenderer* _renderer, const RenderObject* _baseObj)
{
  RenderObject ro = *_baseObj;
  bindBuffersToRenderObject(&ro);

  if (mesh_.n_edges())
  {
    ro.indexBuffer = lineIBO_;
1508
    ro.glDrawElements(GL_LINES, static_cast<GLsizei>(mesh_.n_edges() * 2), indexType_, 0);
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
    
    _renderer->addRenderObject(&ro);
  }
}

template <class Mesh>
void DrawMeshT<Mesh>::drawVertices()
{

  bindBuffers();

  if (numVerts_)
1521
    glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(numVerts_));
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533

  unbindBuffers();
}

template <class Mesh>
void DrawMeshT<Mesh>::addPointRenderObjects(IRenderer* _renderer, const RenderObject* _baseObj)
{
  RenderObject ro = *_baseObj;
  bindBuffersToRenderObject(&ro);

  if (numVerts_)
  {
1534
    ro.glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(numVerts_));
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678

    _renderer->addRenderObject(&ro);
  }
}

//////////////////////////////////////////////////////////////////////////

template <class Mesh>
unsigned int DrawMeshT<Mesh>::countTris(unsigned int* pMaxVertsOut, unsigned int* _pOutNumIndices)
{
  unsigned int triCounter = 0;

  if (pMaxVertsOut) *pMaxVertsOut = 0;
  if (_pOutNumIndices) *_pOutNumIndices = 0;

  for (unsigned int i = 0; i < mesh_.n_faces(); ++i)
  {
    typename Mesh::FaceHandle fh =  mesh_.face_handle(i);

    // count vertices
  	unsigned int nPolyVerts = 0;

    for (typename Mesh::FaceHalfedgeIter hh_it = mesh_.fh_iter(fh); hh_it.is_valid(); ++hh_it ) ++nPolyVerts;

    triCounter += (nPolyVerts - 2);

    if (pMaxVertsOut)
    {
      if (*pMaxVertsOut < nPolyVerts)
        *pMaxVertsOut = nPolyVerts;
    }

    if (_pOutNumIndices) *_pOutNumIndices += nPolyVerts;
  }

  return triCounter;
}



template <class Mesh>
ACG::Vec3f* DrawMeshT<Mesh>::perEdgeVertexBuffer()
{
  // Force update of the buffers if required
  if (updatePerEdgeBuffers_)
    updatePerEdgeBuffers();
  return perEdgeVertexBuf_.empty() ? 0 : &(perEdgeVertexBuf_[0]); 
}

template <class Mesh>
ACG::Vec4f* DrawMeshT<Mesh>::perEdgeColorBuffer()
{
  // Force update of the buffers if required
  if (updatePerEdgeBuffers_)
    updatePerEdgeBuffers();
  return perEdgeColorBuf_.empty() ? 0 : &(perEdgeColorBuf_[0]); 
}


template <class Mesh>
void DrawMeshT<Mesh>::updatePickingVertices(ACG::GLState& _state,
                                            uint _offset)
{
  unsigned int idx = 0;

  // Adjust size of the color buffer to the number of vertices in the mesh
  pickVertColBuf_.resize( mesh_.n_vertices() );
  pickVertBuf_.resize( mesh_.n_vertices() );

  // Get the right picking colors from the gl state and add them per vertex to the color buffer
  typename Mesh::ConstVertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end());
  for (; v_it!=v_end; ++v_it, ++idx) 
  {
    pickVertColBuf_[idx] = _state.pick_get_name_color(idx + _offset);
    pickVertBuf_[idx] = mesh_.point(mesh_.vertex_handle(idx));
  }
}


template <class Mesh>
void DrawMeshT<Mesh>::updatePickingVertices_opt(ACG::GLState& _state)
{
  // Make sure, the face buffers are up to date before generating the picking data!
  if (!numVerts_ && mesh_.n_vertices())
  {
    rebuild_ = REBUILD_FULL;
    rebuild();
  }

#ifndef GL_ARB_texture_buffer_object
  pickVertexMethod_ = 1; // no texture buffers supported during compilation
#endif

  if (numVerts_)
  {
    // upload vbo id->openmesh id lookup-table to texture buffer

    if (pickVertexMethod_ == 0)
    {
#ifdef GL_ARB_texture_buffer_object

      std::vector<int> forwardMap(numVerts_, 0);

      for (int i = 0; i < (int)numVerts_; ++i)
      {
        int vboIdx = mapVertexToVBOIndex(i);
        if (vboIdx >= 0)
          forwardMap[vboIdx] = i;
      }
      pickVertexMapTBO_.setBufferData(sizeof(int) * numVerts_, &forwardMap[0], GL_R32I, GL_STATIC_DRAW);

#endif // GL_ARB_texture_buffer_object

    }
    else
    {
      // Another method: draw with index buffer, which contains the mapping from openmesh vertex id to drawmesh vbo vertex.
      // problem with this: gl_VertexID is affected by index buffer and thus represents the drawmesh vbo ids
      // -> use gl_PrimitiveID instead, which represents the openmesh vertex id
      if (invVertexMap_)
      {
        bindPickVertexIbo();
        fillInvVertexMap(mesh_.n_vertices(), invVertexMap_);
        ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
      }

    }
  }
}


template <class Mesh>
bool ACG::DrawMeshT<Mesh>::supportsPickingVertices_opt()
{
  // load and compile picking shader

  // load once directly from files:
//   if (!pickVertexShader_)
//   {
//     if (pickVertexMethod_ == 0)
//       pickVertexShader_ = GLSL::loadProgram("Picking/pick_vertices_vs.glsl", "Picking/pick_vertices_fs.glsl");
//     else
//       pickVertexShader_ = GLSL::loadProgram("Picking/vertex.glsl", "Picking/pick_vertices_fs2.glsl");
//   }
1679
  
1680
1681
  // load from cache
  if (pickVertexMethod_ == 0)
1682
    pickVertexShader_ = ShaderCache::getInstance()->getProgram("Picking/pick_vertices_vs.glsl", "Picking/pick_vertices_fs.glsl", 0, false);
1683
  else
1684
    pickVertexShader_ = ShaderCache::getInstance()->getProgram("Picking/vertex.glsl", "Picking/pick_vertices_fs2.glsl", 0, false);
1685
1686
1687
1688
1689
1690
1691

  // check link status
  return pickVertexShader_ && pickVertexShader_->isLinked();
}


template <class Mesh>
Jan Möbius's avatar
Jan Möbius committed
1692
void ACG::DrawMeshT<Mesh>::drawPickingVertices_opt( const GLMatrixf& _mvp, size_t _pickOffset )
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
{
  // optimized version which computes picking ids in the shader

  /*
  pickVertexMethod_
   0: - create a textureBuffer containing the mapping from vbo id to openmesh vertex id
      - draw point list of the main vbo and read texture map in the vertex shader
      - computation in vertex shader via gl_VertexID
      -> required mem: 4 bytes per vertex in draw vbo
      -> # vertex transforms: vertex count in draw vbo

   1: - create index buffer containing the mapping from openmesh vertex id to vbo id
         (not required for point-clouds)
      - draw point list with index buffer
      - computation in fragment shader via gl_PrimitiveID
      -> required mem: nothing for point-clouds, otherwise 4 bytes per vertex in openmesh
      -> # vertex transforms: vertex count in openmesh

      method 1 is probably more efficient overall
  */

  // test support by loading and compiling picking shader
  if (!supportsPickingVertices_opt())
    return;

  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, getVBO());
  
1720
  if (pickVertexMethod_ == 1 && invVertexMap_)
1721
1722
1723
1724
1725
1726
    bindPickVertexIbo();

  // setup picking shader
  pickVertexShader_->use();
  getVertexDeclaration()->activateShaderPipeline(pickVertexShader_);

Jan Möbius's avatar
Jan Möbius committed
1727
  pickVertexShader_->setUniform("pickVertexOffset", static_cast<GLint>(_pickOffset) );
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740

  if (pickVertexMethod_ == 0)
  {
    pickVertexShader_->setUniform("vboToInputMap", 0);
#ifdef GL_ARB_texture_buffer_object
    pickVertexMap_opt()->bind(GL_TEXTURE0);
#endif
  }

  pickVertexShader_->setUniform("mWVP", _mvp);

  // draw call
  if (pickVertexMethod_ == 0)
1741
    glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(getNumVerts()));
1742
1743
  else
  {
1744
    if (pickVertexIBO_opt() && invVertexMap_)
1745
      glDrawElements(GL_POINTS, static_cast<GLsizei>(mesh_.n_vertices()), GL_UNSIGNED_INT, 0);
1746
    else
1747
      glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(mesh_.n_vertices()));
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
  }

  // restore gl state      
  getVertexDeclaration()->deactivateShaderPipeline(pickVertexShader_);
  pickVertexShader_->disable();

  // unbind draw buffers
  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

  if (pickVertexMethod_ == 1)
      ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
}



template <class Mesh>
void DrawMeshT<Mesh>::updatePerEdgeBuffers()
{
  // Only update buffers if they are invalid
  if (!updatePerEdgeBuffers_) 
    return;

  perEdgeVertexBuf_.resize(mesh_.n_edges() * 2);

  if ( mesh_.has_edge_colors() ) {
    perEdgeColorBuf_.resize(mesh_.n_edges() * 2);
  } else
    perEdgeColorBuf_.clear();    

  unsigned int idx = 0;

  typename Mesh::ConstEdgeIter  e_it(mesh_.edges_sbegin()), e_end(mesh_.edges_end());
  for (; e_it!=e_end; ++e_it) {

    perEdgeVertexBuf_[idx]   = mesh_.point(mesh_.to_vertex_handle(mesh_.halfedge_handle(*e_it, 0)));
    perEdgeVertexBuf_[idx+1] = mesh_.point(mesh_.to_vertex_handle(mesh_.halfedge_handle(*e_it, 1)));

    if (  mesh_.has_edge_colors() ) {
      const Vec4f color = OpenMesh::color_cast<Vec4f>( mesh_.color(*e_it) ) ;
      perEdgeColorBuf_[ idx ]     = color;
      perEdgeColorBuf_[ idx + 1 ] = color;
    }

    idx += 2;
  }


  updatePerEdgeBuffers_ = 0;

  updateEdgeHalfedgeVertexDeclarations();
}

template <class Mesh>
template<typename Mesh::Normal (DrawMeshT<Mesh>::*NormalLookup)(typename Mesh::FaceHandle)>
void DrawMeshT<Mesh>::updatePerHalfedgeBuffers()
{
  // Only update buffers if they are invalid
  if (!updatePerHalfedgeBuffers_) 
    return;

  perHalfedgeVertexBuf_.resize(mesh_.n_halfedges() * 2);

  if ( mesh_.has_halfedge_colors() ) {
    perHalfedgeColorBuf_.resize(mesh_.n_halfedges() * 2);
  } else
    perHalfedgeColorBuf_.clear();    

  unsigned int idx = 0;

  for (typename Mesh::ConstHalfedgeIter he_it(mesh_.halfedges_sbegin()), he_end(mesh_.halfedges_end());
          he_it != he_end; ++he_it) {

    typename Mesh::HalfedgeHandle next_heh     = mesh_.next_halfedge_handle(*he_it);
    typename Mesh::HalfedgeHandle previous_heh = mesh_.prev_halfedge_handle(*he_it);

    if (mesh_.is_valid_handle(next_heh) && mesh_.is_valid_handle(previous_heh))
    {
        perHalfedgeVertexBuf_[idx]   = halfedge_point<NormalLookup>(*he_it);
        perHalfedgeVertexBuf_[idx+1] = halfedge_point<NormalLookup>(previous_heh);
    }
    else
    {
        // Cannot compute shifted vertex positions. Use original vertex positions instead.
        perHalfedgeVertexBuf_[idx  ] = mesh_.point(mesh_.to_vertex_handle(*he_it));
        perHalfedgeVertexBuf_[idx+1] = mesh_.point(mesh_.from_vertex_handle(*he_it));
    }

    if (  mesh_.has_halfedge_colors() ) {
      const Vec4f color = OpenMesh::color_cast<Vec4f>( mesh_.color(*he_it) ) ;
      perHalfedgeColorBuf_[ idx ]     = color;
      perHalfedgeColorBuf_[ idx + 1 ] = color;
    }

    idx += 2;
  }

  updatePerHalfedgeBuffers_ = 0;

  updateEdgeHalfedgeVertexDeclarations();
}

template<class Mesh>
template<typename Mesh::Normal (DrawMeshT<Mesh>::*NormalLookup)(typename Mesh::FaceHandle)>
typename Mesh::Point DrawMeshT<Mesh>::halfedge_point(const typename Mesh::HalfedgeHandle _heh) {

  typename Mesh::Point p  = mesh_.point(mesh_.to_vertex_handle  (_heh));
  typename Mesh::Point pp = mesh_.point(mesh_.from_vertex_handle(_heh));
  typename Mesh::Point pn = mesh_.point(mesh_.to_vertex_handle(mesh_.next_halfedge_handle(_heh)));

  //  typename Mesh::Point n  = (p-pp)%(pn-p);
  typename Mesh::Point fn;
  if( !mesh_.is_boundary(_heh))
    //fn = mesh_.normal(mesh_.face_handle(_heh));
      fn = (this->*NormalLookup)(mesh_.face_handle(_heh));
  else
    //fn = mesh_.normal(mesh_.face_handle(mesh_.opposite_halfedge_handle(_heh)));
      fn = (this->*NormalLookup)(mesh_.face_handle(mesh_.opposite_halfedge_handle(_heh)));

  typename Mesh::Point upd = ((fn%(pn-p)).normalize() + (fn%(p-pp)).normalize()).normalize();

  upd *= ((pn-p).norm()+(p-pp).norm())*0.08;

  return (p+upd);

  // double alpha = 0.1;
  // // correct weighting for concave triangles (or at concave boundaries)
  // if( (fn | n)  < 0.0) alpha *=-1.0;

  // return (p*(1.0-2.0*alpha) + pp*alpha + pn*alpha);
}

template <class Mesh>
ACG::Vec3f* DrawMeshT<Mesh>::perHalfedgeVertexBuffer()
{
 // Force update of the buffers if required
  if (updatePerHalfedgeBuffers_) {
      if (mesh_.has_face_normals())
          updatePerHalfedgeBuffers<&DrawMeshT::cachedNormalLookup>();
      else if (mesh_.is_trimesh())
          updatePerHalfedgeBuffers<&DrawMeshT::computedTriMeshNormal>();
      else
          updatePerHalfedgeBuffers<&DrawMeshT::computedNormal>();
  }
  return perHalfedgeVertexBuf_.empty() ? 0 : &(perHalfedgeVertexBuf_[0]); 
}

template <class Mesh>
ACG::Vec4f* DrawMeshT<Mesh>::perHalfedgeColorBuffer()
{
  // Force update of the buffers if required
  if (updatePerHalfedgeBuffers_) {
      if (mesh_.has_face_normals())
          updatePerHalfedgeBuffers<&DrawMeshT::cachedNormalLookup>();
      else if (mesh_.is_trimesh())
          updatePerHalfedgeBuffers<&DrawMeshT::computedTriMeshNormal>();
      else
          updatePerHalfedgeBuffers<&DrawMeshT::computedNormal>();
  }
  return perHalfedgeColorBuf_.empty() ? 0 : &(perHalfedgeColorBuf_[0]); 
}




template <class Mesh>
void DrawMeshT<Mesh>::updatePickingEdges(ACG::GLState& _state,
                                         unsigned int _offset)
{
  updatePerEdgeBuffers();

  pickEdgeBuf_.resize(mesh_.n_edges() * 2);


  int idx = 0;

  typename Mesh::ConstEdgeIter  e_it(mesh_.edges_sbegin()), e_end(mesh_.edges_end());
  for (; e_it!=e_end; ++e_it) {

    const Vec4uc pickColor =  _state.pick_get_name_color (e_it->idx() + _offset);

    pickEdgeBuf_[idx]    = pickColor;
    pickEdgeBuf_[idx+1]  = pickColor;

    idx += 2;
  }
}



template <class Mesh>
void DrawMeshT<Mesh>::updatePickingEdges_opt(ACG::GLState& _state )
{
  // Make sure, the face buffers are up to date before generating the picking data!
  if (!numTris_ && mesh_.n_faces())
  {
    rebuild_ = REBUILD_FULL;
    rebuild();
  }

  // nothing else to do, optimized edge picking method has no memory overhead
}


template <class Mesh>
bool ACG::DrawMeshT<Mesh>::supportsPickingEdges_opt()
{
1954
  // fetch picking shader from cache (edge picking uses same shader as vertex picking)
1955
  pickEdgeShader_ = ShaderCache::getInstance()->getProgram("Picking/vertex.glsl", "Picking/pick_vertices_fs2.glsl", 0, false);
1956
1957
1958
1959
1960
1961
1962

  // check link status
  return pickEdgeShader_ && pickEdgeShader_->isLinked();
}


template <class Mesh>
Jan Möbius's avatar
Jan Möbius committed
1963
void ACG::DrawMeshT<Mesh>::drawPickingEdges_opt( const GLMatrixf& _mvp, size_t _pickOffset )
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
{
  // optimized version which computes picking ids in the shader

  /* optimization :
  - reuse draw vbo of drawmesh and line index buffer (which is used for wireframe mode)
     the line index buffer stores all edges in the same order as they appear in openmesh
  - use edge id of openmesh as gl_PrimitiveID in fragment shader to compute the picking id
  
  -> no rendering from sysmem buffers
  -> no maintenance/update of picking colors required
  -> no additional memory allocation
  */

  if (!numTris_)
    return;

  // test support by loading and compiling picking shader
  if (!supportsPickingEdges_opt())
    return;

  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, getVBO());
  bindLineIbo();

  // setup picking shader (same shader as in vertex picking)
  pickEdgeShader_->use();
  getVertexDeclaration()->activateShaderPipeline(pickEdgeShader_);

Jan Möbius's avatar
Jan Möbius committed
1991
  pickEdgeShader_->setUniform("pickVertexOffset", static_cast<GLint>(_pickOffset) );
1992
1993
1994
  pickEdgeShader_->setUniform("mWVP", _mvp);

  // draw call
1995
  glDrawElements(GL_LINES, static_cast<GLsizei>(mesh_.n_edges() * 2), indexType_, 0);
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081

  // restore gl state      
  getVertexDeclaration()->deactivateShaderPipeline(pickEdgeShader_);
  pickEdgeShader_->disable();

  // unbind draw buffers
  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
  ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
}








template <class Mesh>
void DrawMeshT<Mesh>::updatePickingFaces(ACG::GLState& _state )
{
  // Make sure, the face buffers are up to date before generating the picking data!
  if (!numTris_ && mesh_.n_faces())
  {
    rebuild_ = REBUILD_FULL;
    rebuild();
  }

  pickFaceVertexBuf_.resize(3 * numTris_);
  pickFaceColBuf_.resize(3 * numTris_);

  for (unsigned int i = 0; i < numTris_; ++i)
  {
    unsigned int faceId = (unsigned int)meshComp_->mapToOriginalFaceID((int)i);

    const Vec4uc pickColor = _state.pick_get_name_color ( faceId );
    for (unsigned int k = 0; k < 3; ++k)
    {
      int idx = meshComp_->getIndex(i*3 + k);

      typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(idx);
      typename Mesh::VertexHandle vh;

      if (hh.is_valid())
        vh = mesh_.to_vertex_handle( hh );
      else
      {
        int f_id, c_id;
        int posID = meshComp_->mapToOriginalVertexID(idx, f_id, c_id);
        vh = mesh_.vertex_handle(posID);
      }

      pickFaceVertexBuf_[i * 3 + k] = mesh_.point( vh );

      pickFaceColBuf_[i * 3 + k] = pickColor;
    }
  }


}



template <class Mesh>
void DrawMeshT<Mesh>::updatePickingFaces_opt(ACG::GLState& _state )
{
  // Make sure, the face buffers are up to date before generating the picking data!
  if (!numTris_ && mesh_.n_faces())
  {
    rebuild_ = REBUILD_FULL;
    rebuild();
  }

#ifdef GL_ARB_texture_buffer_object
  if (meshComp_ && meshComp_->getNumTriangles())
  {
    // upload tri->face lookup-table to texture buffer
    pickFaceTriToFaceMapTBO_.setBufferData(sizeof(int) * meshComp_->getNumTriangles(), meshComp_->mapToOriginalFaceIDPtr(), GL_R32I, GL_STATIC_DRAW);
  }
#endif // GL_ARB_texture_buffer_object

}


template <class Mesh>
bool ACG::DrawMeshT<Mesh>::supportsPickingFaces_opt()
{
2082
2083
2084
  if (!ACG::Texture::supportsTextureBuffer())
    return false;
    
2085
  // fetch picking shader from cache
2086
  pickFaceShader_ = ShaderCache::getInstance()->getProgram("Picking/vertex.glsl", "Picking/pick_face.glsl", 0, false);
2087
2088
2089
2090
2091
2092
2093

  // check link status
  return pickFaceShader_ && pickFaceShader_->isLinked();
}


template <class Mesh>
Jan Möbius's avatar
Jan Möbius committed
2094
void ACG::DrawMeshT<Mesh>::drawPickingFaces_opt( const GLMatrixf& _mvp, size_t _pickOffset )
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
{
  // optimized version which computes picking ids in the shader

  /* optimization idea:
  - reuse draw buffers of drawmesh
  - create lookup table which maps from draw triangle id to openmesh face id (stored in textureBuffer)
  - get base offset of face picking: pickFaceOffset = _state.pick_get_name_color(0)
  - render with following fragment shader, which computes face picking ids on the fly:

  uniform int pickFaceOffset;
  uniform isamplerBuffer triangleToFaceMap;

  out int outPickID; // if possible to write integer. otherwise, convert to ubyte4 or sth.

  void main()
  {
    // map from triangle id to face id
    int faceID = texelFetch(triangleToFaceMap, gl_PrimitiveID);

    outPickID = pickFaceOffset + faceID;
    // maybe the integer id has to be converted to a vec4 color here, not sure
  }

  -> no rendering from sysmem buffers
  -> no maintenance/update of picking colors required
  -> lower memory footprint: 4 bytes per triangle

  keep old approach to stay compatible on systems which do not support texture buffers or integer arithmetic in shaders
  */

  if (!numTris_)
    return;

  // test support by loading and compiling picking shader
  if (!supportsPickingFaces_opt())
    return;

  // reuse cache optimized draw buffers
  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, getVBO());
  ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, getIBO());

  // setup picking shader
  pickFaceShader_->use();
  getVertexDeclaration()->activateShaderPipeline(pickFaceShader_);

Jan Möbius's avatar
Jan Möbius committed
2140
  pickFaceShader_->setUniform("pickFaceOffset", static_cast<GLint>(_pickOffset));
2141
2142
2143
2144
2145
2146
2147
2148
2149
  pickFaceShader_->setUniform("triToFaceMap", 0);

#ifdef GL_ARB_texture_buffer_object
  pickFaceTriangleMap_opt()->bind(GL_TEXTURE0);
#endif

  pickFaceShader_->setUniform("mWVP", _mvp);

  // draw call
2150
  glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(getNumTris() * 3), getIndexType(), 0);
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257

  // restore gl state      
  getVertexDeclaration()->deactivateShaderPipeline(pickFaceShader_);
  pickFaceShader_->disable();

  // unbind draw buffers
  ACG::GLState::bindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
  ACG::GLState::bindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
}




template <class Mesh>
void DrawMeshT<Mesh>::updatePickingAny(ACG::GLState& _state )
{
  if (!numTris_ && mesh_.n_faces())
  {
    rebuild_ = REBUILD_FULL;
    rebuild();
  }
  
  pickFaceVertexBuf_.resize(3 * numTris_);
  pickAnyFaceColBuf_.resize(3 * numTris_);

  for (unsigned int i = 0; i < numTris_; ++i)
  {
    int faceId = meshComp_->mapToOriginalFaceID(i);
    const Vec4uc pickColor = _state.pick_get_name_color ( faceId );
    for (unsigned int k = 0; k < 3; ++k)
    {
      int idx = meshComp_->getIndex(i*3 + k);


      typename Mesh::HalfedgeHandle hh = mapToHalfedgeHandle(idx);
      typename Mesh::VertexHandle vh;

      if (hh.is_valid())
        vh = mesh_.to_vertex_handle( hh );
      else
      {
        int f_id, c_id;
        int posID = meshComp_->mapToOriginalVertexID(idx, f_id, c_id);
        vh = mesh_.vertex_handle(posID);
      }

      pickFaceVertexBuf_[i * 3 + k] = mesh_.point( vh );

      pickAnyFaceColBuf_[i * 3 + k] = pickColor;
    }
  }



  updatePerEdgeBuffers();

  pickAnyEdgeColBuf_.resize(mesh_.n_edges() * 2);

  unsigned int idx = 0;
  typename Mesh::ConstEdgeIter  e_it(mesh_.edges_sbegin()), e_end(mesh_.edges_end());
  for (; e_it!=e_end; ++e_it) {

    const Vec4uc pickColor =  _state.pick_get_name_color (e_it->idx() + mesh_.n_faces());

    pickAnyEdgeColBuf_[idx]    = pickColor;
    pickAnyEdgeColBuf_[idx+1]  = pickColor;

    idx += 2;
  }



  idx = 0;

  // Adjust size of the color buffer to the number of vertices in the mesh
  pickAnyVertexColBuf_.resize( mesh_.n_vertices() );
  pickVertBuf_.resize( mesh_.n_vertices() );

  // Get the right picking colors from the gl state and add them per vertex to the color buffer
  typename Mesh::ConstVertexIter v_it(mesh_.vertices_begin()), v_end(mesh_.vertices_end());
  for (; v_it!=v_end; ++v_it, ++idx) 
  {
    pickAnyVertexColBuf_[idx] = _state.pick_get_name_color(idx + mesh_.n_faces() + mesh_.n_edges());
    pickVertBuf_[idx] = mesh_.point(mesh_.vertex_handle(idx));
  }
}



template <class Mesh>
void DrawMeshT<Mesh>::updatePickingAny_opt(ACG::GLState& _state )
{
  updatePickingFaces_opt(_state);
  updatePickingEdges_opt(_state);
  updatePickingVertices_opt(_state);
  
  // optimized any picking does not require separate picking buffers
}

template <class Mesh>
bool ACG::DrawMeshT<Mesh>::supportsPickingAny_opt()
{
  return supportsPickingFaces_opt() && supportsPickingEdges_opt() && supportsPickingVertices_opt();
}


template <class Mesh>
Jan Möbius's avatar
Jan Möbius committed
2258
void ACG::DrawMeshT<Mesh>::drawPickingAny_opt( const GLMatrixf& _mvp, size_t _pickOffset )
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
{
  // optimized version which computes picking ids in the shader

  /* optimization:
    draw picking ids of faces, edges and vertices with appropriate offsets
  */

  // test support by loading and compiling picking shader
  if (!supportsPickingAny_opt())
    return;

  drawPickingFaces_opt(_mvp, _pickOffset);

  ACG::GLState::depthFunc(GL_LEQUAL);

  drawPickingEdges_opt(_mvp, _pickOffset + mesh_.n_faces());
  
  drawPickingVertices_opt(_mvp, _pickOffset + mesh_.n_faces() + mesh_.n_edges());
}

template <class Mesh>
void
DrawMeshT<Mesh>::
setTextureIndexPropertyName( std::string _indexPropertyName ) {

  // Check if the given property exists
  OpenMesh::FPropHandleT< int > textureIndexProperty;
  if ( !mesh_.get_property_handle(textureIndexProperty,_indexPropertyName) )  {
    if ( _indexPropertyName != "No Texture Index" )
      std::cerr << "DrawMeshT: Unable to get per face texture Index property named " << _indexPropertyName << std::endl;
    return;
  }

  // Remember the property name
  textureIndexPropertyName_ = _indexPropertyName;

  // mark strips as invalid ( have to be regenerated to collect texture index information)
//   stripsValid_ = false;
// 
//   // mark the buffers as invalid as we have a new per face index array
//   invalidatePerFaceBuffers();
  rebuild_ |= REBUILD_TOPOLOGY;
}

template <class Mesh>
void
DrawMeshT<Mesh>::
setPerFaceTextureCoordinatePropertyName( std::string _perFaceTextureCoordinatePropertyName ) {

  // Check if the given property exists
  OpenMesh::HPropHandleT< typename Mesh::TexCoord2D >  perFaceTextureCoordinateProperty;
  if ( !mesh_.get_property_handle(perFaceTextureCoordinateProperty,_perFaceTextureCoordinatePropertyName) )  {
    if ( _perFaceTextureCoordinatePropertyName != "No Texture" )
      std::cerr << "DrawMeshT: Unable to get per face texture coordinate property named " << _perFaceTextureCoordinatePropertyName << std::endl;
    return;
  }

  // Remember the property name
  perFaceTextureCoordinatePropertyName_ = _perFaceTextureCoordinatePropertyName;

  // mark the buffers as invalid as we have a new per face index array
//  invalidatePerFaceBuffers();
  rebuild_ |= REBUILD_GEOMETRY;
}


template <class Mesh>
unsigned int DrawMeshT<Mesh>::getNumTextures()
{
  unsigned int n = 0;
  for (unsigned int i = 0; i < meshComp_->getNumSubsets(); ++i)
  {
    if (meshComp_->getSubset(i)->id > 0) ++n;
  }
  return n;
}

template <class Mesh>
int 
DrawMeshT<Mesh>::perFaceTextureCoordinateAvailable()  {

  // We really have to recheck, as the property might get lost externally (e.g. on restores of the mesh)
  OpenMesh::HPropHandleT< typename Mesh::TexCoord2D >  perFaceTextureCoordinateProperty;
  if ( !mesh_.get_property_handle(perFaceTextureCoordinateProperty, perFaceTextureCoordinatePropertyName_) )  {
    return false;
  }

  // Property available
  return true;

}  


template <class Mesh>
int 
DrawMeshT<Mesh>::perFaceTextureIndexAvailable() {

  // We really have to recheck, as the property might get lost externally (e.g. on restores of the mesh)
  OpenMesh::FPropHandleT< int > textureIndexProperty;
  if ( !mesh_.get_property_handle(textureIndexProperty, textureIndexPropertyName_) )  {
    return false;
  }

  // Property available
  return true;
}






template <class Mesh>
void ACG::DrawMeshT<Mesh>::createVertexDeclaration()
{
  vertexDecl_->clear();

  vertexDecl_->addElement(GL_FLOAT, 3, VERTEX_USAGE_POSITION);
  vertexDecl_->addElement(GL_FLOAT, 2, VERTEX_USAGE_TEXCOORD);
  vertexDecl_->addElement(GL_FLOAT, 3, VERTEX_USAGE_NORMAL);
  vertexDecl_->addElement(GL_UNSIGNED_BYTE, 4, VERTEX_USAGE_COLOR);

  for (size_t i = 0; i < additionalElements_.size(); ++i)
  {
    VertexProperty* prop = &additionalElements_[i];

    // invalidate detected type
    prop->sourceType_.numElements_ = 0;
    prop->sourceType_.pointer_ = 0;
    prop->sourceType_.type_ = 0;
    prop->sourceType_.shaderInputName_ = 0;
    prop->sourceType_.usage_ = VERTEX_USAGE_SHADER_INPUT;
    prop->propDataPtr_ = 0;
    prop->declElementID_ = -1;

    // get property handle in openmesh by name
    OpenMesh::BaseProperty* baseProp = 0;

    switch (prop->source_)
    {
    case PROPERTY_SOURCE_VERTEX: baseProp = mesh_._get_vprop(prop->name_); break;
    case PROPERTY_SOURCE_FACE: baseProp = mesh_._get_fprop(prop->name_); break;
    case PROPERTY_SOURCE_HALFEDGE: baseProp = mesh_._get_hprop(prop->name_); break;
    default: baseProp = mesh_._get_vprop(prop->name_); break;
    }

    // detect data type of property
    prop->propDataPtr_ = getMeshPropertyType(baseProp, &prop->sourceType_.type_, &prop->sourceType_.numElements_);


    if (prop->propDataPtr_)
    {
      prop->sourceType_.shaderInputName_ = prop