globjects.cc 36.5 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
42
43
44
45
46
47
48
49
50
51
52
53
/*===========================================================================*\
 *                                                                           *
 *                              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.              *
 *                                                                           *
 \*===========================================================================*/

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

#include <ACG/GL/acg_glew.hh>
#include <ACG/GL/globjects.hh>
#include <ACG/GL/GLFormatInfo.hh>
#include <ACG/ShaderUtils/GLSLShader.hh>
54
#include <ACG/Utils/ImageConversion.hh>
Jan Möbius's avatar
Jan Möbius committed
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
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

#include <QImage>
#include <QGLWidget>

namespace ACG {


//-----------------------------------------------------------------------------

Texture::Texture( GLenum tgt, GLenum _unit )
  : target(tgt), unit(_unit), valid(false), texture(0u), internalFormat_(0)
{
}

void Texture::bindAsImage(GLuint _index, GLenum _access)
{
#if defined(GL_ARB_shader_image_load_store)
  if (is_valid())
    glBindImageTexture(_index, id(), 0, GL_FALSE, 0, _access, getInternalFormat());
  else
    std::cerr << "Texture::bindAsImage - error: texture not initialized!" << std::endl;
#else
  std::cerr << "Texture::bindAsImage - glBindImageTexture symbol not loaded!" << std::endl;
#endif
}


GLint Texture::getInternalFormat()
{
  if (!internalFormat_)
  {
    bind();
    glGetTexLevelParameteriv(target, 0, GL_TEXTURE_INTERNAL_FORMAT, &internalFormat_);
  }

  return internalFormat_;
}
// 
// bool Texture::clear( float _color )
// {
// #ifdef GL_ARB_clear_texture
//   if (supportsClearTexture() && texture)
//   {
//     glClearTexImage(texture, 0, GL_R32F, GL_FLOAT, &_color);
//     return true;
//   }
// #endif
//   return false;
// }
// 
// bool Texture::clear( const ACG::Vec2f& _color )
// {
// #ifdef GL_ARB_clear_texture
//   if (supportsClearTexture() && texture)
//   {
//     glClearTexImage(texture, 0, GL_RG32F, GL_FLOAT, _color.data());
//     return true;
//   }
// #endif
//   return false;
// }
// 
// bool Texture::clear( const ACG::Vec3f& _color )
// {
// #ifdef GL_ARB_clear_texture
//   if (supportsClearTexture() && texture)
//   {
//     glClearTexImage(texture, 0, GL_RGB32F, GL_FLOAT, _color.data());
//     return true;
//   }
// #endif
//   return false;
// }

bool Texture::clear( const ACG::Vec4f& _color )
{
#ifdef GL_ARB_clear_texture
  if (supportsClearTexture() && texture)
  {
    glClearTexImage(texture, 0, GL_RGBA, GL_FLOAT, _color.data());
    return true;
  }
#endif
  return false;
}

bool Texture::clear( const ACG::Vec4ui& _color )
{
#ifdef GL_ARB_clear_texture
  if (supportsClearTexture() && texture)
  {
    glClearTexImage(texture, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, _color.data());
    return true;
  }
#endif
  return false;
}

bool Texture::clear( const ACG::Vec4i& _color )
{
#ifdef GL_ARB_clear_texture
  if (supportsClearTexture() && texture)
  {
    glClearTexImage(texture, 0, GL_RGBA_INTEGER, GL_INT, _color.data());
    return true;
  }
#endif
  return false;
}

bool Texture::supportsImageLoadStore()
{
  static int status = -1;

  if (status < 0)
  {
#if defined(GL_ARB_shader_image_load_store)
    // core in version 4.2
    status = checkExtensionSupported("ARB_shader_image_load_store") || openGLVersion(4,2);
#else
    // symbol missing, install latest glew version
    status = 0;
#endif
  }

  return status > 0;
}


bool Texture::supportsTextureBuffer()
{
  static int status = -1;

  if (status < 0)
  {
    // core in version 3.0
    status = checkExtensionSupported("ARB_texture_buffer_object") || openGLVersion(3,0);
  }

  return status > 0;
}


bool Texture::supportsClearTexture()
{
  static int status = -1;

  if (status < 0)
  {
#if defined(GL_ARB_clear_texture)
    status = checkExtensionSupported("ARB_clear_texture");
#else
    // symbol missing, install latest glew version
    status = 0;
#endif
  }

  return status > 0;
}

bool Texture::supportsGenerateMipmap()
{
  static int status = -1;

  if (status < 0)
  {
#if defined(GL_SGIS_generate_mipmap)
    status = checkExtensionSupported("GL_SGIS_generate_mipmap");
#else
    // symbol missing, install latest glew version
    status = 0;
#endif
  }

  return status > 0;
}

//-----------------------------------------------------------------------------


Texture1D::Texture1D( GLenum unit ) : Texture(GL_TEXTURE_1D, unit),
  width_(0),
  format_(0), type_(0)
{}

void Texture1D::setData(GLint _level, 
  GLint _internalFormat, 
  GLsizei _width, 
  GLenum _format,
  GLenum _type,
  const GLvoid* _data) {

    bind();

    glTexImage1D(GL_TEXTURE_1D, _level, _internalFormat, _width, 0, _format, _type, _data);

    width_ = _width;
    internalFormat_ = _internalFormat;
    format_ = _format;
    type_ = _type;
}


void Texture1D::setStorage( GLsizei _levels, GLenum _internalFormat, GLsizei _width ) {
#ifdef GL_ARB_texture_storage
  bind();
  glTexStorage1D(GL_TEXTURE_1D, _levels, _internalFormat, _width);

  width_ = _width;
  internalFormat_ = _internalFormat;

  GLFormatInfo finfo(_internalFormat);
  format_ = finfo.format();
  type_ = finfo.type();
#endif // GL_ARB_texture_storage
}


bool Texture1D::getData( GLint _level, void* _dst ) {
  if (is_valid()) {
    GLint curTex = 0;
    glGetIntegerv(GL_TEXTURE_BINDING_1D, &curTex);

    bind();
    glGetTexImage(GL_TEXTURE_1D, _level, format_, type_, _dst);

    glBindTexture(GL_TEXTURE_1D, curTex);

    return true;
  }
  return false;
}

bool Texture1D::getData( GLint _level, std::vector<char>& _dst ) {
  if (is_valid()) {

    GLFormatInfo finfo(internalFormat_);

    if (finfo.isValid()) {
      size_t bufSize = finfo.elemSize() * width_;

      if (_dst.size() < bufSize)
        _dst.resize(bufSize);

      if (!_dst.empty())
        return getData(_level, &_dst[0]);
    }
  }
  return false;
}





//-----------------------------------------------------------------------------

Texture2D::Texture2D(GLenum unit)
  : Texture(GL_TEXTURE_2D, unit),
  width_(0), height_(0),
  format_(0), type_(0),
  buildMipsCPU_(false)
{}

//-----------------------------------------------------------------------------

bool Texture2D::autogenerateMipMaps()
{
Kersten Schuster's avatar
Kersten Schuster committed
323
324
325
326
327
328
329
    if(openGLVersion(3,0))
    {
        // From OpenGL 3.0, glGenerateMipmap is supported and we should use that
        // but glGenerateMipmap must be called AFTER the data was uploaded.
        return false;
    }

Jan Möbius's avatar
Jan Möbius committed
330
331
332
#ifdef GL_SGIS_generate_mipmap
  if (supportsGenerateMipmap())
  {
333
      parameter(GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
Jan Möbius's avatar
Jan Möbius committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    return true;
  }
#endif
  // hardware accelerated generation is not available, fall back to software implementation
  buildMipsCPU_ = true;
  return false;
}

//-----------------------------------------------------------------------------

void Texture2D::disableAutogenerateMipMaps()
{
#ifdef GL_SGIS_generate_mipmap
  if (supportsGenerateMipmap())
    parameter(GL_GENERATE_MIPMAP_SGIS, GL_FALSE);
#endif
  buildMipsCPU_ = false;
}

//-----------------------------------------------------------------------------

Kersten Schuster's avatar
Kersten Schuster committed
355
356
357
358
void Texture2D::setData(GLint _level,
  GLint _internalFormat,
  GLsizei _width,
  GLsizei _height,
Jan Möbius's avatar
Jan Möbius committed
359
360
  GLenum _format,
  GLenum _type,
Kersten Schuster's avatar
Kersten Schuster committed
361
362
  const GLvoid* _data,
  bool _mipmaps) {
Jan Möbius's avatar
Jan Möbius committed
363
364
365
366
367
368
369
370
371
372
373

  if (getUnit() == GL_NONE)
    setUnit(GL_TEXTURE0);

  bind();

  if (buildMipsCPU_ && _level == 0)
    buildMipMaps(_internalFormat, _width, _height, _format, _type, _data);
  else
    glTexImage2D(GL_TEXTURE_2D, _level, _internalFormat, _width, _height, 0, _format, _type, _data);

Kersten Schuster's avatar
Kersten Schuster committed
374
375
376
377
  // If mip maps should not be built on cpu and the OpenGL version is high enough, we go the default way
  if(_mipmaps && !buildMipsCPU_ && openGLVersion(3,0))
      glGenerateMipmap(GL_TEXTURE_2D);

Jan Möbius's avatar
Jan Möbius committed
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
  width_ = _width;
  height_ = _height;
  internalFormat_ = _internalFormat;
  format_ = _format;
  type_ = _type;
}


void Texture2D::setStorage( GLsizei _levels, GLenum _internalFormat, GLsizei _width, GLsizei _height ) {
#ifdef GL_ARB_texture_storage
  bind();
  glTexStorage2D(GL_TEXTURE_2D, _levels, _internalFormat, _width, _height);

  width_ = _width;
  height_ = _height;
  internalFormat_ = _internalFormat;

  GLFormatInfo finfo(_internalFormat);
  format_ = finfo.format();
  type_ = finfo.type();
#endif // GL_ARB_texture_storage
}


bool Texture2D::getData( GLint _level, void* _dst ) {
  if (is_valid()) {
    GLint curTex = 0;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, &curTex);

    bind();
    glGetTexImage(GL_TEXTURE_2D, _level, format_, type_, _dst);

    glBindTexture(GL_TEXTURE_2D, curTex);

    return true;
  }
  return false;
}

bool Texture2D::getData( GLint _level, std::vector<char>& _dst ) {
  if (is_valid()) {

    GLFormatInfo finfo(internalFormat_);

    if (finfo.isValid()) {
      size_t bufSize = finfo.elemSize() * width_ * height_;

      if (_dst.size() < bufSize)
        _dst.resize(bufSize);

      if (!_dst.empty())
        return getData(_level, &_dst[0]);
    }
  }
  return false;
}

template<class T>
void Texture2D_buildMipMaps_DataInterpreter(Vec4f* _dst, int _numChannels, int _srcOffset, const void* _src)
{
  const T* dataT = static_cast<const T*>(_src);

  for (int i = 0; i < _numChannels; ++i)
    (*_dst)[i] = float(dataT[_srcOffset + i]);
}

void Texture2D::buildMipMaps( GLenum _internalfmt, 
  GLint _width, 
  GLint _height,
  GLenum _format,
  GLenum _type, 
  const void* _data )
{
//   gluBuild2DMipmaps(_target, _internalfmt, _width, _height, _format, _type, _data);
//   return;
// 
  if (_data)
  {
    GLFormatInfo finfo(_internalfmt);

    if (finfo.isValid() && (finfo.isFloat() || finfo.isNormalized()))
    {
      int numChannels = finfo.channelCount();


      // avoid quantization error for smaller mipmaps
      // -> treat image data as floats instead of normalized ubytes


      // compute number of mipmaps

      Vec2i curSize = Vec2i(_width, _height);

      std::vector<int> mipMemsize(1, 0);
      std::vector<Vec2i> mipSize(1, curSize);
      // mipmap count is usually a small number, so push_back() shouldn't be problematic
      mipMemsize.reserve(16);
      mipSize.reserve(16);

      int numMips = 1; // first level

      // downscale width and height by 2 until 1x1 texture
      while (curSize[0] > 1 || curSize[1] > 1)
      {
        for (int k = 0; k < 2; ++k)
          curSize[k] = std::max(1, curSize[k] >> 1);

        // tex dimension
        mipSize.push_back(curSize);

        // size in bytes
        int numPixels = curSize[0] * curSize[1];
        mipMemsize.push_back(numPixels * numChannels * 4);

        ++numMips;
      }

      // compute size in bytes required for the complete mipmap chain starting at level 1
      std::vector<int> mipOffset; // offset in bytes
      mipOffset.reserve(16);
      int totalMemSize = 0;
      for (int mipID = 0; mipID < numMips; ++mipID)
      {
        mipOffset.push_back(totalMemSize);
        totalMemSize += mipMemsize[mipID];
      }


      // alloc memory block for the mipmaps
      std::vector<float> mipData(totalMemSize / 4);

      // downsample
      for (int mipID = 1; mipID < numMips; ++mipID)
      {
        Vec2i srcSize = mipSize[mipID-1];
        Vec2i dstSize = mipSize[mipID];

        int srcOffset = mipOffset[mipID-1];
        int dstOffset = mipOffset[mipID];

        int dstNumPixels = dstSize[0] * dstSize[1];

        // loop is parallelizable, but synchronization overhead is too high
// #ifdef USE_OPENMP
// #pragma omp parallel for
// #endif // USE_OPENMP
        for (int dstPixel = 0; dstPixel < dstNumPixels; ++dstPixel)
        {
          int x = dstPixel % dstSize[0];
          int y = dstPixel / dstSize[0];

          Vec4f pixelData[4];

          Vec2i srcPixelPos[4] =
          {
            Vec2i(x * 2, y * 2), Vec2i(x * 2 + 1, y * 2),
            Vec2i(x * 2, y * 2 + 1), Vec2i(x * 2 + 1, y * 2 + 1)
          };

          Vec4f avgColor = Vec4f(0.0f, 0.0f, 0.0f, 0.0f);

          // load the four source pixels
          for (int srcPixel = 0; srcPixel < 4; ++srcPixel)
          {
            // init with black
            pixelData[srcPixel] = Vec4f(0.0f, 0.0f, 0.0f, 1.0f);

            // clamp pixel position 
            srcPixelPos[srcPixel][0] = std::min(srcPixelPos[srcPixel][0], srcSize[0] - 1);
            srcPixelPos[srcPixel][1] = std::min(srcPixelPos[srcPixel][1], srcSize[1] - 1);

            // linear position of 2d pixel pos, row-major
            int srcPixelPosLinear = srcSize[0] * srcPixelPos[srcPixel][1] + srcPixelPos[srcPixel][0];

            // interpret pixel of the input image based on type
            if (mipID == 1)
            {
              switch ( _type )
              {
              case GL_DOUBLE: Texture2D_buildMipMaps_DataInterpreter<double>(pixelData + srcPixel, numChannels, srcPixelPosLinear * numChannels, _data); break;
              case GL_FLOAT: Texture2D_buildMipMaps_DataInterpreter<float>(pixelData + srcPixel, numChannels, srcPixelPosLinear * numChannels, _data); break;
              case GL_INT: Texture2D_buildMipMaps_DataInterpreter<int>(pixelData + srcPixel, numChannels, srcPixelPosLinear * numChannels, _data); break;
              case GL_UNSIGNED_INT: Texture2D_buildMipMaps_DataInterpreter<unsigned int>(pixelData + srcPixel, numChannels, srcPixelPosLinear * numChannels, _data); break;
              case GL_SHORT: Texture2D_buildMipMaps_DataInterpreter<short>(pixelData + srcPixel, numChannels, srcPixelPosLinear * numChannels, _data); break;
              case GL_UNSIGNED_SHORT: Texture2D_buildMipMaps_DataInterpreter<unsigned short>(pixelData + srcPixel, numChannels, srcPixelPosLinear * numChannels, _data); break;
              case GL_BYTE:
                {
                  Texture2D_buildMipMaps_DataInterpreter<char>(pixelData + srcPixel, numChannels, srcPixelPosLinear * numChannels, _data);

                  if (finfo.isNormalized())
                    pixelData[srcPixel] /= 127.0f;
                } break;
              case GL_UNSIGNED_BYTE:
                {
                  Texture2D_buildMipMaps_DataInterpreter<unsigned char>(pixelData + srcPixel, numChannels, srcPixelPosLinear * numChannels, _data);

                  if (finfo.isNormalized())
                    pixelData[srcPixel] /= 255.0f;
                } break;

              default: std::cerr << "MipMaps: unknown data type: " << _type << std::endl;
              }
            }
            else
            {
              // load from previously computed mipmap

              for (int c = 0; c < numChannels; ++c)
                pixelData[srcPixel][c] = mipData[srcOffset/4 + srcPixelPosLinear * numChannels + c];
            }

            avgColor += pixelData[srcPixel];
          }

          avgColor *= 0.25f;

          // store average of the source pixels
          int dstPixelPosLinear = y * dstSize[0] + x;
          for (int c = 0; c < numChannels; ++c)
            mipData[dstOffset / 4 + dstPixelPosLinear * numChannels + c] = avgColor[c];
        }

      }


      // upload mipmaps to gpu

      for (int mipID = 0; mipID < numMips; ++mipID)
      {
        // inpute image at level 0
        const void* mipDataPtr = _data;
        GLenum mipDataType = _type;

        if (mipID > 0)
        {
          // downsampled image at lower levels
          // these are stored as float textures in memory
          // glTexImage2D converts float data to the requested internal format
          mipDataPtr = &mipData[mipOffset[mipID] / 4];
          mipDataType = GL_FLOAT;
        }

        glTexImage2D(getTarget(), mipID, _internalfmt, mipSize[mipID][0], mipSize[mipID][1], 0, _format, mipDataType, mipDataPtr);
      }
    }
  }
}


bool Texture2D::loadFromFile( const std::string& _filename, GLenum _minFilter, GLenum _magFilter )
{
  bool success = false;

  const int numMipmapEnums = 4;
  GLenum mipmapEnums[numMipmapEnums] = {GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_LINEAR};
  bool mipmaps = false;

  for (int i = 0; i < numMipmapEnums; ++i)
    mipmaps = mipmaps || _minFilter == mipmapEnums[i];

  if (!_filename.empty())
  {
    bind();

    QImage qtex;

    if (qtex.load(_filename.c_str()))
    {
      success = true;

      if (mipmaps)
        autogenerateMipMaps();

651
      QImage gltex = ACG::Util::convertToGLFormat(qtex);
Jan Möbius's avatar
Jan Möbius committed
652

Kersten Schuster's avatar
Kersten Schuster committed
653
      setData(0, GL_RGBA, gltex.width(), gltex.height(), GL_RGBA, GL_UNSIGNED_BYTE, gltex.bits(), mipmaps);
Jan Möbius's avatar
Jan Möbius committed
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
    }

  }

  if (success)
  {
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, _minFilter);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, _magFilter);
  }

  return success;
}


