IRenderer.cc 54.8 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
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
/*===========================================================================*\
 *                                                                           *
 *                              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$                                                       *
 *   $Author$                                                      *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

#include <ACG/GL/acg_glew.hh>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <QFile>
#include <QTextStream>

#include <ACG/GL/gl.hh>

#include <ACG/GL/IRenderer.hh>

#include <ACG/GL/VertexDeclaration.hh>
#include <ACG/GL/GLError.hh>

#include <ACG/GL/ShaderCache.hh>
#include <ACG/GL/ScreenQuad.hh>
#include <ACG/GL/FBO.hh>
#include <ACG/GL/globjects.hh>



namespace ACG
{

int IRenderer::maxClipDistances_ = -1;

IRenderer::IRenderer()
: numLights_(0), 
renderObjects_(0), 
depthMapUsed_(false), 
curViewerID_(0),
prevFbo_(0),
prevDrawBuffer_(GL_BACK),
prevFboSaved_(false),
85
prevVAO_(0),
Jan Möbius's avatar
Jan Möbius committed
86
87
depthCopyShader_(0),
errorDetectionLevel_(1),
88
coreProfile_(false),
Jan Möbius's avatar
Jan Möbius committed
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
enableLineThicknessGL42_(false)
{
  prevViewport_[0] = 0;
  prevViewport_[1] = 0;
  prevViewport_[2] = 0;
  prevViewport_[3] = 0;

  // set global ambient scale to default OpenGL value
  globalLightModelAmbient_ = ACG::Vec3f(0.2f, 0.2f, 0.2f);
}


IRenderer::~IRenderer()
{
  delete depthCopyShader_;

  // free depth map fbos
  for (std::map<int, ACG::FBO*>::iterator it = depthMaps_.begin(); it != depthMaps_.end(); ++it)
    delete it->second;
}

void IRenderer::addRenderObject(ACG::RenderObject* _renderObject)
{
  // avoid null-ptr access
  if (!_renderObject->debugName)
    _renderObject->debugName = "<unnamed>";

  if (_renderObject->name.empty())
    _renderObject->name = _renderObject->debugName;

  // do some more checks for error detection
  if (!_renderObject->vertexDecl && !_renderObject->vertexArrayObject)
    std::cout << "error: missing vertex declaration in renderobject: " << _renderObject->debugName << std::endl;
  else
  {
    if (errorDetectionLevel_ > 0)
    {
      // commonly encountered rendering errors

      if (!_renderObject->numIndices)
        std::cout << "warning: numIndices is 0 in renderobject: " << _renderObject->debugName << std::endl;

      //  Why is my object invisible/black?
      if (!_renderObject->depthWrite && 
        !_renderObject->colorWriteMask[0] && !_renderObject->colorWriteMask[1] &&
        !_renderObject->colorWriteMask[2] && !_renderObject->colorWriteMask[3])
        std::cout << "warning: depth write and color write disabled in renderobject: " << _renderObject->debugName << std::endl;

137
138
139
140
141
142
      // Why is gl_PointSize not working in shader?
#ifndef GL_PROGRAM_POINT_SIZE
      if (_renderObject->programPointSize)
        std::cout << "warning: GL_PROGRAM_POINT_SIZE requested but missing in opengl headers!" << std::endl;
#endif

Jan Möbius's avatar
Jan Möbius committed
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
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
      if (errorDetectionLevel_ > 1 && _renderObject->shaderDesc.shadeMode == SG_SHADE_UNLIT)
      {
        if (_renderObject->emissive.max() < 1e-3f)
          std::cout << "warning: unlit object rendered with black emissive color: " << _renderObject->debugName << std::endl;
        else
        {
          // rendering with clear color

          float clearColor[4];
          glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor);

          if (checkEpsilon(clearColor[0] - _renderObject->emissive[0]) &&
            checkEpsilon(clearColor[1] - _renderObject->emissive[1]) &&
            checkEpsilon(clearColor[2] - _renderObject->emissive[2]))
          {
            std::cout << "warning: unlit object rendered with clear color as emissive color: " << _renderObject->debugName << std::endl;
            std::cout << "         Should this be intentional, disable color writing instead via obj->glColorMask(0,0,0,0)" << std::endl;
          }
        }
      }

      if (_renderObject->textures().size())
      {
        // Why are my textures sampled as black?

        // mipmap enabled, but no mipmap chain provided?

        for (std::map<size_t,RenderObject::Texture>::const_iterator it = _renderObject->textures().begin();
          it != _renderObject->textures().end(); ++it)
        {
          if (it->second.type == GL_TEXTURE_BUFFER)
            continue; // skip texture buffers, for which testing for mipmaps would generate an error

          glBindTexture(it->second.type, it->second.id);

          GLint minFilter = GL_NONE;
          glGetTexParameteriv(it->second.type, GL_TEXTURE_MIN_FILTER, &minFilter);

          if (minFilter == GL_NEAREST_MIPMAP_LINEAR ||
            minFilter == GL_NEAREST_MIPMAP_NEAREST ||
            minFilter == GL_LINEAR_MIPMAP_LINEAR ||
            minFilter == GL_LINEAR_MIPMAP_NEAREST)
          {
            GLint maxLevel = 0;
            glGetTexParameteriv(it->second.type, GL_TEXTURE_MAX_LEVEL, &maxLevel);

            GLint texWidth = 0;
            glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &texWidth);

            GLint maxLod = -1;
            for (GLint lod = 0; lod < maxLevel && maxLod < 0; ++lod)
            {
              GLint lodWidth;
              glGetTexLevelParameteriv(GL_TEXTURE_2D, lod, GL_TEXTURE_WIDTH, &lodWidth);

              if (lodWidth <= 0 || lodWidth == GL_INVALID_VALUE)
                maxLod = lod-1;
            }

            if (maxLod <= 0 && texWidth > 1)
            {
              std::cout << "warning: texture is sampled with mipmapping, but no mipchain is present: " << _renderObject->debugName << " texid: " << it->second.id << std::endl;
              std::cout << "         automatically disabling mipmapping!!" << std::endl;

              GLint correctedFilter = GL_LINEAR;

              if (minFilter == GL_NEAREST_MIPMAP_LINEAR ||
                minFilter == GL_LINEAR_MIPMAP_LINEAR)
                correctedFilter = GL_LINEAR;
              else
                correctedFilter = GL_NEAREST;

              glTexParameteri(it->second.type, GL_TEXTURE_MIN_FILTER, correctedFilter);
            }
          }
        }

      }

      if (errorDetectionLevel_ > 1)
      {
        // Why is there nothing written to the depth-buffer?
        // this might very well be intentional, so put it in higher level

        if (_renderObject->depthWrite && !_renderObject->depthTest)
        {
          std::cout << "warning: trying to write to depth buffer with depth-testing disabled does not work in: " << _renderObject->debugName << std::endl;
          std::cout << "         If depth-writing was intended, enable depth-testing and set depth-func to GL_ALWAYS" << std::endl;
        }
      }

      if (!_renderObject->vertexArrayObject)
      {
        // Why are there gl errors and/or nothing gets drawn?
        if (_renderObject->shaderDesc.shadeMode != SG_SHADE_UNLIT)
        {
          // check for normals
          if (!_renderObject->vertexDecl->findElementByUsage(VERTEX_USAGE_NORMAL))
            std::cout << "warning: missing normals for lighting in renderobject: " << _renderObject->debugName << std::endl
                      << "         Set shadeMode to SG_SHADE_UNLIT or provide normals!" << std::endl;
        }

        if (_renderObject->shaderDesc.textured())
        {
          // check for texcoords
          if (!_renderObject->vertexDecl->findElementByUsage(VERTEX_USAGE_TEXCOORD))
            std::cout << "warning: missing texcoords for textured mode in renderobject: " << _renderObject->debugName << std::endl;
        }

        if (_renderObject->shaderDesc.vertexColors)
        {
          // check for vertex colors
          if (!_renderObject->vertexDecl->findElementByUsage(VERTEX_USAGE_COLOR))
            std::cout << "warning: missing colors for vertexcolor mode in renderobject: " << _renderObject->debugName << std::endl;
        }
      }


      // Why is alpha blending not work?
      if (fabsf(_renderObject->alpha - 1.0f) > 1e-3f && !(_renderObject->alphaTest || _renderObject->blending))
        std::cout << "warning: alpha value != 1 but no alpha blending or testing enabled in renderobject: " << _renderObject->debugName << std::endl;


#ifdef GL_ARB_tessellation_shader
      // Trying to render with tessellation shaders?
      const bool tessellationActive = !_renderObject->shaderDesc.tessControlTemplateFile.isEmpty() || !_renderObject->shaderDesc.tessEvaluationTemplateFile.isEmpty();
      bool tryToFixPatchInfo = false;
      if (tessellationActive && _renderObject->primitiveMode != GL_PATCHES)
      {
        std::cout << "error: tessellation shaders are not used with GL_PATCHES primitiveType in renderobject: " << _renderObject->debugName << std::endl;
        tryToFixPatchInfo = true;
      }

      if (tessellationActive && !_renderObject->patchVertices)
      {
        std::cout << "error: undefined patch size for tessellation in renderobject: " << _renderObject->debugName << std::endl;
        tryToFixPatchInfo = true;
      }

      if (tryToFixPatchInfo)
      {
        if (_renderObject->primitiveMode == GL_POINTS)
        {
          _renderObject->primitiveMode = GL_PATCHES;
          _renderObject->patchVertices = 1;
          std::cout << "warning: attempting to draw with patchVertices = 1 for tessellation in renderobject: " << _renderObject->debugName << std::endl;
        }
        else if (_renderObject->primitiveMode == GL_LINES)
        {
          _renderObject->primitiveMode = GL_PATCHES;
          _renderObject->patchVertices = 2;
          std::cout << "warning: attempting to draw with patchVertices = 2 for tessellation in renderobject: " << _renderObject->debugName << std::endl;
        }
        else if (_renderObject->primitiveMode == GL_TRIANGLES)
        {
          _renderObject->primitiveMode = GL_PATCHES;
          _renderObject->patchVertices = 3;
          std::cout << "warning: attempting to draw with patchVertices = 3 for tessellation in renderobject: " << _renderObject->debugName << std::endl;
        }
        else if (_renderObject->primitiveMode == GL_QUADS)
        {
          _renderObject->primitiveMode = GL_PATCHES;
          _renderObject->patchVertices = 4;
          std::cout << "warning: attempting to draw with patchVertices = 4 for tessellation in renderobject: " << _renderObject->debugName << std::endl;
        }
      }

#endif
    }


    renderObjects_.push_back(*_renderObject);


    ACG::RenderObject* p = &renderObjects_.back();

    // apply modifiers
    size_t numMods = renderObjectModifiers_.size();
    for (size_t i = 0; i < numMods; ++i)
    {
      if (renderObjectModifiers_[i])
        renderObjectModifiers_[i]->apply(p);
    }

    if (!p->shaderDesc.numLights)
      p->shaderDesc.numLights = numLights_;

    else if (p->shaderDesc.numLights < 0 || p->shaderDesc.numLights >= SG_MAX_SHADER_LIGHTS)
      p->shaderDesc.numLights = 0;

    p->internalFlags_ = 0;

    // precompile shader
#ifdef GL_VERSION_3_2
    GLSL::Program* shaderProg = ACG::ShaderCache::getInstance()->getProgram(&p->shaderDesc);
#endif


    // check primitive type and geometry shader
    if (errorDetectionLevel_ > 1 && p->shaderDesc.geometryTemplateFile.length())
    {
#ifdef GL_VERSION_3_2
      GLint geomInputType = 0;
      glGetProgramiv(shaderProg->getProgramId(), GL_GEOMETRY_INPUT_TYPE, &geomInputType);


      if (geomInputType != GLint(p->primitiveMode))
      {

        switch (geomInputType)
        {
        case GL_POINTS: std::cout << "warning: primitive mode is incompatible with points-geometryshader in renderobject: " << _renderObject->debugName << std::endl; break;
        
        case GL_LINES: 
          {
            if (p->primitiveMode != GL_LINE_STRIP && p->primitiveMode != GL_LINE_LOOP)
              std::cout << "warning: primitive mode is incompatible with lines-geometryshader in renderobject: " << _renderObject->debugName << std::endl;
          } break;

        case GL_LINES_ADJACENCY:
          {
            if (p->primitiveMode != GL_LINE_STRIP_ADJACENCY)
              std::cout << "warning: primitive mode is incompatible with lines_adjacency-geometryshader in renderobject: " << _renderObject->debugName << std::endl;
          } break;

        case GL_TRIANGLES:
          {
            if (p->primitiveMode != GL_TRIANGLE_STRIP && p->primitiveMode != GL_TRIANGLE_FAN)
              std::cout << "warning: primitive mode is incompatible with triangles-geometryshader in renderobject: " << _renderObject->debugName << std::endl;
          } break;
          
        case GL_TRIANGLES_ADJACENCY:
          {
            if (p->primitiveMode != GL_TRIANGLE_STRIP_ADJACENCY)
              std::cout << "warning: primitive mode is incompatible with triangles_adjacency-geometryshader in renderobject: " << _renderObject->debugName << std::endl;
          } break;

        default: std::cout << "warning: unknown input_type for geometryshader in renderobject: " << _renderObject->debugName << std::endl;
        }
        
        

      }


#else
      if (_renderObject->isDefaultLineObject())
      {
        if (_renderObject->primitiveMode != GL_LINES && _renderObject->primitiveMode != GL_LINE_STRIP && _renderObject->primitiveMode != GL_LINE_LOOP)
          std::cout << "warning: primitive mode is incompatible with lines-geometryshader in renderobject: " << _renderObject->debugName << std::endl;
      }
      else if (_renderObject->isDefaultPointObject())
      {
        if (_renderObject->primitiveMode != GL_POINTS)
          std::cout << "warning: primitive mode is incompatible with points-geometryshader in renderobject: " << _renderObject->debugName << std::endl;
      }
#endif
    }

  }
}




void IRenderer::collectRenderObjects( ACG::GLState* _glState, ACG::SceneGraph::DrawModes::DrawMode _drawMode, ACG::SceneGraph::BaseNode* _sceneGraphRoot )
{
  // collect light sources
//  collectLightNodes(_sceneGraphRoot);
  numLights_ = 0; // reset light counter

//  // flush render objects
//  for (size_t i = 0; i < renderObjects_.size(); ++i)
//  {
//    renderObjects_[i].uniformPool_.clear();
//  }
  renderObjects_.clear();

  if (!_sceneGraphRoot) return;

  // default material needed
  ACG::SceneGraph::Material defMat;
  defMat.baseColor(ACG::Vec4f(0.0f, 0.0f, 0.0f, 1.0f));
  defMat.ambientColor(ACG::Vec4f(0.2f, 0.2f, 0.2f, 1.0f));
  defMat.diffuseColor(ACG::Vec4f(0.6f, 0.6f, 0.6f, 1.0f));
  defMat.specularColor(ACG::Vec4f(0.0f, 0.0f, 0.0f, 1.0f));
  defMat.shininess(1.0f);
  //  defMat.alphaValue(1.0f);

  // collect renderables
  traverseRenderableNodes(_glState, _drawMode, *_sceneGraphRoot, defMat);
}


/// Stack element used in IRenderer::traverseRenderableNodes
namespace {
class ScenegraphTraversalStackEl {
    public:
        ScenegraphTraversalStackEl(ACG::SceneGraph::BaseNode *_node,
                const ACG::SceneGraph::Material *_material) :
            node(_node), material(_material),
            subtree_index_start(0), leave(false) {}

        ACG::SceneGraph::BaseNode *node;
        const ACG::SceneGraph::Material* material;
        size_t subtree_index_start;
        bool leave;
};
}

void IRenderer::traverseRenderableNodes( ACG::GLState* _glState, ACG::SceneGraph::DrawModes::DrawMode _drawMode, ACG::SceneGraph::BaseNode &_node, const ACG::SceneGraph::Material &_mat )
{
    renderObjectSource_.clear();
    overlayObjectSource_.clear();

    if (_node.status() == ACG::SceneGraph::BaseNode::HideSubtree)
        return;

    std::vector<ScenegraphTraversalStackEl> stack;
    // That's roughly the minimum size every scenegraph requries.
    stack.reserve(32);
    stack.push_back(ScenegraphTraversalStackEl(&_node, &_mat));
    while (!stack.empty()) {
        ScenegraphTraversalStackEl &cur = stack.back();
467
        auto cur_idx = stack.size() - 1;
Jan Möbius's avatar
Jan Möbius committed
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
        ACG::SceneGraph::DrawModes::DrawMode nodeDM = cur.node->drawMode();
        if (nodeDM == ACG::SceneGraph::DrawModes::DEFAULT)
          nodeDM = _drawMode;

        if (!cur.leave) {
            /*
             * Stuff that happens before processing cur.node's children.
             */
            if ( cur.node->status() != ACG::SceneGraph::BaseNode::HideNode )
                cur.node->enter(this, *_glState, nodeDM);

            cur.subtree_index_start = renderObjects_.size();

            // fetch material (Node itself can be a material node, so we have to
            // set that in front of the nodes own rendering
            ACG::SceneGraph::MaterialNode* matNode =
                    dynamic_cast<ACG::SceneGraph::MaterialNode*>(cur.node);
            if (matNode)
              cur.material = &matNode->material();

            if (cur.node->status() != ACG::SceneGraph::BaseNode::HideNode)
                cur.node->getRenderObjects(this, *_glState, nodeDM, cur.material);

            // keep track of which node added objects
            size_t numAddedObjects = renderObjects_.size() - renderObjectSource_.size();
            renderObjectSource_.insert(renderObjectSource_.end(), numAddedObjects, cur.node);

