IRenderer.cc 52.3 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1
2
3
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
Jan Möbius's avatar
Jan Möbius committed
4
5
6
7
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
Jan Möbius's avatar
Jan Möbius committed
8
9
 *                                                                           *
 *---------------------------------------------------------------------------*
Jan Möbius's avatar
Jan Möbius committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
Jan Möbius's avatar
Jan Möbius committed
39
40
41
42
43
44
45
46
47
48
49
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                       *
 *   $Author$                                                      *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

50
#include <ACG/GL/acg_glew.hh>
51
52
#include <cstdio>
#include <cstring>
Jan Möbius's avatar
Jan Möbius committed
53
#include <iostream>
54
#include <algorithm>
Jan Möbius's avatar
Jan Möbius committed
55
#include <QFile>
56
#include <QTextStream>
Jan Möbius's avatar
Jan Möbius committed
57
58
59
60
61
62

#include <ACG/GL/gl.hh>

#include <ACG/GL/IRenderer.hh>

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

Jan Möbius's avatar
Jan Möbius committed
65
#include <ACG/GL/ShaderCache.hh>
66
#include <ACG/GL/ScreenQuad.hh>
67
#include <ACG/GL/FBO.hh>
68
69
#include <ACG/GL/globjects.hh>

Jan Möbius's avatar
Jan Möbius committed
70
71


72
73
74
namespace ACG
{

75
76
int IRenderer::maxClipDistances_ = -1;

Jan Möbius's avatar
Jan Möbius committed
77
IRenderer::IRenderer()
78
79
80
81
: numLights_(0), 
renderObjects_(0), 
depthMapUsed_(false), 
curViewerID_(0),
Christopher Tenter's avatar
Christopher Tenter committed
82
83
prevFbo_(0),
prevDrawBuffer_(GL_BACK),
84
85
86
87
prevFboSaved_(false),
depthCopyShader_(0),
errorDetectionLevel_(1),
enableLineThicknessGL42_(false)
Jan Möbius's avatar
Jan Möbius committed
88
{
89
90
91
92
  prevViewport_[0] = 0;
  prevViewport_[1] = 0;
  prevViewport_[2] = 0;
  prevViewport_[3] = 0;
93
94
95

  // set global ambient scale to default OpenGL value
  globalLightModelAmbient_ = ACG::Vec3f(0.2f, 0.2f, 0.2f);
Jan Möbius's avatar
Jan Möbius committed
96
}
Jan Möbius's avatar
Jan Möbius committed
97

98

Jan Möbius's avatar
Jan Möbius committed
99
100
IRenderer::~IRenderer()
{
101
  delete depthCopyShader_;
102
103
104
105

  // free depth map fbos
  for (std::map<int, ACG::FBO*>::iterator it = depthMaps_.begin(); it != depthMaps_.end(); ++it)
    delete it->second;
Jan Möbius's avatar
Jan Möbius committed
106
}
107

Jan Möbius's avatar
Jan Möbius committed
108
109
void IRenderer::addRenderObject(ACG::RenderObject* _renderObject)
{
Christopher Tenter's avatar
Christopher Tenter committed
110
111
112
113
114
115
116
  // avoid null-ptr access
  if (!_renderObject->debugName)
    _renderObject->debugName = "<unnamed>";

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

Jan Möbius's avatar
Jan Möbius committed
117
  // do some more checks for error detection
118
  if (!_renderObject->vertexDecl && !_renderObject->vertexArrayObject)
119
    std::cout << "error: missing vertex declaration in renderobject: " << _renderObject->debugName << std::endl;
Jan Möbius's avatar
Jan Möbius committed
120
121
  else
  {
122
123
124
125
    if (errorDetectionLevel_ > 0)
    {
      // commonly encountered rendering errors

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

129
130
      //  Why is my object invisible/black?
      if (!_renderObject->depthWrite && 
131
132
        !_renderObject->colorWriteMask[0] && !_renderObject->colorWriteMask[1] &&
        !_renderObject->colorWriteMask[2] && !_renderObject->colorWriteMask[3])
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        std::cout << "warning: depth write and color write disabled in renderobject: " << _renderObject->debugName << std::endl;

      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;
          }
        }
      }

156
157
158
159
160
161
162
163
164
      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)
        {
Christopher Tenter's avatar
Christopher Tenter committed
165
166
167
168
169
#ifdef GL_ARB_texture_buffer_object
          if (it->second.type == GL_TEXTURE_BUFFER)
            continue; // skip texture buffers, for which testing for mipmaps would generate an error
#endif

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
          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);
            }
          }
        }

      }