void Texture2D::loadRandom( GLint _internalFormat, GLsizei _width, GLsizei _height )
{
  ACG::GLFormatInfo finfo(_internalFormat);

  if (finfo.isValid() && _width && _height)
  {
    int n = _width * _height * finfo.channelCount();

    GLvoid* dataPtr = 0;

    std::vector<float> randF;
    std::vector<int> randI;

    GLenum gltype = 0;

    if (finfo.isFloat() || finfo.isNormalized())
    {
      randF.resize(n);

      bool isSigned = finfo.isInt();

      for (int i = 0; i < n; ++i)
      {
        float r = float(rand()) / float(RAND_MAX);

        if (isSigned)
          r = r * 2.0f - 1.0f;

        randF[i] = r;
      }

      dataPtr = &randF[0];
      gltype = GL_FLOAT;
    }
    else
    {
      randI.resize(n);

      for (int i = 0; i < n; ++i)
        randI[i] = rand();

      dataPtr = &randI[0];
      gltype = GL_INT;
    }
    
    bind();
    setData(0, _internalFormat, _width, _height, finfo.format(), gltype, dataPtr);
  }
}

bool Texture2D::checkTextureMem( GLenum _internalFormat, GLsizei _width, GLsizei _height, GLenum _format)
{
  GLuint t = 0;
  glGenTextures(1, &t);

  bool res = false;

  if (t)
  {
    GLint savedTex = 0;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, &savedTex);


    glBindTexture(GL_TEXTURE_2D, t);
    glTexImage2D(GL_PROXY_TEXTURE_2D, 0, _internalFormat, _width, _height, 0, _format, GL_FLOAT, 0);

    GLint w = 0;
    glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
    if (w) 
      res = true;

    glBindTexture(GL_TEXTURE_2D, savedTex);
    glDeleteTextures(1, &t);
  }

  return res;
}