495
            auto cur_mat = cur.material; // make a copy so we can avoid use-after-free on stack.push_back
Jan Möbius's avatar
Jan Möbius committed
496
497
498
499
500
501
502
503
504
            // Process children?
            if (cur.node->status() != ACG::SceneGraph::BaseNode::HideChildren) {
                // Process all children which are second pass
                for (ACG::SceneGraph::BaseNode::ChildIter
                        cIt = cur.node->childrenBegin(),
                        cEnd = cur.node->childrenEnd(); cIt != cEnd; ++cIt) {
                  if (((*cIt)->traverseMode() &
                          ACG::SceneGraph::BaseNode::SecondPass) &&
                          (*cIt)->status() != ACG::SceneGraph::BaseNode::HideSubtree)
505
                      stack.emplace_back(*cIt, cur_mat);
Jan Möbius's avatar
Jan Möbius committed
506
507
508
509
510
511
512
513
514
                }

                // Process all children which are not second pass
                for (ACG::SceneGraph::BaseNode::ChildIter
                        cIt = cur.node->childrenBegin(),
                        cEnd = cur.node->childrenEnd(); cIt != cEnd; ++cIt) {
                  if ((~(*cIt)->traverseMode() &
                          ACG::SceneGraph::BaseNode::SecondPass) &&
                          (*cIt)->status() != ACG::SceneGraph::BaseNode::HideSubtree)
515
                      stack.emplace_back(*cIt, cur_mat);
Jan Möbius's avatar
Jan Möbius committed
516
517
518
519
                }
            }

            // Next time process the other branch of this if statement.
