DepthPeeling.cc 50.4 KB
Newer Older
Jan Möbius's avatar
 
Jan Möbius committed
1
2
/*===========================================================================*\
*                                                                            *
Jan Möbius's avatar
Jan Möbius committed
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
*                              OpenFlipper                                   *
*      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen       *
*                           www.openflipper.org                              *
*                                                                            *
*--------------------------------------------------------------------------- *
*  This file is part of OpenFlipper.                                         *
*                                                                            *
*  OpenFlipper is free software: you can redistribute it and/or modify       *
*  it under the terms of the GNU Lesser General Public License as            *
*  published by the Free Software Foundation, either version 3 of            *
*  the License, or (at your option) any later version with the               *
*  following exceptions:                                                     *
*                                                                            *
*  If other files instantiate templates or use macros                        *
*  or inline functions from this file, or you compile this file and          *
*  link it with other files to produce an executable, this file does         *
*  not by itself cause the resulting executable to be covered by the         *
*  GNU Lesser General Public License. This exception does not however        *
*  invalidate any other reasons why the executable file might be             *
*  covered by the GNU Lesser General Public License.                         *
*                                                                            *
*  OpenFlipper is distributed in the hope that it will be useful,            *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of            *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
*  GNU Lesser General Public License for more details.                       *
*                                                                            *
*  You should have received a copy of the GNU LesserGeneral Public           *
*  License along with OpenFlipper. If not,                                   *
*  see <http://www.gnu.org/licenses/>.                                       *
*                                                                            *
\*===========================================================================*/

/*===========================================================================*\
*                                                                            *
*   $Revision$                                                       *
*   $LastChangedBy$                                                *
*   $Date$                     *
Jan Möbius's avatar
 
Jan Möbius committed
40
41
42
43
44
45
46
47
48
49
50
51
*                                                                            *
\*===========================================================================*/

#include "DepthPeeling.hh"
#include <OpenFlipper/common/GlobalOptions.hh>
#include <ObjectTypes/Light/LightNode.hh>


// this define enables a shader export of the generated peel shader for debugging purpose
//#define DEPTHPEELING_SHADER_EXPORT


Jan Möbius's avatar
Jan Möbius committed
52
53
54
55
56
57
DepthPeelingPlugin::DepthPeelingPlugin() :
        blendQueryID_(0),
        glStateTmp_(0),
        numLights_(0)
{

Jan Möbius's avatar
Jan Möbius committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
  for (unsigned int i = 0; i < 16; ++i)
    lightTypes_[i] = LIGHTTYPE_POINT;

  for (unsigned int i = 0; i < PEEL_NUM_COMBINATIONS; ++i)
    peelProgs_[i] = 0;

  for (unsigned int i = 0; i < PEEL_NUM_COMBINATIONS*3; ++i)
    peelShaders_[i] = 0;

  for (unsigned int i = 0; i < 8; ++i)
    blendShaders_[i] = 0;

  for (unsigned int i = 0; i < 4; ++i)
    blendDualPeelProg_[i] = 0;


Jan Möbius's avatar
Jan Möbius committed
74
75
76
77
78
79
80
}

DepthPeelingPlugin::~DepthPeelingPlugin() {

}


Jan Möbius's avatar
 
Jan Möbius committed
81
82
83
84
85
86
87
88
89
90
91
92
93
DepthPeelingPlugin::ViewerResources::ViewerResources()
{
  rtWidth_ = rtHeight_ = 0;

  glWidth_ = glHeight_ = 0;

  memset(blendDualPeelTexID_, 0, 7*4);

  blendDualPeelFbo_ = 0;
}

void DepthPeelingPlugin::initializePlugin()
{
94
95
  memset(blendShaders_, 0, sizeof(blendShaders_));
  memset(peelShaders_, 0, sizeof(peelShaders_));
Jan Möbius's avatar
 
Jan Möbius committed
96

97
98
  memset(blendDualPeelProg_, 0, sizeof(blendDualPeelProg_));
  memset(peelProgs_, 0, sizeof(peelProgs_));
Jan Möbius's avatar
 
Jan Möbius committed
99
100

  blendQueryID_ = 0;
Jan Möbius's avatar
Jan Möbius committed
101
  numLights_    = 0;
Jan Möbius's avatar
 
Jan Möbius committed
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

  ACG::glCheckErrors();
}

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

void DepthPeelingPlugin::exit()
{
  destroyResources();
}

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

QString DepthPeelingPlugin::rendererName() {
  return QString("Depth Peeling Renderer");
}

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

void DepthPeelingPlugin::supportedDrawModes(ACG::SceneGraph::DrawModes::DrawMode& _mode) {
  _mode =  ACG::SceneGraph::DrawModes::DEFAULT;
}

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

void DepthPeelingPlugin::reloadResources(int _viewerId) {
  // called in constructor and resizeEvent()

  ACG::GLState::syncFromGL();

  ViewerResources* p = &viewerRes_[_viewerId];

  if (!p->glWidth_ || !p->glHeight_) return;

  destroyResources(_viewerId);

  // dual depth peeling rt's
  glGenTextures(7, p->blendDualPeelTexID_);
  GLint DualPeelIntFmt[] = {GL_RG32F, GL_RG32F, // depth0, depth1
                 GL_RGBA, GL_RGBA, // front blender0, ..._1
                 GL_RGBA, GL_RGBA, // back_temp_tex0, ..._1,
                 GL_RGB};   // back_blender

  for (int i = 0; i < 7; ++i)
  {
    GLint fmt = GL_RGB; // fmt for depth textures

    if (i >= 2) fmt = GL_RGBA; // fmt for front_blender01 and back_temp01
    if (i == 6) fmt = GL_RGB; // fmt for back_blender

Jan Möbius's avatar
Jan Möbius committed
152
153
154
155
156
157
158
    ACG::GLState::bindTexture(GL_TEXTURE_RECTANGLE_EXT, p->blendDualPeelTexID_[i]);
    // texture access: clamped
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP);
    // filter: none
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
Jan Möbius's avatar
 
Jan Möbius committed
159

Jan Möbius's avatar
Jan Möbius committed
160
161
162
163
    glTexImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, DualPeelIntFmt[i], p->glWidth_, p->glHeight_, 0, fmt, GL_FLOAT, 0);



Jan Möbius's avatar
 
Jan Möbius committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

    ACG::glCheckErrors();
  }

  p->rtWidth_ = p->glWidth_;
  p->rtHeight_ = p->glHeight_;

  // dual depth peeling fbo's
  glGenFramebuffersEXT(1, &p->blendDualPeelFbo_);
  {
    // layer_peel fbo
    ACG::GLState::bindFramebuffer(GL_FRAMEBUFFER, p->blendDualPeelFbo_);

    // color_attachment order:
    // depth0, front_blend0, back_temp0,   depth1, front_blend1, back_temp1,    back_blender_tex_id

    for (int i = 0; i < 6; ++i)
    {
      glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+i,
Jan Möbius's avatar
Jan Möbius committed
183
        GL_TEXTURE_RECTANGLE_EXT, p->blendDualPeelTexID_[i < 3 ? 2*i : 2*(i-3) +1], 0);
Jan Möbius's avatar
 
Jan Möbius committed
184
185
186
    }

    // back_blender_tex_id
Jan Möbius's avatar
Jan Möbius committed
187
      glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT6, GL_TEXTURE_RECTANGLE_EXT,
Jan Möbius's avatar
Jan Möbius committed
188
                                p->blendDualPeelTexID_[6], 0);
Jan Möbius's avatar
 