//-----------------------------------------------------------------------------

#if defined(GL_VERSION_1_5)

void VertexBufferObject::del() {
    if (valid)
        glDeleteBuffers(1, &vbo);
    valid = false;
}

void VertexBufferObject::upload(
        GLsizeiptr size, const GLvoid* data, GLenum usage) {

  if (!valid)
    gen();
  
  bind();

  glBufferData(target, size, data, usage);
}

void VertexBufferObject::uploadSubData(
        GLuint _offset, GLuint _size, const GLvoid* _data ) {

  glBufferSubData(target, _offset, _size, _data);
}

void VertexBufferObject::gen() {
    glGenBuffers(1, &vbo);
    if(vbo > 0u)
        valid = true;
}

int VertexBufferObject::size() {
  bind();
  int bufsize = 0;
  glGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufsize);
  return bufsize;
}

#endif


//-----------------------------------------------------------------------------

TextureBuffer::TextureBuffer(GLenum u)
  : 
Texture(GL_TEXTURE_BUFFER, u), 
  bufferSize_(0), buffer_(0), usage_(0), fmt_(0) {
}


TextureBuffer::~TextureBuffer() {
  if (buffer_)
    glDeleteBuffers(1, &buffer_);
}

void TextureBuffer::setBufferData(
        size_t _size, const void* _data, GLenum _internalFormat, GLenum _usage) {
805
806
if(!ACG::compatibilityProfile())
{
Jan Möbius's avatar
Jan Möbius committed
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
  if (supportsTextureBuffer()) {
    // setup buffer object
    if (!buffer_)
        glGenBuffers(1, &buffer_);

    glBindBuffer(GL_TEXTURE_BUFFER, buffer_);
    glBufferData(GL_TEXTURE_BUFFER, static_cast<GLsizei>(_size), _data, _usage);

    usage_ = _usage;
    fmt_ = _internalFormat;

    // bind buffer to texture
    if (getUnit() == GL_NONE)
        setUnit(GL_TEXTURE0);

    bind();

    glTexBuffer(GL_TEXTURE_BUFFER, _internalFormat, buffer_);

    bufferSize_ = _size;
  }
  else
    std::cerr << "TextureBuffer::setData - gpu does not support buffer textures!" << std::endl;
830
831
832
} else{
  std::cerr << "TextureBuffer::setData - currently only in core profile available!" << std::endl;
}
Jan Möbius's avatar
Jan Möbius committed
833
834
835
}