520
521
            // 'cur' is now invalidated due to push_back, access via stack
            stack[cur_idx].leave = true;
Jan Möbius's avatar
Jan Möbius committed
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

        } else {
            /*
             * Stuff that happens after processing cur.node's children.
             */
            current_subtree_objects_ = RenderObjectRange(
                    renderObjects_.begin() + cur.subtree_index_start,
                    renderObjects_.end());

            if (cur.node->status() != ACG::SceneGraph::BaseNode::HideNode )
                cur.node->leave(this, *_glState, nodeDM);
            stack.pop_back();
        }
    }
}

void IRenderer::prepareRenderingPipeline(ACG::GLState* _glState, ACG::SceneGraph::DrawModes::DrawMode _drawMode, ACG::SceneGraph::BaseNode* _scenegraphRoot)
{
540
541
542
543
544
545
546
  // save default VAO
#ifdef GL_ARB_vertex_array_object
  glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &prevVAO_);
#endif

  coreProfile_ = !_glState->compatibilityProfile();

Jan Möbius's avatar
Jan Möbius committed
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
  // grab view transform from glstate
  viewMatrix_ = _glState->modelview();
  camPosWS_ = Vec3f( viewMatrix_(0,3), viewMatrix_(1,3), viewMatrix_(2,3) );
  camDirWS_ = Vec3f( viewMatrix_(0,2), viewMatrix_(1,2), -viewMatrix_(2,2) ); // mind the z flip