Jan Möbius committed
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
  }

  ACG::GLState::bindFramebuffer(GL_FRAMEBUFFER, 0);


  // load shaders

  const char* ShaderFiles[] = {"Blending/dual_peeling_init_vertex.glsl",
    "Blending/dual_peeling_init_fragment.glsl",
    "Blending/dual_peeling_blend_vertex.glsl",
    "Blending/dual_peeling_blend_fragment.glsl",
    "Blending/dual_peeling_final_vertex.glsl",
    "Blending/dual_peeling_final_fragment.glsl"};

  for (int i = 0; i < 6; ++i)
  {
    QString shaderFile = OpenFlipper::Options::shaderDirStr() + QDir::separator() + QString(ShaderFiles[i]);

    if (blendShaders_[i]) continue;

    if (i & 1) // alternating vertex/fragment shader
      blendShaders_[i] = GLSL::loadFragmentShader(shaderFile.toUtf8());
    else
      blendShaders_[i] = GLSL::loadVertexShader(shaderFile.toUtf8());

    if (!blendShaders_[i]) {
      log(LOGERR, QString(ShaderFiles[i]) + QString(" could not be loaded and compiled"));
      return;
    }
  }

  // dual depth peeling programs

  if (!blendDualPeelProg_[0])
  {
    for (int i = 0; i < 4; ++i)
    {
      if (i != 1)
        blendDualPeelProg_[i] = new GLSL::Program();
    }

    // init shaders
    blendDualPeelProg_[0]->attach(blendShaders_[0]);
    blendDualPeelProg_[0]->attach(blendShaders_[1]);
    blendDualPeelProg_[0]->link();

    // blend shaders
    blendDualPeelProg_[2]->attach(blendShaders_[2]);
    blendDualPeelProg_[2]->attach(blendShaders_[3]);
    blendDualPeelProg_[2]->link();

    // final shaders
    blendDualPeelProg_[3]->attach(blendShaders_[4]);
    blendDualPeelProg_[3]->attach(blendShaders_[5]);
    blendDualPeelProg_[3]->link();
  }

  if (!blendQueryID_)
    glGenQueries(1, &blendQueryID_);

  ACG::glCheckErrors();
}

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

void DepthPeelingPlugin::destroyResources() {
  // called in destructor and reloadBlendingTech()

  if (blendQueryID_)
    glDeleteQueries(1, &blendQueryID_);
  blendQueryID_ = 0;

  for (int i = 0; i < 4; ++i)
  {
    delete blendDualPeelProg_[i]; blendDualPeelProg_[i] = 0;
  }

  for (unsigned int i = 0; i < sizeof(blendShaders_) / sizeof(blendShaders_[0]); ++i)
  {
    delete blendShaders_[i];
    blendShaders_[i] = 0;
  }

272
273
274
275
276
277
278
279
280
281
  for (unsigned int i = 0; i < sizeof(peelShaders_) / sizeof(peelShaders_[0]); ++i)
  {
    delete peelShaders_[i]; peelShaders_[i] = 0;
  }

  for (unsigned int i = 0; i < sizeof(peelProgs_) / sizeof(peelProgs_[0]); ++i)
  {
    delete peelProgs_[i]; peelProgs_[i] = 0;
  }

Jan Möbius's avatar
 
Jan Möbius committed
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
  // free all viewer specific resources
  std::map<int, ViewerResources>::iterator resIt = viewerRes_.begin();
  for (; resIt != viewerRes_.end(); ++resIt)
    destroyResources(resIt->first);
}

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

void DepthPeelingPlugin::destroyResources(int _viewerId)
{
  ViewerResources* p = &viewerRes_[_viewerId];

  if (p->blendDualPeelFbo_) glDeleteFramebuffersEXT(1, &p->blendDualPeelFbo_);
  p->blendDualPeelFbo_ = 0;

  if (p->blendDualPeelTexID_) glDeleteTextures(7, p->blendDualPeelTexID_);
  memset(p->blendDualPeelTexID_, 0, sizeof(p->blendDualPeelTexID_));
}

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

void DepthPeelingPlugin::drawQuadProj(float x0, float y0, float w, float h)
{
  // quad in projection space
  // here only position are passed to GL
  // tex-coords can be generated in a vertex-shader as follows
  //  uv = pos * (.5, -.5) + (.5, .5)

  glBegin(GL_QUADS);
  {
    glVertex2f(x0,  y0);
    glVertex2f(x0, y0-h);
    glVertex2f(x0+w, y0-h);
    glVertex2f(x0+w, y0);
  }
  glEnd();
}

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

void DepthPeelingPlugin::traverseLightNodes( BaseNode* _node)
{
  std::vector<int> pLightTypes;

  if (_node)
  {
    BaseNode::StatusMode status(_node->status());
    bool process_children(status != BaseNode::HideChildren);

    // If the subtree is hidden, ignore this node and its children while rendering
    if (status != BaseNode::HideSubtree)
    {

      if (_node->status() != BaseNode::HideNode)
      {
        ACG::SceneGraph::LightNode* lnode = dynamic_cast<ACG::SceneGraph::LightNode*>(_node);
        if (lnode)
        {
          ACG::SceneGraph::LightSource light;
          lnode->getLightSource(&light);

//          GLenum lightID = lnode->getGLLightID();
          GLenum lightID = numLights_ + GL_LIGHT0;

          if (lightID != GL_INVALID_ENUM)
          {
            int id = lightID - GL_LIGHT0;

            if (numLights_ < 8)
            {
              if (light.directional())
                lightTypes_[numLights_] = LIGHTTYPE_DIRECTIONAL;
              else if (light.spotCutoff() > 179.5f)
                lightTypes_[numLights_] = LIGHTTYPE_POINT;
              else
                lightTypes_[numLights_] = LIGHTTYPE_SPOT;

              glLightIDs_[numLights_] = id;
              
              ++numLights_;
            }

          }

        }
      }

      if (process_children)
      {

        BaseNode::ChildIter cIt, cEnd(_node->childrenEnd());

        // Process all children which are not second pass
        for (cIt = _node->childrenBegin(); cIt != cEnd; ++cIt)
          if (~(*cIt)->traverseMode() & BaseNode::SecondPass)
            traverseLightNodes(*cIt);

        // Process all children which are second pass
        for (cIt = _node->childrenBegin(); cIt != cEnd; ++cIt)
          if ((*cIt)->traverseMode() & BaseNode::SecondPass)
            traverseLightNodes(*cIt);

      }

    }
  }
}

// depth peeling shader generation

void DepthPeelingPlugin::generatePeelingShaders(GLSL::StringList* _strVertexShaderOut,
                                                GLSL::StringList* _strFragmentShaderOut,
                                                GLSL::StringList* _strGeometryShaderOut,
                                                bool _textured,
                                                bool _flatShaded,
397
398
399
                                                bool _phong,
                                                bool _vertexColor,
                                                bool _wireFrame)
Jan Möbius's avatar
 