bool TextureBuffer::getBufferData(void* _dst) {
836
837
if(!ACG::compatibilityProfile())
{
Jan Möbius's avatar
Jan Möbius committed
838
839
840
841
842
843
844
  if (buffer_) {
    glBindBuffer(GL_TEXTURE_BUFFER, buffer_);
    glGetBufferSubData(GL_TEXTURE_BUFFER, 0, bufferSize_, _dst);
    return true;
  }
  else
    std::cerr << "TextureBuffer::getBufferData - gpu does not support buffer textures!" << std::endl;
845
846
847
}else{
    std::cerr << "TextureBuffer::getBufferData - currently only in core profile available!" << std::endl;
}
Jan Möbius's avatar
Jan Möbius committed
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
  return false;
}

bool TextureBuffer::getBufferData(std::vector<char>& _dst) {
  if (_dst.size() < size_t(bufferSize_))
    _dst.resize(bufferSize_);

  if (!_dst.empty())
    return getBufferData(&_dst[0]);

  return false;
}



//-----------------------------------------------------------------------------


#if defined(GL_NV_vertex_program) || defined(GL_NV_fragment_program)

void ProgramBaseNV::bind() {
    if (!valid)
        gen();
    glBindProgramNV(target, program);
}

void ProgramBaseNV::unbind() {
    glBindProgramNV(target, 0);
}