//   printf("pos: %f %f %f\ndir: %f %f %f\n", camPosWS_[0], camPosWS_[1], camPosWS_[2],
//     camDirWS_[0], camDirWS_[1], camDirWS_[2]);

  // First, all render objects get collected.
  collectRenderObjects(_glState, _drawMode, _scenegraphRoot);

  // ==========================================================
  // Sort renderable objects based on their priority
  // Filter for overlay, lines etc.
  // ==========================================================

  size_t numRenderObjects = 0,
    numOverlayObjects = 0,
    numLineObjects = 0;

  for (std::vector<ACG::RenderObject>::const_iterator it = renderObjects_.begin();
          it != renderObjects_.end(); ++it) {
      if (!it->overlay && !(it->isDefaultLineObject() && enableLineThicknessGL42_))
          numRenderObjects++;
      if (it->overlay)
          numOverlayObjects++;
      if (enableLineThicknessGL42_ && it->isDefaultLineObject())
          numLineObjects++;
  }

  /*
   * Neither clear() nor resize() ever decreases the capacity of
   * a vector. So it has no adverse impact on performance to clear
   * the vectors here.
   */
  sortedObjects_.clear();
  sortedObjects_.reserve(numRenderObjects);

  overlayObjects_.clear();
  overlayObjects_.reserve(numOverlayObjects);

  lineGL42Objects_.clear();
  lineGL42Objects_.reserve(numLineObjects);


  sortListObjects_.clear();
  sortListObjects_.reserve(numRenderObjects);

  sortListOverlays_.clear();
  sortListOverlays_.reserve(numOverlayObjects);

  // init sorted objects array
  for (size_t i = 0; i < renderObjects_.size(); ++i)
  {
    if (renderObjects_[i].overlay)
    {
      overlayObjects_.push_back(&renderObjects_[i]);
      sortListOverlays_.push_back(i);
    }
    else if (enableLineThicknessGL42_ && numLineObjects && renderObjects_[i].isDefaultLineObject())
    {
      renderObjects_[i].shaderDesc.geometryTemplateFile = "Wireframe/gl42/geometry.tpl";
      renderObjects_[i].shaderDesc.fragmentTemplateFile = "Wireframe/gl42/fragment.tpl";

      // disable color write to fbo, but allow RenderObject to control depth write
      renderObjects_[i].glColorMask(0,0,0,0);

//      sortedObjects_[sceneObjectOffset++] = &renderObjects_[i];
      lineGL42Objects_.push_back(&renderObjects_[i]);
    }
    else
    {
      sortedObjects_.push_back(&renderObjects_[i]);
      sortListObjects_.push_back(i);
    }
  }

  sortRenderObjects();


  // ---------------------------
  // Initialize the render state
  // ---------------------------
  // gl cleanup