Jan Möbius committed
400
401
{
  if (_flatShaded) _phong = false;
402
  if (_vertexColor) _phong = false;
Jan Möbius's avatar
 
Jan Möbius committed
403
404
405
406
407
408
409
410

  std::string strColor = "color";
  std::string strNormal = "normal";
  std::string strFragPos = "vPosVS";

  if (_flatShaded)
    strFragPos = "VPosVS";

411
412
413
  if (_wireFrame)
    _flatShaded = _vertexColor = _textured = _phong = false;

Jan Möbius's avatar
 
Jan Möbius committed
414
415
  std::string strCode = "";

416
  for (unsigned int i = 0; i < numLights_ && (!_wireFrame); ++i)
Jan Möbius's avatar
 
Jan Möbius committed
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
  {
    // new code block for this light
    strCode += "{\n";

    std::string strLight = "gl_LightSource[";
    std::string strMaterial = "gl_FrontLightProduct[";
    {
      char szTmp[8];
      sprintf(szTmp, "%d]", glLightIDs_[i]);

      strLight += szTmp;
      strMaterial += szTmp;
    }

    // light vector
    if (lightTypes_[i] == LIGHTTYPE_DIRECTIONAL)
      strCode += "vec3 vLightVS = " + strLight + ".position.xyz;\n";
    else
      strCode += "vec3 vLightVS = " + strLight + ".position.xyz - " + strFragPos + ".xyz;\n";

    strCode += "vec3 vLightDir = normalize(vLightVS);\n";

    // ambient
    strCode += "vec4 colLight = " + strMaterial + ".ambient;\n";

    // diffuse
    strCode += "float ldotn = dot(vLightDir, " + strNormal + ");\n";
    strCode += "ldotn = clamp(ldotn, 0.0, 1.0);\n";
    strCode += "colLight += ldotn * ";
    if (_textured && _phong)
      strCode += "diffColor * ";
448
449
450
451
452
453
454
455
456

    if (_vertexColor)
    {
      if (_flatShaded)
        strCode += "vColor[2];\n";
      else
        strCode += "gl_Color;\n";
    }
    else
Jan Möbius's avatar
 
Jan Möbius committed
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
    strCode += strMaterial + ".diffuse;\n";

    //specular
    strCode += "colLight += floor(ldotn + 0.9) * pow(ldotn, gl_FrontMaterial.shininess) * " + strMaterial + ".specular;\n";


    if (lightTypes_[i] == LIGHTTYPE_DIRECTIONAL)
      strCode += strColor + ".rgb += colLight.rgb;\n";
    else 
    {
      // attenuation
      strCode += "float fLenSq = dot(vLightVS, vLightVS);\n";
      strCode += "float atten = " + strLight + ".constantAttenuation + " +
        strLight + ".linearAttenuation * sqrt(fLenSq) + " +
        strLight + ".quadraticAttenuation * fLenSq;\n";

      if (lightTypes_[i] == LIGHTTYPE_POINT)
        strCode += strColor + ".rgb += colLight.rgb / atten;\n";
      else
      {
        // spotlight
        strCode += "float spot = -dot(vLightDir, " + strLight + ".spotDirection);\n";
        strCode += "spot *= step(" + strLight + ".spotCosCutoff, spot);\n";
        strCode += "spot *= pow(spot, " + strLight + ".spotExponent);\n";

        strCode += strColor + ".rgb += " + "(spot / atten) * colLight.rgb;\n";
      }
    }

    strCode += "}\n";
  }

  const char* szVertexShader[] = {"varying vec2 vTexCoord;",
    "varying vec3 vNormal;  // normal: view space",
    "varying vec4 vPosVS; // position in view space",
    "varying vec4 vColor; // used in gouraud / flat shading only",
    "",
    "void main(void)",
    "{",
    "  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;",
    "  ",
    "  vNormal = gl_NormalMatrix * gl_Normal; // gl_NormalMatrix : upper left 3x3 of WorldViewIT",
    "  vPosVS = (gl_ModelViewMatrix * gl_Vertex);",
    "  vTexCoord = gl_MultiTexCoord0.xy;",
    ""};
  // NOTE: this vertex shader code misses the ending '}' to append the lighting code later

  // geometry shader for flat shading only
  const char* szGeometryShaderStart[] = {
    "#version 120",
    "#extension GL_ARB_geometry_shader4 : enable",
    "",
    "varying vec2 vTexCoord[3];",
    "varying vec4 vPosVS[3];",
    "varying vec3 vNormal[3];",
    "varying vec4 vColor[3];",
    "",
    "varying vec2 VTexCoord;",
    "varying vec3 VNormal;",
    "varying vec4 VPosVS;",
    "varying vec4 VColor;",
    "",
    "",
    "void main()",
    "{",
    "   // recompute triangle normal",
//    "   vec3 normal = cross(vNormal[2].xyz - vNormal[0].xyz, vNormal[1].xyz - vNormal[0].xyz);",
    "   vec3 normal = cross(gl_PositionIn[1].xyz - gl_PositionIn[0].xyz, gl_PositionIn[2].xyz - gl_PositionIn[0].xyz);",
    "   normal = normalize(normal);",
    "   normal = gl_NormalMatrix * normal;",
//    "   normal = vNormal[2].xyz;",
    "   ",
    "   VPosVS = (gl_PositionIn[0] + gl_PositionIn[1] + gl_PositionIn[2]) / 3.0;",
    "   VPosVS = gl_ModelViewMatrix * VPosVS; // triangle center in view space needed for point and spot lights",
    "   vec4 color = vec4(gl_FrontMaterial.emission.rgb, gl_FrontMaterial.ambient.a);",
    ""};

  const char* szGeometryShaderEnd[] = {
    "",
    "   for(int i = 0; i < 3; i++)",
    "   {",
    "     gl_Position = gl_ModelViewProjectionMatrix * gl_PositionIn[i];",
    "	 VTexCoord = vTexCoord[i];",
    "	 VNormal = normal;",
    "	 VPosVS = vPosVS[i];",
//    "	 VColor = (normal+vec3(0.5,0.5,0.5)).xyzz*0.5;",
    "	 VColor = color;",
    "     EmitVertex();",
    "   }",
    "   EndPrimitive();",
    "   ",
    "}"};

  const char* szFragmentShaderStart[] = {"varying vec2 vTexCoord;",
    "varying vec3 vNormal; ",
    "varying vec4 vPosVS;",
    "varying vec4 vColor;",
    "",
    "uniform sampler2D DiffuseTex;",
    "uniform sampler2DRect DepthBlenderTex;",
    "uniform sampler2DRect FrontBlenderTex;",
    "",
    "#define MAX_DEPTH 1.0",
    "",
    "",
    "void main(void)",
    "{",
    "  // window-space depth interpolated linearly in screen space",
    "  float fragDepth = gl_FragCoord.z;",
    "",
    "  vec2 depthBlender = texture2DRect(DepthBlenderTex, gl_FragCoord.xy).xy;",
    "  vec4 forwardTemp = texture2DRect(FrontBlenderTex, gl_FragCoord.xy);",
    "  ",
    "  // Depths and 1.0-alphaMult always increase",
    "  // so we can use pass-through by default with MAX blending",
    "  gl_FragData[0].xy = depthBlender;",
    "  ",
    "  // Front colors always increase (DST += SRC*ALPHA_MULT)",
    "  // so we can use pass-through by default with MAX blending",
    "  gl_FragData[1] = forwardTemp;",
    "  ",
    "  // Because over blending makes color increase or decrease,",
    "  // we cannot pass-through by default.",
    "  // Each pass, only one fragment writes a color greater than 0",
    "  gl_FragData[2] = vec4(0.0);",
    "",
    "  float nearestDepth = -depthBlender.x;",
    "  float farthestDepth = depthBlender.y;",
    "  float alphaMultiplier = 1.0 - forwardTemp.w;",
    "",
    "  if (fragDepth < nearestDepth || fragDepth > farthestDepth) {",
    "    // Skip this depth in the peeling algorithm",
    "    gl_FragData[0].xy = vec2(-MAX_DEPTH);",
    "    return;",
    "  }",
    "  ",
    "  if (fragDepth > nearestDepth && fragDepth < farthestDepth) {",
    "    // This fragment needs to be peeled again",
    "    gl_FragData[0].xy = vec2(-fragDepth, fragDepth);",
    "    return;",
    "  }",
    "  ",
    "  // If we made it here, this fragment is on the peeled layer from last pass",
    "  // therefore, we need to shade it, and make sure it is not peeled any farther",
    "",};

  const char* szFragmentShaderEnd[] = {"",
    "  gl_FragData[0].xy = vec2(-MAX_DEPTH);",
    "  ",
    "  if (fragDepth == nearestDepth) {",
    "    gl_FragData[1].xyz += color.rgb * color.a * alphaMultiplier;",
    "    gl_FragData[1].w = 1.0 - alphaMultiplier * (1.0 - color.a);",
    "  } else {",
    "    gl_FragData[2] += color;",
    "  }",
    "}"};

  // assemble final shaders:

  // vertex shader
  for (unsigned int i = 0; i < sizeof(szVertexShader) / sizeof(char*); ++i)
  {
    std::string str = szVertexShader[i];
    if (_phong)
    {
      if (!strncmp("varying vec4 vColor", str.c_str(), strlen("varying vec4 vColor")))
      {
//        str.replace(str.begin(), str.begin() + 7, "flat out");
        str += "\n";
        continue;
      }
    }
    str += "\n";
    _strVertexShaderOut->push_back(str);
  }

  // finalize vertex shader
634
  if (!_phong && !_flatShaded && !_wireFrame)
Jan Möbius's avatar
 
Jan Möbius committed
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
  {
    // lighting code:
    _strVertexShaderOut->push_back("\nvec4 color = vec4(gl_FrontMaterial.emission.rgb, gl_FrontMaterial.ambient.a);");
    _strVertexShaderOut->push_back("\nvec3 normal = vNormal;\n");

    std::string::size_type curPos = 0;
    std::string::size_type newLinePos = strCode.find_first_of('\n');
    while (newLinePos != std::string::npos)
    {
      _strVertexShaderOut->push_back(strCode.substr(curPos, newLinePos - curPos + 1));
      curPos = newLinePos + 1; 
      newLinePos = strCode.find_first_of('\n', curPos);
    }
    _strVertexShaderOut->push_back("\nvColor = color;\n");
  }
  if (_flatShaded)
651
652
653
  {
    if (_vertexColor)
      _strVertexShaderOut->push_back("vColor = gl_Color;\n");
Jan Möbius's avatar
 
Jan Möbius committed
654
    _strVertexShaderOut->push_back("gl_Position = gl_Vertex;\n");
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
676
677
678
679
680
681
682
683
684
685
686

  _strVertexShaderOut->push_back("\n}");
  
  // fragment shader:
  for (unsigned int i = 0; i < sizeof(szFragmentShaderStart) / sizeof(char*); ++i)
  {
    std::string str = szFragmentShaderStart[i];
    if (_phong)
    {
      if (!strncmp("varying vec4 vColor", str.c_str(), strlen("varying vec4 vColor")))
      {
//        str.replace(str.begin(), str.begin() + 7, "flat in");
          str += "\n";
          continue;
      }
    }
    if (_flatShaded)
    {
      if (!strncmp("varying vec2 vTexCoord", str.c_str(), strlen("varying vec2 vTexCoord")))
        str = "varying vec2 VTexCoord;";
      if (!strncmp("varying vec3 vNormal", str.c_str(), strlen("varying vec3 vNormal")))
        str = "varying vec3 VNormal;";
      if (!strncmp("varying vec4 vPosVS", str.c_str(), strlen("varying vec4 vPosVS")))
        str = "varying vec4 VPosVS;";
      if (!strncmp("varying vec4 vColor", str.c_str(), strlen("varying vec4 vColor")))
        str = "varying vec4 VColor;";
    }
    str += "\n";
    _strFragmentShaderOut->push_back(str);
  }

687
  if (!_wireFrame)
Jan Möbius's avatar
 
Jan Möbius committed
688
  {
689
690
691
    if (!_flatShaded)
    {
      _strFragmentShaderOut->push_back("  vec3 normal = normalize(vNormal);\n");
692
//      _strFragmentShaderOut->push_back("  vec3 normal = normalize(cross(dFdx(vPosVS.xyz), dFdy(vPosVS.xyz)));\n");
693
694
695
696
      _strFragmentShaderOut->push_back("  vec4 color = vec4(gl_FrontMaterial.emission.rgb, gl_FrontMaterial.ambient.a);\n");
      if (_textured)
        _strFragmentShaderOut->push_back(" vec4 diffColor = texture2D(DiffuseTex, vTexCoord); color.a *= diffColor.a;\n");
    }
Jan Möbius's avatar
 
Jan Möbius committed
697
698
    else
    {
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
      _strFragmentShaderOut->push_back("  vec4 color = vec4(gl_FrontMaterial.emission.rgb, gl_FrontMaterial.ambient.a);\n");
      _strFragmentShaderOut->push_back("  vec4 vColor = VColor;\n");
      if (_textured)
        _strFragmentShaderOut->push_back(" vec4 diffColor = texture2D(DiffuseTex, VTexCoord); color.a *= diffColor.a;\n");
    }
    
    if (!_phong)
    {
      if (_textured)
        _strFragmentShaderOut->push_back(" color = diffColor * vColor;\n");
      else
        _strFragmentShaderOut->push_back(" color = vColor;\n");
    }
    else
    {
      // lighting code:
      std::string::size_type curPos = 0;
      std::string::size_type newLinePos = strCode.find_first_of('\n');
      while (newLinePos != std::string::npos)
      {
        _strFragmentShaderOut->push_back(strCode.substr(curPos, newLinePos - curPos + 1));
        curPos = newLinePos + 1; 
        newLinePos = strCode.find_first_of('\n', curPos);
      }
Jan Möbius's avatar
 
Jan Möbius committed
723
724
    }
  }
725
726
  else // wireframe: no shading necessary
    _strFragmentShaderOut->push_back("  vec4 color = vec4(1.0, 1.0, 1.0, gl_FrontMaterial.ambient.a);\n");
Jan Möbius's avatar
 
Jan Möbius committed
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

  for (unsigned int i = 0; i < sizeof(szFragmentShaderEnd) / sizeof(char*); ++i)
  {
    std::string str = szFragmentShaderEnd[i];
    str += "\n";
    _strFragmentShaderOut->push_back(str);
  }


  // geometry shader:
  if (_flatShaded)
  {
    for (unsigned int i = 0; i < sizeof(szGeometryShaderStart) / sizeof(char*); ++i)
    {
      std::string str = szGeometryShaderStart[i];
      str += "\n";
      _strGeometryShaderOut->push_back(str);
    }

    // lighting code:
    std::string::size_type curPos = 0;
    std::string::size_type newLinePos = strCode.find_first_of('\n');
    while (newLinePos != std::string::npos)
    {
      _strGeometryShaderOut->push_back(strCode.substr(curPos, newLinePos - curPos + 1));
      curPos = newLinePos + 1; 
      newLinePos = strCode.find_first_of('\n', curPos);
    }

    for (unsigned int i = 0; i < sizeof(szGeometryShaderEnd) / sizeof(char*); ++i)
    {
      std::string str = szGeometryShaderEnd[i];
      str += "\n";
      _strGeometryShaderOut->push_back(str);
    }
  }


  // debug output:
#ifdef DEPTHPEELING_SHADER_EXPORT
  FILE* pShaderOut = fopen("peel_vertex.glsl", "wt");
  for (GLSL::StringList::iterator it = _strVertexShaderOut->begin(); it != _strVertexShaderOut->end(); ++it)
    fprintf(pShaderOut, it->c_str());
  fclose(pShaderOut);


  pShaderOut = fopen("peel_frag.glsl", "wt");
  for (GLSL::StringList::iterator it = _strFragmentShaderOut->begin(); it != _strFragmentShaderOut->end(); ++it)
    fprintf(pShaderOut, it->c_str());
  fclose(pShaderOut);

  if (_flatShaded)
  {
    pShaderOut = fopen("peel_geom.glsl", "wt");
    for (GLSL::StringList::iterator it = _strGeometryShaderOut->begin(); it != _strGeometryShaderOut->end(); ++it)
      fprintf(pShaderOut, it->c_str());
    fclose(pShaderOut);
  }
#endif
}

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

790
791
792
template <class Action>
bool
DepthPeelingPlugin::traverseDrawApplyAction( BaseNode* _node, Action& _action, ACG::SceneGraph::DrawModes::DrawMode _globalDrawMode, int _pass, int _peelPass)
Jan Möbius's avatar
 
Jan Möbius committed
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
  bool ret = true; // process_children flag returned

  // use nodes drawmode to grab a peeler program with correct shading
  ACG::SceneGraph::DrawModes::DrawMode dm, dmSave = _node->drawMode();
  dm = dmSave;

  if (!dm) return ret;

  if (dm & ACG::SceneGraph::DrawModes::DEFAULT)
    dm = _globalDrawMode;
/*
  if (dm & ACG::SceneGraph::DrawModes::HIDDENLINE)
  {
    // hiddenline is accomplished with wireframe in first peel layer only
    dm &= ~ACG::SceneGraph::DrawModes::HIDDENLINE;
    dm |= ACG::SceneGraph::DrawModes::WIREFRAME;
    if (_peelPass > 2)
      return ret;
    _node->drawMode(dm);
  }
*/
  if (dm & ACG::SceneGraph::DrawModes::WIREFRAME || dm & ACG::SceneGraph::DrawModes::HIDDENLINE)
  {
    ACG::SceneGraph::DrawModes::DrawMode dmShaded = dm;
    dmShaded &= ~ACG::SceneGraph::DrawModes::WIREFRAME;
    dmShaded &= ~ACG::SceneGraph::DrawModes::HIDDENLINE;

    // polygon only draw
    if (dmShaded)
    {
      _node->drawMode(dmShaded); // evil method: change nodes drawmode here, restore it later
      ret &= traverseDrawApplyAction(_node, _action, _globalDrawMode, _pass, _peelPass);
    }

    // wireframe only follows
    dm &= (~dmShaded);
    _node->drawMode(dm);
  }

Jan Möbius's avatar
Jan Möbius committed
833
  unsigned int shaderIndex = getPeelShaderIndex(dm);
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899

  // do hiddenline algorithmus manually here
  GLenum prev_depth = glStateTmp_->depthFunc();
  if (dm & ACG::SceneGraph::DrawModes::HIDDENLINE)
  {
    // manual hiddenline

    // First:
    // Render all faces in background color to initialize z-buffer
    _node->drawMode(ACG::SceneGraph::DrawModes::SOLID_SMOOTH_SHADED);

    GLSL::Program* peelProg = peelProgs_[PEEL_SHADER_HIDDENLINE];
    peelProg->use();
    peelProg->setUniform("DepthBlenderTex", 4);
    peelProg->setUniform("FrontBlenderTex", 5);
    peelProg->setUniform("ObjectColor", glStateTmp_->clear_color());

    ACG::GLState::depthRange(0.01, 1.0);
    ACG::GLState::lockDepthRange();
    ACG::GLState::lockProgram();
    ret &= _action(_node);
    ACG::GLState::unlockProgram();
    ACG::GLState::unlockDepthRange();
    ACG::GLState::depthRange(0.0, 1.0);

    // Second
    // Render the lines. All lines not on the front will be skipped in z-test
    _node->drawMode(ACG::SceneGraph::DrawModes::WIREFRAME);

    ACG::GLState::depthFunc(GL_LEQUAL);
    ACG::GLState::lockDepthFunc();

    // use wireframe shader now
    shaderIndex = PEEL_SHADER_WIREFRAME;
  }

  GLSL::Program* peelProg = peelProgs_[shaderIndex];
  peelProg->use();
  peelProg->setUniform("DepthBlenderTex", 4);
  peelProg->setUniform("FrontBlenderTex", 5);

  if (shaderIndex & PEEL_SHADER_FLAT)
  {
    // set geomtry shader constants
    peelProg->setGeometryInputType(GL_TRIANGLES);
    peelProg->setGeometryOutputType(GL_TRIANGLE_STRIP);
    peelProg->setGeometryVertexCount(3);
  }
  peelProg->setUniform("DiffuseTex", 0);

  ACG::GLState::lockProgram();
  ret &= _action(_node);
  ACG::GLState::unlockProgram();

  // restore state
  _node->drawMode(dmSave);

  if (dm & ACG::SceneGraph::DrawModes::HIDDENLINE)
  {
    ACG::GLState::unlockDepthFunc();

    //restore depth buffer comparison function
    ACG::GLState::depthFunc(prev_depth);
  }

  return ret;
Jan Möbius's avatar
 
Jan Möbius committed
900
901
902
903
}

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