bool ProgramBaseNV::load(const char* prog_text) {
    int size = int(strlen(prog_text));
    if (!valid)
        gen();
    glLoadProgramNV(target, program, size, (const GLubyte *) prog_text);
    GLint errpos;
    glGetIntegerv(GL_PROGRAM_ERROR_POSITION_NV, &errpos);
    if (errpos != -1) {
        fprintf(stderr, "\nprogram error:\n");
        int bgn = std::max(0, errpos - 10), end = std::min(size, bgn + 30);
        for (int i = bgn; i < end; ++i)
            fputc(prog_text[i], stderr);
        fputc('\n', stderr);
        return false;
    }
    return true;
}


void ProgramBaseNV::gen() {
    glGenProgramsNV(1, &program);
    valid = true;
}

void ProgramBaseNV::del() {
    if (valid)
        glDeleteProgramsNV(1, &program);
    valid = false;
}

#endif

#if defined(GL_ARB_vertex_program) || defined(GL_ARB_fragment_program)

void ProgramBaseARB::bind() {
    if (!valid)
        gen();
    glBindProgramARB(target, program);
}
void ProgramBaseARB::unbind() {
    glBindProgramARB(target, 0);
}

bool ProgramBaseARB::load(const char* prog_text) {
    int size = int(strlen(prog_text));
    if (!valid)
        gen();
    bind();
    glProgramStringARB(target, GL_PROGRAM_FORMAT_ASCII_ARB, size, prog_text);
    GLint errpos;
    glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errpos);
    if (errpos != -1) {
        fprintf(stderr, "\nprogram error:\n");
        int bgn = std::max(0, errpos - 10), end = std::min(size, bgn + 30);
        for (int i = bgn; i < end; ++i)
            fputc(prog_text[i], stderr);
        fputc('\n', stderr);
        return false;
    }
    return true;
}