632
633
634
635
636
637
638
639
  if (_glState->compatibilityProfile())
  {
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_INDEX_ARRAY);
  }
Jan Möbius's avatar
Jan Möbius committed
640
641
642
643
644
645
646
647
648

  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LESS);
  glDepthMask(GL_TRUE);

  // save active fbo and viewport
  saveInputFbo();

649
650
if(_glState->compatibilityProfile())
{
Jan Möbius's avatar
Jan Möbius committed
651
652
653
654
  // get global ambient factor
  GLfloat lightModelAmbient[4];
  glGetFloatv(GL_LIGHT_MODEL_AMBIENT, lightModelAmbient);
  globalLightModelAmbient_ = ACG::Vec3f(lightModelAmbient[0], lightModelAmbient[1], lightModelAmbient[2]);
655
}
Jan Möbius's avatar
Jan Möbius committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675

  // search list of render object for objects requiring the scene depth map
  bool requiresSceneDepths = false;

  for (size_t i = 0; i < renderObjects_.size(); ++i)
  {
    if (renderObjects_[i].depthMapUniformName)
      requiresSceneDepths = true;
  }

  // render scene depth map
  if (requiresSceneDepths)
    renderDepthMap(curViewerID_, _glState->viewport_width(), _glState->viewport_height());
}