904
905
906
template <class Action>
void
DepthPeelingPlugin::traverseDraw( BaseNode* _node, Action& _action, ACG::SceneGraph::DrawModes::DrawMode _globalDrawMode, int _pass, int _peelPass)
Jan Möbius's avatar
 
Jan Möbius committed
907
908
{

909
910
911
912
  // Process node if it exists
  if (_node) {
    BaseNode::StatusMode status(_node->status());
    bool process_children(status != BaseNode::HideChildren);
Jan Möbius's avatar
 
Jan Möbius committed
913

914
915
    // If the subtree is hidden, ignore this node and its children while rendering
    if (status != BaseNode::HideSubtree) {
Jan Möbius's avatar
 
Jan Möbius committed
916

917
918
919
920
      // Executes this nodes enter function (if available and active in multipass)
      if ( _node->multipassStatusActive(_pass) ) {
        if_has_enter(_action, _node);
      }
Jan Möbius's avatar
 
Jan Möbius committed
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
      // If the node itself is hidden, don't call the action on it.
      // Additionally check if rendering order is node first. otherwise, we will call it after the children.
      // And check if it should be called in this rendering pass.
      if ( (_node->status() != BaseNode::HideNode )  && ( _node->traverseMode() & BaseNode::NodeFirst ) && _node->multipassNodeActive(_pass))
        process_children &= traverseDrawApplyAction(_node, _action, _globalDrawMode, _pass, _peelPass);

      if (process_children) {

        BaseNode::ChildIter cIt, cEnd(_node->childrenEnd());

        // Process all children
        for (cIt = _node->childrenBegin(); cIt != cEnd; ++cIt)
          if (~(*cIt)->traverseMode() & BaseNode::SecondPass)
            traverseDraw(*cIt, _action, _globalDrawMode, _pass, _peelPass);

        // Process all children which are second pass
        for (cIt = _node->childrenBegin(); cIt != cEnd; ++cIt)
          if ((*cIt)->traverseMode() & BaseNode::SecondPass)
            traverseDraw(*cIt, _action, _globalDrawMode, _pass, _peelPass);

      }


      // If we are in childrenfirst node, the children have been painted andwe now check, if we can draw this node.
      // If its hidden, ignore it.
      // If it should not be rendered in this pass, ignore it too.
      if ( (_node->traverseMode() & BaseNode::ChildrenFirst ) && (_node->status() != BaseNode::HideNode) && _node->multipassNodeActive(_pass) )
        process_children &= traverseDrawApplyAction(_node, _action, _globalDrawMode, _pass, _peelPass);

      // Call the leave function of the node (if available and active in multipass).
      if ( _node->multipassStatusActive(_pass) )
        if_has_leave(_action, _node);

    } // if (status != BaseNode::HideSubtree)
  } // if(node_)
}