void ProgramBaseARB::gen() {
    glGenProgramsARB(1, &program);
    valid = true;
}
void ProgramBaseARB::del() {
    if (valid)
        glDeleteProgramsARB(1, &program);
    valid = false;
}

#endif // GL_ARB_vertex_program


//-----------------------------------------------------------------------------

// support state unknown : -1
int VertexArrayObject::supportStatus_ = -1;

VertexArrayObject::VertexArrayObject() 
  : id_(0)
{
}

VertexArrayObject::~VertexArrayObject()
{
#ifdef GL_ARB_vertex_array_object
  if (id_)
    glDeleteVertexArrays(1, &id_);
#endif
}


void VertexArrayObject::bind()
{
#ifdef GL_ARB_vertex_array_object
  if (!id_)
    init();

  if (id_)
    glBindVertexArray(id_);
#endif
}

void VertexArrayObject::unbind()
{
#ifdef GL_ARB_vertex_array_object
  glBindVertexArray(0);
#endif
}

void VertexArrayObject::init()
{
#ifdef GL_ARB_vertex_array_object
  if (id_)
    glDeleteVertexArrays(1, &id_);

  glGenVertexArrays(1, &id_);
#endif
}

bool VertexArrayObject::isSupported()
{
#ifndef GL_ARB_vertex_array_object
  // missing definition in gl header!
  supportStatus_ = 0;
#else

  if (supportStatus_ < 0)
    supportStatus_ = checkExtensionSupported("GL_ARB_vertex_array_object") ? 1 : 0;
1009
1010
  if( openGLVersion(3,2) )
      return true;
Jan Möbius's avatar
Jan Möbius committed
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
1119
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
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
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
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
#endif

  return supportStatus_ > 0;
}



//-----------------------------------------------------------------------------



// support state unknown : -1
int AtomicCounter::supportStatus_ = -1;

AtomicCounter::AtomicCounter(int _numCounters)
  : numCounters_(_numCounters), buffer_(0)
{
}

AtomicCounter::~AtomicCounter()
{
  if (buffer_)
    glDeleteBuffers(1, &buffer_);
}

void AtomicCounter::init()
{
  // check support and initialize
#ifdef GL_ARB_shader_atomic_counters
  if (isSupported() && numCounters_ > 0)
  {
    glGenBuffers(1, &buffer_);
    bind();
    glBufferData(GL_ATOMIC_COUNTER_BUFFER, numCounters_ * sizeof(unsigned int), 0, GL_DYNAMIC_COPY);
    unbind();
  }
#endif

  if (!isValid())
    std::cerr << "atomic counter failed to initialize!" << std::endl;
}

void AtomicCounter::bind()
{
#ifdef GL_ARB_shader_atomic_counters
  // implicit initialization
  if (!isValid())
    init();

  if (isValid())
    glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, buffer_);
#endif
}

void AtomicCounter::bind(GLuint _index)
{
#ifdef GL_ARB_shader_atomic_counters
  // implicit initialization
  if (!isValid())
    init();

  if (isValid())
    glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, _index, buffer_);
#endif
}

void AtomicCounter::unbind()
{
#ifdef GL_ARB_shader_atomic_counters
  glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0);
#endif
}

void AtomicCounter::set(unsigned int _value)
{
#ifdef GL_ARB_shader_atomic_counters
  // implicit initialization
  bind();

  if (isValid())
  {
    const size_t bufSize = numCounters_ * sizeof(unsigned int);
    //     unsigned int* bufData = new unsigned int[numCounters_];
    //     memset(bufData, int(_value), bufSize);
    // 
    //     glBufferSubData(GL_ATOMIC_COUNTER_BUFFER, 0, bufSize, bufData);
    //     delete [] bufData;

    void* bufPtr = glMapBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, bufSize, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
    memset(bufPtr, int(_value), bufSize);
    glUnmapBuffer(GL_ATOMIC_COUNTER_BUFFER);

    unbind();
  }
#endif
}