void IRenderer::finishRenderingPipeline(bool _drawOverlay)
{
#ifdef GL_ARB_vertex_array_object
676
  glBindVertexArray(prevVAO_);
Jan Möbius's avatar
Jan Möbius committed
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
#endif

  // draw thick lines
  if (enableLineThicknessGL42_)
    renderLineThicknessGL42();

  if (_drawOverlay)
  {
    const int numOverlayObj = overlayObjects_.size();
    // two-pass overlay rendering:
    // 1. clear depth buffer at pixels of overlay objects
    // 2. render overlay with correct depth-testing

    // 1. pass: clear depth to max value at overlay footprint
    for (int i = 0; i < numOverlayObj; ++i)
    {
      RenderObject* obj = getOverlayRenderObject(i);

      if (obj->depthTest && obj->depthFunc != GL_ALWAYS)
      {
        float depthMax = 1.0f;

        if (obj->depthFunc == GL_GREATER || obj->depthFunc == GL_GEQUAL)
          depthMax = 0.0f;

        // save depth setting of renderobject
        Vec2f depthRange = obj->depthRange;
        bool depthWrite = obj->depthWrite;
        GLenum depthFunc = obj->depthFunc;

        // reset depth to maximal distance by using depth range
        obj->depthRange = Vec2f(depthMax, depthMax);
        obj->depthWrite = true;
        obj->depthFunc = GL_ALWAYS;

        renderObject(obj);

        // restore depth setting
        obj->depthRange = depthRange;
        obj->depthWrite = depthWrite;
        obj->depthFunc = depthFunc;
      }

    }

    // 2. render overlay with correct depth-testing
    for (int i = 0; i < numOverlayObj; ++i)
    {
      RenderObject* obj = getOverlayRenderObject(i);
      renderObject(obj);
    }

  }

#ifdef GL_ARB_vertex_array_object
732
  glBindVertexArray(prevVAO_);
Jan Möbius's avatar
Jan Möbius committed
733
734
735
736
737
#endif

  for (int i = 0; i < maxClipDistances_; ++i)
    glDisable(GL_CLIP_DISTANCE0 + i);

738
739
  glDisable(GL_PROGRAM_POINT_SIZE);

Jan Möbius's avatar
Jan Möbius committed
740
741
742
743
744
  glDepthMask(1);
  glColorMask(1,1,1,1);

  glUseProgram(0);

745
746
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
Jan Möbius's avatar
Jan Möbius committed
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

  // Renderer check:
  // Print a warning if the currently active fbo / viewport is not the same as the saved fbo.
  // Restore to previous fbo and viewport if not done already.

  GLint curFbo;
  GLint curViewport[4];
  GLint curDrawBuf;
  glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &curFbo);
  glGetIntegerv(GL_VIEWPORT, curViewport);
  glGetIntegerv(GL_DRAW_BUFFER, &curDrawBuf);
  
  if (curFbo != prevFbo_)
  {
    std::cout << "warning: input and output fbo are not the same in renderer implementation" << std::endl;
    restoreInputFbo();
  }

  if (curDrawBuf != prevDrawBuffer_)
  {
    std::cout << "warning: input and output draw-buffer are not the same in renderer implementation" << std::endl;
    restoreInputFbo();
  }

  if (curViewport[0] != prevViewport_[0] ||
    curViewport[1] != prevViewport_[1] ||
    curViewport[2] != prevViewport_[2] ||
    curViewport[3] != prevViewport_[3])
  {
    std::cout << "warning: input and output viewport are not the same in renderer implementation" << std::endl;
    restoreInputFbo();
  }
}