215
216
217
218
219
220
221
222
223
224
225
226
227

      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;
        }
      }

228
      if (!_renderObject->vertexArrayObject)
229
      {
230
231
232
233
234
        // 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))
Christopher Tenter's avatar
Christopher Tenter committed
235
236
            std::cout << "warning: missing normals for lighting in renderobject: " << _renderObject->debugName << std::endl
                      << "         Set shadeMode to SG_SHADE_UNLIT or provide normals!" << std::endl;
237
        }
238

239
240
241
242
243
244
        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;
        }
245

246
247
248
249
250
251
        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;
        }
252
253
254
255
256
257
      }


      // 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;
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


#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
305
    }
306
307


Jan Möbius's avatar
Jan Möbius committed
308
    renderObjects_.push_back(*_renderObject);
Jan Möbius's avatar
Jan Möbius committed
309
310


Jan Möbius's avatar
Jan Möbius committed
311
    ACG::RenderObject* p = &renderObjects_.back();
312

313
314
315
316
317
318
319
320
    // apply modifiers
    size_t numMods = renderObjectModifiers_.size();
    for (size_t i = 0; i < numMods; ++i)
    {
      if (renderObjectModifiers_[i])
        renderObjectModifiers_[i]->apply(p);
    }

Jan Möbius's avatar
Jan Möbius committed
321
322
    if (!p->shaderDesc.numLights)
      p->shaderDesc.numLights = numLights_;
Jan Möbius's avatar
Jan Möbius committed
323

Jan Möbius's avatar
Jan Möbius committed
324
325
    else if (p->shaderDesc.numLights < 0 || p->shaderDesc.numLights >= SG_MAX_SHADER_LIGHTS)
      p->shaderDesc.numLights = 0;
Jan Möbius's avatar
Jan Möbius committed
326

Jan Möbius's avatar
Jan Möbius committed
327
    p->internalFlags_ = 0;
Jan Möbius's avatar
Jan Möbius committed
328

Jan Möbius's avatar
Jan Möbius committed
329
    // precompile shader
Jan's avatar
Jan committed
330
#ifdef GL_VERSION_3_2
331
    GLSL::Program* shaderProg = ACG::ShaderCache::getInstance()->getProgram(&p->shaderDesc);
Jan Möbius's avatar
Jan Möbius committed
332
#endif
333
334
335
336
337


    // check primitive type and geometry shader
    if (errorDetectionLevel_ > 1 && p->shaderDesc.geometryTemplateFile.length())
    {
Jan's avatar
Jan committed
338
#ifdef GL_VERSION_3_2
339
340
341
342
      GLint geomInputType = 0;
      glGetProgramiv(shaderProg->getProgramId(), GL_GEOMETRY_INPUT_TYPE, &geomInputType);


Christopher Tenter's avatar
Christopher Tenter committed
343
      if (geomInputType != GLint(p->primitiveMode))
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
      {

        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
    }
Jan Möbius's avatar
Jan Möbius committed
395

Jan Möbius's avatar
Jan Möbius committed
396
397
  }
}
Jan Möbius's avatar
Jan Möbius committed
398
399
400



Jan Möbius's avatar
Jan Möbius committed
401
402
403
404
405
406
407

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

408
409
410
411
412
//  // flush render objects
//  for (size_t i = 0; i < renderObjects_.size(); ++i)
//  {
//    renderObjects_[i].uniformPool_.clear();
//  }
413
  renderObjects_.clear();
Jan Möbius's avatar
Jan Möbius committed
414

415
  if (!_sceneGraphRoot) return;
Jan Möbius's avatar
Jan Möbius committed
416
417
418
419
420
421
422
423
424
425
426

  // 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