void AtomicCounter::get(unsigned int* _out)
{
#ifdef GL_ARB_shader_atomic_counters
  if (isValid())
  {
    bind();

    const size_t bufSize = numCounters_ * sizeof(unsigned int);

    // doesnt work, driver crash on ati:
    //    glGetBufferSubData(GL_ATOMIC_COUNTER_BUFFER, 0, bufSize, _out);

    void* bufPtr = glMapBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, bufSize, GL_MAP_READ_BIT);
    memcpy(_out, bufPtr, bufSize);
    glUnmapBuffer(GL_ATOMIC_COUNTER_BUFFER);

    unbind();
  }
#endif
}

bool AtomicCounter::isSupported()
{
#ifndef GL_ARB_shader_atomic_counters
  // missing definition in gl header!
  supportStatus_ = 0;
#else

  if (supportStatus_ < 0)
    supportStatus_ = checkExtensionSupported("GL_ARB_shader_atomic_counters") ? 1 : 0;
#endif

  return supportStatus_ > 0;
}

bool AtomicCounter::isValid() const
{
  return buffer_ && numCounters_ > 0;
}

//-----------------------------------------------------------------------------

QueryObject::QueryObject(GLenum _type) 
  : id_(0), state_(-1), type_(_type)
{

}

QueryObject::~QueryObject()
{
  if (id_)
    glDeleteQueries(1, &id_);
}

void QueryObject::begin()
{
  if (!id_)
    glGenQueries(1, &id_);

  glBeginQuery(type_, id_);
  state_ = 0;
}

void QueryObject::end()
{
  if (!state_)
  {
    glEndQuery(type_);
    state_ = 1;
  }
}

bool QueryObject::available() const
{
  GLint r = GL_FALSE;
  if (state_ > 0)
    glGetQueryObjectiv(id_, GL_QUERY_RESULT_AVAILABLE, &r);
  return r != GL_FALSE;
}

GLuint QueryObject::result() const
{
  GLuint r = 0xffffffff;
  if (state_ > 0)
    glGetQueryObjectuiv(id_, GL_QUERY_RESULT, &r);
  return r;
}


//-----------------------------------------------------------------------------

int QueryCounter::supportStatus_ = -1;

QueryCounter::QueryCounter()
  : state_(-1)
{
  queryObjects_[0] = queryObjects_[1] = 0;
}

QueryCounter::~QueryCounter()
{
  if (queryObjects_[0])
    glDeleteQueries(2, queryObjects_);
}


void QueryCounter::restart()
{
#ifdef GL_ARB_timer_query
  if (isSupported())
  {
    state_ = 0;

    if (!queryObjects_[0])
      glGenQueries(2, queryObjects_);

    glQueryCounter(queryObjects_[0], GL_TIMESTAMP);
  }
#endif
}

void QueryCounter::stop()
{
#ifdef GL_ARB_timer_query
  if (state_ == 0)
  {
    glQueryCounter(queryObjects_[1], GL_TIMESTAMP);
    ++state_;
  }
#endif
}

GLuint64 QueryCounter::elapsedNs()
{
  GLuint64 timing = 0;
#ifdef GL_ARB_timer_query
  stop();

  if (state_ == 1)
  {
    GLint available = 0;
    while (!available)
      glGetQueryObjectiv(queryObjects_[1], GL_QUERY_RESULT_AVAILABLE, &available);

    GLuint64 timeStart;
    glGetQueryObjectui64v(queryObjects_[0], GL_QUERY_RESULT, &timeStart);
    glGetQueryObjectui64v(queryObjects_[1], GL_QUERY_RESULT, &timing);
    timing -= timeStart;
  }
#endif
  return timing;
}

GLuint64 QueryCounter::elapsedMs()
{
  return elapsedNs() / 1000;
}

float QueryCounter::elapsedSecs()
{
  GLuint64 ms = elapsedMs();

  return float(ms) / 1000.0f;
}

bool QueryCounter::isSupported()
{
#ifndef GL_ARB_timer_query
  // missing definition in gl header!
  supportStatus_ = 0;
#else

  if (supportStatus_ < 0)
    supportStatus_ = checkExtensionSupported("GL_ARB_timer_query") || openGLVersion(3,2) ? 1 : 0;
#endif

  return supportStatus_ > 0;
}


//-----------------------------------------------------------------------------


// support state unknown : -1
int UniformBufferObject::supportStatus_ = -1;
int UniformBufferObject::maxBlockSize_ = -1;
int UniformBufferObject::maxBindings_ = -1;
int UniformBufferObject::maxCombinedShaderBlocks_ = -1;
int UniformBufferObject::offsetAlignment_ = -1;

UniformBufferObject::UniformBufferObject()
  : VertexBufferObject(
#ifndef GL_ARB_uniform_buffer_object
  GL_NONE
#else
  GL_UNIFORM_BUFFER
#endif
  ),
  data_(0)
{
}

UniformBufferObject::~UniformBufferObject()
{
}

