DrawMeshT_impl.hh 77.4 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
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
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * 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.              *
 *                                                                           *
\*===========================================================================*/

42

Jan Möbius's avatar
Jan Möbius committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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

#define ACG_DRAW_MESH_TCC

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

#include "DrawMesh.hh"

#include <ACG/GL/gl.hh>
#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"),
87
   perFaceTextureCoordinatePropertyName_("h:texcoords2D"),
Jan Möbius's avatar
Jan Möbius committed
88
89
90
91
92
   updateFullVBO_(true),
   updatePerEdgeBuffers_(1),
  updatePerHalfedgeBuffers_(1)
{

93
94
95
  //today (4.5.2018) the picking shader which uses a textureBuffer, also uses gl_PrimitiveID
  // since it is only supported since glslversion 150 we can just check for openGLVersion 3.2
  pickVertexMethod_ =  openGLVersionTest(3,2) ? 1 : 0;
Jan Möbius's avatar
Jan Möbius committed
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
  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:

Jan Möbius's avatar
Jan Möbius committed
250
  explicit DrawMeshFaceInput(Mesh& _mesh) :
Jan Möbius's avatar
Jan Möbius committed
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
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
457
458
459
460
461
462
463
464
465
466
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
516
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
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
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
855
856
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
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
  mesh_(_mesh)
  {
  };

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


  int getNumFaces() const { return mesh_.n_faces(); }

  // 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,
                 mesh_.vertex_handle(static_cast<unsigned int>(i)),
                 (typename Mesh::HalfedgeHandle)(-1), 
                 (typename Mesh::FaceHandle)(-1));

    createVBO();
    rebuild_ = REBUILD_NONE;
    return;
  }

  invalidateFullVBO();


  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
    for (size_t i = 0; i < numVerts_; ++i)
    {
      // 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
  if (halfedgeNormalMode_ && mesh_.has_halfedge_normals())
    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)
        {
          size_t numAttribs = baseProp->n_elements();
          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
DrawMeshT<Mesh>::readVertex(size_t _vertex,
                            const typename Mesh::VertexHandle&   _vh,
                            const typename Mesh::HalfedgeHandle& _hh,
                            const typename Mesh::FaceHandle&     _fh)
{
  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
DrawMeshT<Mesh>::getVertexColor(const typename Mesh::VertexHandle& _vh)
{
  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
DrawMeshT<Mesh>::getFaceColor(const typename Mesh::FaceHandle& _fh)
{
  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);

  // non indexed vbo needs updating now
  invalidateFullVBO();
}

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];
// 
1119
//     glBufferData(GL_ELEMENT_ARRAY_BUFFER_ARB, numTris_ * 3 * sizeof(unsigned short), pwIndices, GL_STATIC_DRAW_ARB);
Jan Möbius's avatar
Jan Möbius committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
//   }
//   else
  createIndexBuffer();


  // line index buffer:
  if (mesh_.n_edges())
  {
    std::vector<unsigned int> lineBuffer(mesh_.n_edges() * 2);

    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)
      {
        // 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;
      }
      else
      {
        lineBuffer[2 * i] = invVertexMap_[mesh_.from_vertex_handle(hh).idx()];
        lineBuffer[2 * i + 1] = invVertexMap_[mesh_.to_vertex_handle(hh).idx()];
      }
    }

    bindLineIbo();

    fillLineBuffer(mesh_.n_edges(), &lineBuffer[0]);
  }

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

template <class Mesh>
DrawMeshT<Mesh>::~DrawMeshT(void)
{
  delete [] invVertexMap_;
1159
  delete meshComp_;
Jan Möbius's avatar
Jan Möbius committed
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
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
}



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()
{
  // r