void IRenderer::saveInputFbo()
{
  // save active fbo
  saveActiveFbo(&prevFbo_, prevViewport_, &prevDrawBuffer_);
  prevFboSaved_ = true;
}

void IRenderer::restoreInputFbo()
{
  if (prevFboSaved_)
    restoreFbo(prevFbo_, prevViewport_, prevDrawBuffer_);
}

void IRenderer::saveActiveFbo( GLint* _outFboId, GLint* _outViewport, GLint* _outDrawBuffer ) const
{
  // save active fbo
  glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, _outFboId);
  glGetIntegerv(GL_VIEWPORT, _outViewport);
  glGetIntegerv(GL_DRAW_BUFFER, _outDrawBuffer);
}

void IRenderer::restoreFbo( GLint _fboId, const GLint* _outViewport, GLint _drawBuffer ) const
{
  glBindFramebuffer(GL_FRAMEBUFFER, _fboId);
  glDrawBuffer(_drawBuffer);
  glViewport(_outViewport[0], _outViewport[1], _outViewport[2], _outViewport[3]);
}

void IRenderer::clearInputFbo( const ACG::Vec4f& clearColor )
{
  glClearColor(clearColor[0], clearColor[1], clearColor[2], 1.0f);

  // glClear will affect the whole back buffer, not only the area in viewport.
  // Temporarily use glScissor to only clear the viewport area in the back buffer.
  if (!prevFboSaved_)
  {
    GLint oldViewport[4];
    glGetIntegerv(GL_VIEWPORT, oldViewport);
    glScissor(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]);
  }
  else
    glScissor(prevViewport_[0], prevViewport_[1], prevViewport_[2], prevViewport_[3]);

  glEnable(GL_SCISSOR_TEST);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  // disable scissors again, draw calls only affect the area in glViewport anyway
  glDisable(GL_SCISSOR_TEST);
}

namespace {
struct RenderObjectComparator {
Jan Möbius's avatar
Jan Möbius committed
834
    explicit RenderObjectComparator(const std::vector<ACG::RenderObject>& _vec) : vec_(_vec) {
Jan Möbius's avatar
Jan Möbius committed
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
    }

    bool operator() (int a, int b) {
        return (vec_[a].priority < vec_[b].priority);
    }

    const std::vector<ACG::RenderObject>& vec_;
};
}

void IRenderer::sortRenderObjects()
{
  size_t numObjs = sortListObjects_.size();
  size_t numOverlays = sortListOverlays_.size();

  RenderObjectComparator cmpOp(renderObjects_);

  std::sort(sortListObjects_.begin(), sortListObjects_.end(), cmpOp);
  std::sort(sortListOverlays_.begin(), sortListOverlays_.end(), cmpOp);

  // apply sorting list
  std::vector<ACG::SceneGraph::BaseNode*> temp;
  renderObjectSource_.swap(temp);


  renderObjectSource_.resize(numObjs, 0);
  overlayObjectSource_.resize(numOverlays, 0);

  for (size_t i = 0; i < numObjs; ++i)
  {
    int objID = sortListObjects_[i];
    sortedObjects_[i] = &renderObjects_[objID];

    renderObjectSource_[i] = temp[objID];
  }

  for (size_t i = 0; i < numOverlays; ++i)
  {
    int objID = sortListOverlays_[i];
    overlayObjects_[i] = &renderObjects_[objID];

    overlayObjectSource_[i] = temp[objID];
  }
}