427
  traverseRenderableNodes(_glState, _drawMode, *_sceneGraphRoot, defMat);
Jan Möbius's avatar
Jan Möbius committed
428
}
Jan Möbius's avatar
Jan Möbius committed
429

Jan Möbius's avatar
Jan Möbius committed
430

431
432
433
434
/// Stack element used in IRenderer::traverseRenderableNodes
namespace {
class ScenegraphTraversalStackEl {
    public:
435
        ScenegraphTraversalStackEl(ACG::SceneGraph::BaseNode *_node,
436
437
438
439
                const ACG::SceneGraph::Material *_material) :
            node(_node), material(_material),
            subtree_index_start(0), leave(false) {}

440
        ACG::SceneGraph::BaseNode *node;
441
442
443
444
445
        const ACG::SceneGraph::Material* material;
        size_t subtree_index_start;
        bool leave;
};
}
Jan Möbius's avatar
Jan Möbius committed
446

447
void IRenderer::traverseRenderableNodes( ACG::GLState* _glState, ACG::SceneGraph::DrawModes::DrawMode _drawMode, ACG::SceneGraph::BaseNode &_node, const ACG::SceneGraph::Material &_mat )
448
{
449
450
451
452
453
454
    if (_node.status() == ACG::SceneGraph::BaseNode::HideSubtree)
        return;

    std::vector<ScenegraphTraversalStackEl> stack;
    // That's roughly the minimum size every scenegraph requries.
    stack.reserve(32);
455
    stack.push_back(ScenegraphTraversalStackEl(&_node, &_mat));
456
457
    while (!stack.empty()) {
        ScenegraphTraversalStackEl &cur = stack.back();
458
        ACG::SceneGraph::DrawModes::DrawMode nodeDM = cur.node->drawMode();
459
460
461
462
463
464
465
        if (nodeDM == ACG::SceneGraph::DrawModes::DEFAULT)
          nodeDM = _drawMode;

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

            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 =
474
                    dynamic_cast<ACG::SceneGraph::MaterialNode*>(cur.node);
475
476
477
            if (matNode)
              cur.material = &matNode->material();

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

            // Process children?
482
            if (cur.node->status() != ACG::SceneGraph::BaseNode::HideChildren) {
483
484
                // Process all children which are second pass
                for (ACG::SceneGraph::BaseNode::ChildIter
485
486
                        cIt = cur.node->childrenBegin(),
                        cEnd = cur.node->childrenEnd(); cIt != cEnd; ++cIt) {
487
488
489
                  if (((*cIt)->traverseMode() &
                          ACG::SceneGraph::BaseNode::SecondPass) &&
                          (*cIt)->status() != ACG::SceneGraph::BaseNode::HideSubtree)
490
                      stack.push_back(ScenegraphTraversalStackEl(*cIt, cur.material));
491
492
493
494
                }

                // Process all children which are not second pass
                for (ACG::SceneGraph::BaseNode::ChildIter
495
496
                        cIt = cur.node->childrenBegin(),
                        cEnd = cur.node->childrenEnd(); cIt != cEnd; ++cIt) {
497
498
499
                  if ((~(*cIt)->traverseMode() &
                          ACG::SceneGraph::BaseNode::SecondPass) &&
                          (*cIt)->status() != ACG::SceneGraph::BaseNode::HideSubtree)
500
                      stack.push_back(ScenegraphTraversalStackEl(*cIt, cur.material));
501
502
                }
            }
503

504
505
            // Next time process the other branch of this if statement.
            cur.leave = true;
506

507
508
509
510
511
512
513
        } else {
            /*
             * Stuff that happens after processing cur.node's children.
             */
            current_subtree_objects_ = RenderObjectRange(
                    renderObjects_.begin() + cur.subtree_index_start,
                    renderObjects_.end());
Jan Möbius's avatar
Jan Möbius committed
514

515
516
            if (cur.node->status() != ACG::SceneGraph::BaseNode::HideNode )
                cur.node->leave(this, *_glState, nodeDM);
517
518
            stack.pop_back();
        }
Jan Möbius's avatar
Jan Möbius committed
519
    }
520
521
}