void DepthPeelingPlugin::drawScenePeelPass(ACG::GLState* _glState, ACG::SceneGraph::DrawModes::DrawMode _drawMode, BaseNode* _sceneGraphRoot, int _peelPass)
{
  ACG::SceneGraph::DrawAction action(_drawMode, *_glState, false);
//  traverseDraw(_sceneGraphRoot, action, *_glState, _drawMode);

  // Reset render pass counter
  _glState->reset_render_pass();

  // Get max render passes
  unsigned int max_passes = _glState->max_render_passes();

  // Render all passes
  for(unsigned int pass = BaseNode::PASS_1; pass <= (BaseNode::PASS_1 + max_passes); ++pass) {

    // Traverse scenegraph
    traverseDraw (_sceneGraphRoot, action, _drawMode, pass, _peelPass);
    // Increment render pass counter by 1
    _glState->next_render_pass();
Jan Möbius's avatar
 
Jan Möbius committed
977
978
  }

979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
  // Reset render pass counter
  _glState->reset_render_pass();
}

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

void DepthPeelingPlugin::drawScenePass(ACG::GLState* _glState, ACG::SceneGraph::DrawModes::DrawMode _drawMode, BaseNode* _sceneGraphRoot)
{
  ACG::SceneGraph::DrawAction action(_drawMode, *_glState, false);
  traverse_multipass(_sceneGraphRoot, action, *_glState, _drawMode);
}

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