void IRenderer::bindObjectVBO(ACG::RenderObject* _obj,
                                       GLSL::Program*     _prog)
{
  _prog->use();


#ifdef GL_ARB_vertex_array_object
889
890
  if (_obj->vertexArrayObject)
    glBindVertexArray(_obj->vertexArrayObject);
Jan Möbius's avatar
Jan Möbius committed
891
892
893
894
895
896
897
898
#endif

  if (!_obj->vertexArrayObject)
  {
    //////////////////////////////////////////////////////////////////////////
    // NOTE:
    //  always bind buffers before glVertexAttribPointer calls!!
    //  freeze in glDrawElements guaranteed (with no error message whatsoever)
899
900
    glBindBuffer(GL_ARRAY_BUFFER, _obj->vertexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _obj->indexBuffer);
Jan Möbius's avatar
Jan Möbius committed
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


    // activate vertex declaration
    _obj->vertexDecl->activateShaderPipeline(_prog);

  }
}


void IRenderer::bindObjectUniforms( ACG::RenderObject* _obj, GLSL::Program* _prog )
{
  // transforms
  ACG::GLMatrixf mvp = _obj->proj * _obj->modelview;
  ACG::GLMatrixf mvIT = _obj->modelview;
  mvIT.invert();
  mvIT.transpose();

  _prog->setUniform("g_mWVP", mvp);
  _prog->setUniform("g_mWV", _obj->modelview);
  _prog->setUniformMat3("g_mWVIT", mvIT);
  _prog->setUniform("g_mP", _obj->proj);

  _prog->setUniform("g_vCamPos", camPosWS_);
  _prog->setUniform("g_vCamDir", camDirWS_);

  // material
  
  _prog->setUniform("g_cEmissive", _obj->emissive);

  _prog->setUniform("g_cDiffuse", _obj->diffuse);
  _prog->setUniform("g_cAmbient", _obj->ambient);
  _prog->setUniform("g_cSpecular", _obj->specular);

  ACG::Vec4f materialParams(_obj->shininess, _obj->alpha, 0.0f, 0.0f);
  _prog->setUniform("g_vMaterial", materialParams);

  _prog->setUniform("g_cLightModelAmbient", globalLightModelAmbient_);

  // Additional Uniforms defined in the render Object
  if ( !_obj->uniformPool_.empty() )
    _obj->uniformPool_.bind(_prog);

  // textures:

  // maybe consider using bindless textures some time in the future
  // to get rid of the old and problematic glActiveTexture(), glBindTexture() state machine usage:
  // https://www.opengl.org/registry/specs/ARB/bindless_texture.txt

  int maxTextureStage = 0;
  for (std::map<size_t,RenderObject::Texture>::const_iterator iter = _obj->textures().begin();
      iter != _obj->textures().end();++iter)
  {
    //check for valid texture id
    const size_t texture_stage = iter->first;
    const RenderObject::Texture tex = iter->second;
    if (!tex.id)
      continue;

    glActiveTexture(GL_TEXTURE0 + (GLenum)texture_stage);
    glBindTexture(iter->second.type, tex.id);
    _prog->setUniform(QString("g_Texture%1").arg(texture_stage).toStdString().c_str(), (int)texture_stage);

    maxTextureStage = std::max(maxTextureStage, (int)texture_stage);
  }


  // scene depth texture
  if (_obj->depthMapUniformName)
  {
    // bind to (hopefully) unused texture stage
    int depthMapSlot = maxTextureStage + 1;

    _prog->setUniform(_obj->depthMapUniformName, depthMapSlot);
    glActiveTexture(GL_TEXTURE0 + depthMapSlot);
    glBindTexture(GL_TEXTURE_2D, depthMaps_[curViewerID_]->getAttachment(GL_COLOR_ATTACHMENT0));
  }


  // lights
  for (int i = 0; i < numLights_; ++i)
  {
    LightData* lgt = lights_ + i;

    char szUniformName[256];

    sprintf(szUniformName, "g_cLightDiffuse_%d", i);
    _prog->setUniform(szUniformName, lgt->diffuse);

    sprintf(szUniformName, "g_cLightAmbient_%d", i);
    _prog->setUniform(szUniformName, lgt->ambient);

    sprintf(szUniformName, "g_cLightSpecular_%d", i);
    _prog->setUniform(szUniformName, lgt->specular);


    if (lgt->ltype == ACG::SG_LIGHT_POINT || lgt->ltype == ACG::SG_LIGHT_SPOT)
    {
      sprintf(szUniformName, "g_vLightPos_%d", i);
      _prog->setUniform(szUniformName, lgt->pos);