Jan Möbius's avatar
Jan Möbius committed
522
523
void IRenderer::prepareRenderingPipeline(ACG::GLState* _glState, ACG::SceneGraph::DrawModes::DrawMode _drawMode, ACG::SceneGraph::BaseNode* _scenegraphRoot)
{
524
525
526
527
528
529
530
531
  // 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]);

Jan Möbius's avatar
Jan Möbius committed
532
533
534
535
536
  // First, all render objects get collected.
  collectRenderObjects(_glState, _drawMode, _scenegraphRoot);

  // ==========================================================
  // Sort renderable objects based on their priority
537
  // Filter for overlay, lines etc.
Jan Möbius's avatar
Jan Möbius committed
538
539
  // ==========================================================

540
541
542
543
544
545
546
547
548
549
550
551
552
  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++;
  }
Jan Möbius's avatar
Jan Möbius committed
553

554
555
556
557
558
559
560
  /*
   * 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);
Jan Möbius's avatar
Jan Möbius committed
561

562
563
  overlayObjects_.clear();
  overlayObjects_.reserve(numOverlayObjects);
564

565
566
  lineGL42Objects_.clear();
  lineGL42Objects_.reserve(numLineObjects);
567

Jan Möbius's avatar
Jan Möbius committed
568
  // init sorted objects array
569
570
571
  for (size_t i = 0; i < renderObjects_.size(); ++i)
  {
    if (renderObjects_[i].overlay)
572
      overlayObjects_.push_back(&renderObjects_[i]);
573
574
575
576
577
578
579
580
581
    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];
582
      lineGL42Objects_.push_back(&renderObjects_[i]);
583
    }
584
    else
585
      sortedObjects_.push_back(&renderObjects_[i]);
586
  }
Jan Möbius's avatar
Jan Möbius committed
587
588
589

  sortRenderObjects();

590

Jan Möbius's avatar
Jan Möbius committed
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
  // ---------------------------
  // Initialize the render state
  // ---------------------------
  // gl cleanup

  glDisableClientState(GL_VERTEX_ARRAY);
  glDisableClientState(GL_COLOR_ARRAY);
  glDisableClientState(GL_NORMAL_ARRAY);
  glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  glDisableClientState(GL_INDEX_ARRAY);


  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LESS);
  glDepthMask(GL_TRUE);
607
608
609

  // save active fbo and viewport
  saveInputFbo();
610
611
612
613
614
615


  // get global ambient factor
  GLfloat lightModelAmbient[4];
  glGetFloatv(GL_LIGHT_MODEL_AMBIENT, lightModelAmbient);
  globalLightModelAmbient_ = ACG::Vec3f(lightModelAmbient[0], lightModelAmbient[1], lightModelAmbient[2]);
616
617
618
619
620


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

621
  for (size_t i = 0; i < renderObjects_.size(); ++i)
622
  {
623
    if (renderObjects_[i].depthMapUniformName)
624
625
626
627
628
629
      requiresSceneDepths = true;
  }

  // render scene depth map
  if (requiresSceneDepths)
    renderDepthMap(curViewerID_, _glState->viewport_width(), _glState->viewport_height());
Jan Möbius's avatar
Jan Möbius committed
630
631
632
633
}



634
void IRenderer::finishRenderingPipeline(bool _drawOverlay)
Jan Möbius's avatar
Jan Möbius committed
635
{
636
637
638
639
#ifdef GL_ARB_vertex_array_object
  glBindVertexArray(0);
#endif

640
641
642
643
  // draw thick lines
  if (enableLineThicknessGL42_)
    renderLineThicknessGL42();

644
645
  if (_drawOverlay)
  {
646
    const int numOverlayObj = overlayObjects_.size();
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
    // 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);
    }

  }

692
693
694
695
#ifdef GL_ARB_vertex_array_object
  glBindVertexArray(0);
#endif

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

Jan Möbius's avatar
Jan Möbius committed
699
700
  glDepthMask(1);
  glColorMask(1,1,1,1);
701

Jan Möbius's avatar
Jan Möbius committed
702
  glUseProgram(0);
703

Jan Möbius's avatar
Jan Möbius committed
704
705
  glBindBuffer