void UniformBufferObject::bind( GLuint _index )
{
#ifdef GL_ARB_uniform_buffer_object
  glBindBufferBase(GL_UNIFORM_BUFFER, _index, id());
#endif
}


bool UniformBufferObject::isSupported()
{
#ifndef GL_ARB_uniform_buffer_object
  // missing definition in gl header!
  supportStatus_ = 0;
#else

  if (supportStatus_ < 0)
    supportStatus_ = checkExtensionSupported("GL_ARB_uniform_buffer_object") ? 1 : 0;
#endif

  return supportStatus_ > 0;
}

void UniformBufferObject::queryCaps()
{
#ifdef GL_ARB_uniform_buffer_object
  if (isSupported())
  {
    glGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &maxBindings_);
    glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &maxBlockSize_);
    glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &maxCombinedShaderBlocks_);
    glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &offsetAlignment_);
  }
#endif
}

int UniformBufferObject::getMaxBindings()
{
  if (maxBindings_ < 0)
    queryCaps();

  return maxBindings_;
}

int UniformBufferObject::getMaxBlocksize()
{
  if (maxBlockSize_ < 0)
    queryCaps();

  return maxBlockSize_;
}

int UniformBufferObject::getMaxCombinedShaderBlocks()
{
  if (maxCombinedShaderBlocks_ < 0)
    queryCaps();

  return maxCombinedShaderBlocks_;
}

int UniformBufferObject::getOffsetAlignment()
{
  if (offsetAlignment_ < 0)
    queryCaps();

  return offsetAlignment_;
}

void UniformBufferObject::setUniformData( GLSL::Program* _prog, const char* _bufferName, const char* _uniformName, const void* _data, int _datasize, bool _delay )
{
  if (_prog && _bufferName && _uniformName && _data)
  {
    GLuint idx = _prog->getUniformBlockIndex(_bufferName);

    if (idx != GL_INVALID_INDEX)
    {
      size_t bufsize = size_t(_prog->getUniformBlockSize(idx));

      if (data_.size() != bufsize)
        data_.resize(bufsize, 0);

      int offset = -1;
      _prog->getUniformBlockOffsets(1, &_uniformName, &offset);

      if (offset >= 0)
      {
        memcpy(&data_[offset], _data, _datasize);

        if (!_delay)
        {
          VertexBufferObject::bind();

          if (size() != int(bufsize))
            VertexBufferObject::upload(bufsize, &data_[0], GL_DYNAMIC_DRAW);
          else
            uploadSubData(offset, _datasize, _data);
        }
      }
    }
  }
}

void UniformBufferObject::upload()
{
  if (!data_.empty())
  {
    VertexBufferObject::bind();

    VertexBufferObject::upload(data_.size(), &data_[0], GL_DYNAMIC_DRAW);
  }
}


//-----------------------------------------------------------------------------



// support state unknown : -1
int ShaderStorageBufferObject::supportStatus_ = -1;
int ShaderStorageBufferObject::maxBlockSize_ = -1;
int ShaderStorageBufferObject::maxBindings_ = -1;
int ShaderStorageBufferObject::maxCombinedShaderBlocks_ = -1;

ShaderStorageBufferObject::ShaderStorageBufferObject()
  : VertexBufferObject(
#ifndef GL_ARB_shader_storage_buffer_object
   GL_NONE
#else
   GL_SHADER_STORAGE_BUFFER
#endif
   )
{
}

ShaderStorageBufferObject::~ShaderStorageBufferObject()
{
}

void ShaderStorageBufferObject::bind( GLuint _index )
{
#ifdef GL_ARB_shader_storage_buffer_object
  glBindBufferBase(GL_SHADER_STORAGE_BUFFER, _index, id());
#endif
}

bool ShaderStorageBufferObject::isSupported()
{
#ifndef GL_ARB_shader_storage_buffer_object
  // missing definition in gl header!
  supportStatus_ = 0;
#else

  if (supportStatus_ < 0)
    supportStatus_ = checkExtensionSupported("GL_ARB_shader_storage_buffer_object") ? 1 : 0;
#endif

  return supportStatus_ > 0;
}

void ShaderStorageBufferObject::queryCaps()
{
#ifdef GL_ARB_shader_storage_buffer_object
  if (isSupported())
  {
    glGetIntegerv(GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS, &maxBindings_);
    glGetIntegerv(GL_MAX_SHADER_STORAGE_BLOCK_SIZE, &maxBlockSize_);
    glGetIntegerv(GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS, &maxCombinedShaderBlocks_);
  }
#endif
}

int ShaderStorageBufferObject::getMaxBindings()
{
  if (maxBindings_ < 0)
    queryCaps();

  return maxBindings_;
}

int ShaderStorageBufferObject::getMaxBlocksize()
{
  if (maxBlockSize_ < 0)
    queryCaps();

  return maxBlockSize_;
}

int ShaderStorageBufferObject::getMaxCombinedShaderBlocks()
{
  if (maxCombinedShaderBlocks_ < 0)
    queryCaps();

  return maxCombinedShaderBlocks_;
}





} /* namespace ACG */