void DepthPeelingPlugin::updatePeelingShaderSet()
{
  bool rebuildShaders = false;

Jan Möbius's avatar
 
Jan Möbius committed
997
998
  BaseNode* sceneGraphRoot = PluginFunctions::getSceneGraphRootNode();

999
  // peel shader is rebuilt, if a new light is added or a light type changed
Jan Möbius's avatar
 
Jan Möbius committed
1000

1001
1002
1003
  LightType prevLights[8];
  unsigned int prevIDs[8];
  unsigned int prevNum = numLights_;
Jan Möbius's avatar
 
Jan Möbius committed
1004

1005
1006
  memcpy(prevLights, lightTypes_, sizeof(LightType) * numLights_);
  memcpy(prevIDs, glLightIDs_, sizeof(unsigned int) * numLights_);
Jan Möbius's avatar
 
Jan Möbius committed
1007

1008
1009
  numLights_ = 0;
  traverseLightNodes(sceneGraphRoot);
Jan Möbius's avatar
 
Jan Möbius committed
1010

1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
  // test for necessary shader recompilation
  if (numLights_ == prevNum)
  {
    // look for any light node changes
    if (memcmp(prevLights, lightTypes_, sizeof(LightType) * numLights_) ||
      memcmp(prevIDs, glLightIDs_, sizeof(unsigned int) * numLights_))
      rebuildShaders = true;
  }
  else rebuildShaders = true;

  if (rebuildShaders)
  {
    // delete old shaders and programs
Jan Möbius's avatar
Jan Möbius committed
1024
    for (unsigned int i = 0; i < sizeof(peelShaders_) / sizeof(peelShaders_[0]); ++i)
Jan Möbius's avatar
 
Jan Möbius committed
1025
    {
1026
      delete peelShaders_[i]; peelShaders_[i] = 0;
Jan Möbius's avatar
 
Jan Möbius committed
1027
    }
1028

Jan Möbius's avatar
Jan Möbius committed
1029
    for (unsigned int i = 0; i < sizeof(peelProgs_) / sizeof(peelProgs_[0]); ++i)
Jan Möbius's avatar
 
Jan Möbius committed
1030
    {
1031
      delete peelProgs_[i]; peelProgs_[i] = 0;
Jan Möbius's avatar
 
Jan Möbius committed
1032
1033
    }

Jan Möbius's avatar
Jan Möbius committed
1034
    for (unsigned int i = 0; i < PEEL_NUM_COMBINATIONS; ++i)
Jan Möbius's avatar
 
Jan Möbius committed
1035
    {
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
      GLuint texturedDrawMode = 0, flatDrawMode = 0, phongDrawMode = 0, vertexColorDrawMode = 0, gouraudDrawMode = 0;

      texturedDrawMode = i & PEEL_SHADER_TEXTURED;
      flatDrawMode = i & PEEL_SHADER_FLAT;
      phongDrawMode = i & PEEL_SHADER_PHONG;
      vertexColorDrawMode = i & PEEL_SHADER_VERTEXCOLORS;
      gouraudDrawMode = i & PEEL_SHADER_GOURAUD;

      if (i != PEEL_SHADER_WIREFRAME)
      {
        // filter nonsense
        if (flatDrawMode && phongDrawMode) continue;
        if (flatDrawMode && gouraudDrawMode) continue;
        if (phongDrawMode && gouraudDrawMode) continue;

        if (phongDrawMode + flatDrawMode + gouraudDrawMode == 0) continue;
      }
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063

      if (flatDrawMode)
      {
        // replace flat shading with gouraud, if geometry shaders are not supported
        if (!ACG::checkExtensionSupported("GL_ARB_geometry_shader4") && !ACG::checkExtensionSupported("GL_EXT_geometry_shader4"))
        {
          flatDrawMode = 0;
          gouraudDrawMode = 1;
        }
      }

Jan Möbius's avatar
 
Jan Möbius committed
1064
      GLSL::StringList strVertexShader, strFragmentShader, strGeometryShader;
1065
      generatePeelingShaders(&strVertexShader, &strFragmentShader, &strGeometryShader, texturedDrawMode != 0, flatDrawMode != 0, phongDrawMode != 0, vertexColorDrawMode != 0, i == PEEL_SHADER_WIREFRAME);
Jan Möbius's avatar
 
Jan Möbius committed
1066

1067
      peelProgs_[i] = new GLSL::Program();
1068
      
Jan Möbius's avatar
 
Jan Möbius committed
1069

1070
1071
1072
1073
1074
      GLSL::VertexShader* pVertexSh = new GLSL::VertexShader();
      pVertexSh->setSource(strVertexShader);
      pVertexSh->compile();
      peelShaders_[i*3 + 0] = pVertexSh;
      peelProgs_[i]->attach(pVertexSh);
Jan Möbius's avatar
 
Jan Möbius committed
1075

1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
      if (flatDrawMode)
      {
        GLSL::GeometryShader* pGeomSh = new GLSL::GeometryShader();
        pGeomSh->setSource(strGeometryShader);
        pGeomSh->compile();
        peelShaders_[i*3 + 1] = pGeomSh;
        peelProgs_[i]->attach(pGeomSh);
      }

      GLSL::FragmentShader* pFragSh = new GLSL::FragmentShader();
      pFragSh->setSource(strFragmentShader);
      pFragSh->compile();
      peelShaders_[i*3 + 2] = pFragSh;
      peelProgs_[i]->attach(pFragSh);
Jan Möbius's avatar
 
Jan Möbius committed
1090

1091
1092
      peelProgs_[i]->link();
      ACG::glCheckErrors();
Jan Möbius's avatar
 
Jan Möbius committed
1093
1094


1095
1096
1097
1098
1099
1100
1101
#ifdef DEPTHPEELING_SHADER_EXPORT
      char szFileName[256];
      sprintf(szFileName, "peel_vertex_%02d.glsl", i);
      FILE* pShaderOut = fopen(szFileName, "wt");
      for (GLSL::StringList::iterator it = strVertexShader.begin(); it != strVertexShader.end(); ++it)
        fprintf(pShaderOut, it->c_str());
      fclose(pShaderOut);
Jan Möbius's avatar
 
Jan Möbius committed
1102
1103


1104
1105
1106
1107
1108
      sprintf(szFileName, "peel_frag%02d.glsl", i);
      pShaderOut = fopen(szFileName, "wt");
      for (GLSL::StringList::iterator it = strFragmentShader.begin(); it != strFragmentShader.end(); ++it)
        fprintf(pShaderOut, it->c_str());
      fclose(pShaderOut);
Jan Möbius's avatar
 
Jan Möbius committed
1109
1110
1111

      if (flatDrawMode)
      {
1112
1113
1114
1115
1116
        sprintf(szFileName, "peel_geom%02d.glsl", i);
        pShaderOut = fopen(szFileName, "wt");
        for (GLSL::StringList::iterator it = strGeometryShader.begin(); it != strGeometryShader.end(); ++it)
          fprintf(pShaderOut, it->c_str());
        fclose(pShaderOut);
Jan Möbius's avatar
 
Jan Möbius committed
1117
      }
1118
1119
1120
#endif
    }
  }
Jan Möbius's avatar
 
Jan Möbius committed
1121
1122


1123
1124
1125
  // create a special shader for hiddenline
  // hiddenline = wireframe + early z cull
  // the special shader is needed for the z buffer pass
Jan Möbius's avatar
 
Jan Möbius committed
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
  const char* szVertexShader[] = {
    "void main(void)",
    "{",
    "  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;",
    "}"};

  const char* szFragmentShader[] = {
    "uniform vec4 ObjectColor;",
    "uniform sampler2DRect DepthBlenderTex;",
    "uniform sampler2DRect FrontBlenderTex;",
    "",
    "#define MAX_DEPTH 1.0",
    "",
    "",
    "void main(void)",
    "{",
    "  // window-space depth interpolated linearly in screen space",
    "  float fragDepth = gl_FragCoord.z;",
    "",
    "  vec2 depthBlender = texture2DRect(DepthBlenderTex, gl_FragCoord.xy).xy;",
    "  vec4 forwardTemp = texture2DRect(FrontBlenderTex, gl_FragCoord.xy);",
    "  ",
    "  // Depths and 1.0-alphaMult always increase",
    "  // so we can use pass-through by default with MAX blending",
    "  gl_FragData[0].xy = depthBlender;",
    "  ",
    "  // Front colors always increase (DST += SRC*ALPHA_MULT)",
    "  // so we can use pass-through by default with MAX blending",
    "  gl_FragData[1] = forwardTemp;",
    "  ",
    "  // Because over blending makes color increase or decrease,",
    "  // we cannot pass-through by default.",
    "  // Each pass, only one fragment writes a color greater than 0",
    "  gl_FragData[2] = vec4(0.0);",
    "",
    "  float nearestDepth = -depthBlender.x;",
    "  float farthestDepth = depthBlender.y;",
    "  float alphaMultiplier = 1.0 - forwardTemp.w;",
    "",
    "  if (fragDepth < nearestDepth || fragDepth > farthestDepth) {",
    "    // Skip this depth in the peeling algorithm",
    "    gl_FragData[0].xy = vec2(-MAX_DEPTH);",
    "    return;",
    "  }",
    "  ",
    "  if (fragDepth > nearestDepth && fragDepth < farthestDepth) {",
    "    // This fragment needs to be peeled again",
    "    gl_FragData[0].xy = vec2(-fragDepth, fragDepth);",
    "    return;",
    "  }",
    "  ",
    "  // If we made it here, this fragment is on the peeled layer from last pass",
    "  // therefore, we need to shade it, and make sure it is not peeled any farther",
    "  vec4 color = ObjectColor;",
    "  gl_FragData[0].xy = vec2(-MAX_DEPTH);",
    "  ",
    "  if (fragDepth == nearestDepth) {",
    "    gl_FragData[1].xyz += color.rgb * color.a * alphaMultiplier;",
    "    gl_FragData[1].w = 1.0 - alphaMultiplier * (1.0 - color.a);",
    "  } else {",
    "    gl_FragData[2] += color;",
    "  }",
    "}"};
Jan Möbius's avatar
 
Jan Möbius committed
1190

1191
1192
1193
1194
1195
1196
    GLSL::StringList strVertexShader, strFragmentShader;
    for (unsigned int i = 0; i < sizeof(szVertexShader) / sizeof(char*); ++i)
    {
      std::string str = szVertexShader[i];
      str += "\n";
      strVertexShader.push_back(str);
Jan Möbius's avatar
 
Jan Möbius committed
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

    for (unsigned int i = 0; i < sizeof(szFragmentShader) / sizeof(char*); ++i)
    {
      std::string str = szFragmentShader[i];
      str += "\n";
      strFragmentShader.push_back(str);
    }

    GLSL::Program* peelHiddenLine = peelProgs_[PEEL_SHADER_HIDDENLINE] = new GLSL::Program();

    GLSL::VertexShader* pVertexSh = new GLSL::VertexShader();
    pVertexSh->setSource(strVertexShader);
    pVertexSh->compile();
    peelShaders_[PEEL_SHADER_HIDDENLINE*3 + 0] = pVertexSh;
    peelHiddenLine->attach(pVertexSh);

    GLSL::FragmentShader* pFragSh = new GLSL::FragmentShader();
    pFragSh->setSource(strFragmentShader);
    pFragSh->compile();
    peelShaders_[PEEL_SHADER_HIDDENLINE*3 + 2] = pFragSh;
    peelHiddenLine->attach(pFragSh);

    peelHiddenLine->link();
    ACG::glCheckErrors();
}

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

unsigned int DepthPeelingPlugin::getPeelShaderIndex(ACG::SceneGraph::DrawModes::DrawMode _drawMode)
{
  if (_drawMode & ACG::SceneGraph::DrawModes::WIREFRAME ||
    _drawMode & ACG::SceneGraph::DrawModes::HIDDENLINE)
    return PEEL_SHADER_WIREFRAME;

  bool textured = _drawMode & ACG::SceneGraph::DrawModes::SOLID_TEXTURED || _drawMode & ACG::SceneGraph::DrawModes::SOLID_TEXTURED_SHADED;
  bool flat = _drawMode & ACG::SceneGraph::DrawModes::SOLID_FLAT_SHADED;
  bool phong = _drawMode & ACG::SceneGraph::DrawModes::SOLID_PHONG_SHADED;
  bool vertexColor = _drawMode & ACG::SceneGraph::DrawModes::SOLID_FACES_COLORED || _drawMode & ACG::SceneGraph::DrawModes::SOLID_FACES_COLORED_FLAT_SHADED ||
1236
    _drawMode & ACG::SceneGraph::DrawModes::SOLID_POINTS_COLORED || _drawMode & ACG::SceneGraph::DrawModes::POINTS_COLORED || _drawMode & ACG::SceneGraph::DrawModes::SOLID_FACES_COLORED_SMOOTH_SHADED;
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

  bool gouraud = _drawMode & ACG::SceneGraph::DrawModes::SOLID_SMOOTH_SHADED;

  // fix illegal combinations
  if (phong && flat) flat = false;
  if (flat && gouraud) gouraud = false;
  if (gouraud && phong) phong = false;

  // wireframe, point, etc use gouraud shading
  if ((!phong) && (!gouraud) && (!flat)) gouraud = true;

  unsigned int idx = 0;

  if (flat) idx |= PEEL_SHADER_FLAT;
  if (gouraud) idx |= PEEL_SHADER_GOURAUD;
  if (phong) idx |= PEEL_SHADER_PHONG;
  if (vertexColor) idx |= PEEL_SHADER_VERTEXCOLORS;
  if (textured) idx |= PEEL_SHADER_TEXTURED;

  return idx;
}

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

void DepthPeelingPlugin::render(ACG::GLState* _glState, Viewer::ViewerProperties& _properties)
{
  glStateTmp_ = _glState;

  glPushAttrib(GL_ALL_ATTRIB_BITS);

1267
1268
  const GLuint targetFbo = ACG::GLState::getFramebufferDraw();

1269
1270
1271
1272
1273
1274
1275
1276
  int viewerId = _properties.viewerId();

  ViewerResources* pViewer = &viewerRes_[viewerId];
  pViewer->glWidth_ = _glState->viewport_width();
  pViewer->glHeight_ = _glState->viewport_height();

  if (pViewer->glWidth_ != pViewer->rtWidth_ || pViewer->glHeight_ != pViewer->rtHeight_)
    reloadResources(viewerId);
Jan Möbius's avatar
 
Jan Möbius committed
1277
  
1278
1279
1280
1281
//  updatePeelingShaderSet(viewerId, _properties.drawMode());
  updatePeelingShaderSet();
  BaseNode* sceneGraphRoot = PluginFunctions::getSceneGraphRootNode();

Jan Möbius's avatar
 
Jan Möbius committed
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
  ACG::GLState::depthFunc(GL_LESS);


  ACG::GLState::disable(GL_CULL_FACE);
  ACG::GLState::disable(GL_LIGHTING);
  ACG::GLState::disable(GL_NORMALIZE);

  ACG::GLState::lockDepthFunc();
  ACG::GLState::lockState(GL_CULL_FACE);
  ACG::GLState::lockState(GL_LIGHTING);
  ACG::GLState::lockState(GL_NORMALIZE);

  // from nvidia demo code:
  //  needed some minor adjustments

  GLenum drawBuffers[] = {GL_COLOR_ATTACHMENT0_EXT,
    GL_COLOR_ATTACHMENT1_EXT,
    GL_COLOR_ATTACHMENT2_EXT,
    GL_COLOR_ATTACHMENT3_EXT,
    GL_COLOR_ATTACHMENT4_EXT,
    GL_COLOR_ATTACHMENT5_EXT,
    GL_COLOR_ATTACHMENT6_EXT};

  // the farthest depth value possible in the depth buffer
  const float maxDepth = 1.0f;

  ACG::GLState::disable(GL_DEPTH_TEST);
  ACG::GLState::enable(GL_BLEND);

  ACG::GLState::lockState(GL_DEPTH_TEST);
  ACG::GLState::lockState(GL_BLEND);

  
  
  /* FIXED: VIEWPORT BUG
  
  log-window causes viewport shift by 16 units upward in window's y axis
  therefore the scene gets rendered only in the upper part of the viewport: 
    ->  glViewport(0, 16, glWidht, glHeight_)
  
  glHeight_() is NOT the height of the back buffer (i.e. glViewer window), 
    but the height of scene target view
    -> glHeight_() is 16 units less than the back buffer
  
  -> all render targets are 16 units less in height than back buffer
  
  since the scene has to use the full render targets size,
  use glViewport(0, 0, glWidth_, glHeight_) for all offscreen rendering
  
  in the final pass, shift the viewport up by 16 units and use the shift amount
  in the shader (uniform g_Offset), to finally get the correct sampling coordinates
  
  
  note: shift amount is not hardcoded, but fetched from glGetIntegerv(GL_VIEWPORT)
  */

  
  GLint old_viewport[4];
  glGetIntegerv(GL_VIEWPORT, old_viewport);
  glViewport(0, 0, pViewer->glWidth_, pViewer->glHeight_);

  for (int i = 0; i < 6; ++i)
  {
    ACG::GLState::activeTexture(GL_TEXTURE0 + i);
1346
    ACG::GLState::bindTexture(GL_TEXTURE_RECTANGLE_EXT, 0);
Jan Möbius's avatar
 
Jan Möbius committed
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
  }
  

  // ---------------------------------------------------------------------
  // 1. Initialize Min-Max Depth Buffer
  // ---------------------------------------------------------------------

  ACG::GLState::bindFramebuffer(GL_FRAMEBUFFER_EXT, pViewer->blendDualPeelFbo_);

  // Render targets 1 and 2 store the front and back colors
  // Clear to 0.0 and use MAX blending to filter written color
  // At most one front color and one back color can be written every pass
  ACG::GLState::drawBuffers(2, &drawBuffers[1]);
  glClearColor(0, 0, 0, 0);
  glClear(GL_COLOR_BUFFER_BIT);

  // Render target 0 stores (-minDepth, maxDepth, alphaMultiplier)
  ACG::GLState::drawBuffer(drawBuffers[0]);
  glClearColor(-maxDepth, -maxDepth, 0, 0);
  glClear(GL_COLOR_BUFFER_BIT);
  ACG::GLState::blendEquation(GL_MAX_EXT);
  ACG::GLState::lockBlendEquation();

  blendDualPeelProg_[0]->use();
  ACG::GLState::lockProgram();
1372
  drawScenePass(_glState, _properties.drawMode(), sceneGraphRoot);
Jan Möbius's avatar
 
Jan Möbius committed
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
  ACG::GLState::unlockProgram();



  int currId = 0;

  // ---------------------------------------------------------------------
  // 2. Dual Depth Peeling + Blending
  // ---------------------------------------------------------------------

  // Since we cannot blend the back colors in the geometry passes,
  // we use another render target to do the alpha blending
  //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, g_dualBackBlenderFboId);
  ACG::GLState::drawBuffer(drawBuffers[6]);
  glClearColor(_glState->clear_color()[0], _glState->clear_color()[1], _glState->clear_color()[2], 0);

  glClear(GL_COLOR_BUFFER_BIT);

  // Geometry layers are peeled until the sample query returns 0
  GLuint sampleCount = 1;
  for (int pass = 1; sampleCount; ++pass)
  {
    currId = pass % 2;
    int prevId = 1 - currId;
    int bufId = currId * 3;

    ACG::GLState::drawBuffers(2, &drawBuffers[bufId+1]);
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

    ACG::GLState::drawBuffer(drawBuffers[bufId+0]);
    glClearColor(-maxDepth, -maxDepth, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

    // Render target 0: RG32F MAX blending
    // Render target 1: RGBA MAX blending
    // Render target 2: RGBA MAX blending
    ACG::GLState::drawBuffers(3, &drawBuffers[bufId+0]);
    ACG::GLState::unlockBlendEquation();
    ACG::GLState::blendEquation(GL_MAX_EXT);
    ACG::GLState::lockBlendEquation();

    ACG::GLState::activeTexture(GL_TEXTURE5); // front_blender_tex  base_offset: 2
1416
    ACG::GLState::bindTexture(GL_TEXTURE_RECTANGLE_EXT, pViewer->blendDualPeelTexID_[2 + prevId]);
Jan Möbius's avatar
 
Jan Möbius committed
1417
1418

    ACG::GLState::activeTexture(GL_TEXTURE4); // depth_tex  base_offset: 0
1419
    ACG::GLState::bindTexture(GL_TEXTURE_RECTANGLE_EXT, pViewer->blendDualPeelTexID_[0 + prevId]);
Jan Möbius's avatar
Jan Möbius committed
1420

Jan Möbius's avatar
 
Jan Möbius committed
1421
1422

    // scene geometry peeling pass
1423
    //  note that the peel shader is set right before rendering in the traverser, based on a node's drawmode
Jan Möbius's avatar
 
Jan Möbius committed
1424
1425
1426
1427
    ACG::GLState::activeTexture(GL_TEXTURE0);

    ACG::GLState::shadeModel(GL_SMOOTH); // flat shading is emulated in Geometry Shader, which only works with interpolated vertex shader output
    ACG::GLState::lockShadeModel();
1428
    drawScenePeelPass(_glState, _properties.drawMode(), sceneGraphRoot, pass);
Jan Möbius's avatar
 
Jan Möbius committed
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
    ACG::GLState::unlockShadeModel();


    // Full screen pass to alpha-blend the back color
    ACG::GLState::drawBuffer(drawBuffers[6]);

    ACG::GLState::unlockBlendEquation();
    ACG::GLState::blendEquation(GL_FUNC_ADD);
    ACG::GLState::lockBlendEquation();
    ACG::GLState::blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // start samples counter query
    glBeginQuery(GL_SAMPLES_PASSED_ARB, blendQueryID_);

    blendDualPeelProg_[2]->use();
    blendDualPeelProg_[2]->setUniform("TempTex", 4);

    ACG::GLState::activeTexture(GL_TEXTURE4); // back_temp_tex  base_offset: 4
1447
    ACG::GLState::bindTexture(GL_TEXTURE_RECTANGLE_EXT, pViewer->blendDualPeelTexID_[4 + currId]);
Jan Möbius's avatar
 
Jan Möbius committed
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467

    drawQuadProj(); // full screen quad, already projected

    glEndQuery(GL_SAMPLES_PASSED_ARB);
    glGetQueryObjectuiv(blendQueryID_, GL_QUERY_RESULT_ARB, &sampleCount);
  }

  ACG::GLState::unlockBlendEquation();

  ACG::GLState::unlockState(GL_BLEND);
  ACG::GLState::disable(GL_BLEND);



  // ---------------------------------------------------------------------
  // 3. Final Pass
  //  operates on screen pixels only
  // ---------------------------------------------------------------------

  // enable back buffer
1468
  ACG::GLState::bindFramebuffer(GL_FRAMEBUFFER_EXT, targetFbo);
Jan Möbius's avatar
 
Jan Möbius committed
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
  ACG::GLState::drawBuffer(GL_BACK);

  // program id 3
  blendDualPeelProg_[3]->use();
  blendDualPeelProg_[3]->setUniform("FrontBlenderTex", 4);
  blendDualPeelProg_[3]->setUniform("BackBlenderTex", 5);

  // bugfix for multiple viewports:
  //  gl_FragCoord represents the screen space coordinate of a pixel into the back buffer
  //  this has to be back-shifted by the upper left viewport coordinate to get correct texture coordinates
  blendDualPeelProg_[3]->setUniform("ViewportOffset", ACG::Vec2f(old_viewport[0], old_viewport[1]));

  ACG::GLState::activeTexture(GL_TEXTURE5); // back_blender:  offset 6
1482
  ACG::GLState::bindTexture(GL_TEXTURE_RECTANGLE_EXT, pViewer->blendDualPeelTexID_[6]);
Jan Möbius's avatar
Jan Möbius committed
1483

Jan Möbius's avatar
 
Jan Möbius committed
1484
1485

  ACG::GLState::activeTexture(GL_TEXTURE4); // front_blender_tex  base_offset: 2
1486
  ACG::GLState::bindTexture(GL_TEXTURE_RECTANGLE_EXT, pViewer->blendDualPeelTexID_[2 + currId]);
Jan Möbius's avatar
 
Jan Möbius committed
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
1513
1514

  
  glViewport(old_viewport[0], old_viewport[1], old_viewport[2], old_viewport[3]);
  drawQuadProj(-1.0f, 1.0f, 2.0f, 2.0f);


  blendDualPeelProg_[3]->disable();



  ACG::glCheckErrors();


  // unlock states
  ACG::GLState::unlockDepthFunc();
  ACG::GLState::unlockState(GL_CULL_FACE);
  ACG::GLState::unlockState(GL_LIGHTING);
  ACG::GLState::unlockState(GL_NORMALIZE);

  ACG::GLState::unlockState(GL_DEPTH_TEST);
  ACG::GLState::unlockState(GL_BLEND);


  glPopAttrib();
}

Q_EXPORT_PLUGIN2( depthpeelingplugin , DepthPeelingPlugin );