vtkDualDepthPeelingPass.cxx 67.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDualDepthPeelingPass.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkDualDepthPeelingPass.h"

18
#include "vtkOpenGLFramebufferObject.h"
19 20 21 22 23 24 25
#include "vtkInformation.h"
#include "vtkInformationKey.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLActor.h"
#include "vtkOpenGLBufferObject.h"
#include "vtkOpenGLError.h"
26
#include "vtkOpenGLRenderUtilities.h"
27 28 29 30 31
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLVertexArrayObject.h"
#include "vtkRenderer.h"
#include "vtkRenderState.h"
32
#include "vtkRenderTimerLog.h"
33 34 35 36 37 38 39 40
#include "vtkShaderProgram.h"
#include "vtkTextureObject.h"
#include "vtkTypeTraits.h"

#include <algorithm>

// Define to print debug statements to the OpenGL CS stream (useful for e.g.
// apitrace debugging):
41
//#define ANNOTATE_STREAM
42 43 44 45 46 47 48

// Define to output details about each peel:
//#define DEBUG_PEEL

// Define to output details about each frame:
//#define DEBUG_FRAME

49 50 51 52 53 54 55
// Define to render the categorization of the initial volume-prepass pixel:
// - Pixels with no opaque or translucent geometry will be red.
// - Pixels with only opaque geometry will be green.
// - Pixels with only translucent geometry will be blue.
// - Pixels with both opaque and translucent geometry will be purple.
//#define DEBUG_VOLUME_PREPASS_PIXELS

56 57 58 59 60 61 62 63 64 65
// Recent OSX/ATI drivers perform some out-of-order execution that's causing
// the dFdx/dFdy calls to be conditionally executed. Specifically, it looks
// like the early returns when the depth is not on a current peel layer
// (Peeling pass, VTK::PreColor::Impl hook) are moved before the dFdx/dFdy
// calls used to compute normals. Disable the early returns on apple for now, I
// don't think most GPUs really benefit from them anyway at this point.
#ifdef __APPLE__
#define NO_PRECOLOR_EARLY_RETURN
#endif

66 67 68 69 70
using RenderEvent = vtkRenderTimerLog::ScopedEventLogger;

#define TIME_FUNCTION(functionName) \
  VTK_SCOPED_RENDER_EVENT(#functionName, this->Timer);

71
vtkStandardNewMacro(vtkDualDepthPeelingPass)
72
vtkCxxSetObjectMacro(vtkDualDepthPeelingPass, VolumetricPass, vtkRenderPass)
73 74 75 76 77 78

namespace
{
void annotate(const std::string &str)
{
#ifdef ANNOTATE_STREAM
79
  vtkOpenGLRenderUtilities::MarkDebugEvent(str);
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
#else // ANNOTATE_STREAM
  (void)str;
#endif // ANNOTATE_STREAM
}
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::PrintSelf(std::ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Render(const vtkRenderState *s)
{
95 96 97
  VTK_SCOPED_RENDER_EVENT("vtkDualDepthPeelingPass::Render",
                          s->GetRenderer()->GetRenderWindow()->GetRenderTimer());

98 99 100 101 102 103
  // Setup vtkOpenGLRenderPass
  this->PreRender(s);

  this->Initialize(s);
  this->Prepare();

104 105 106 107 108
  if (this->IsRenderingVolumes())
  {
    this->PeelVolumesOutsideTranslucentRange();
  }

109
#ifndef DEBUG_VOLUME_PREPASS_PIXELS
110
  while (!this->PeelingDone())
111
  {
112
    this->Peel();
113
  }
114
#endif // DEBUG_VOLUME_PREPASS_PIXELS
115 116 117 118 119 120 121

  this->Finalize();

  this->PostRender(s);
}

//------------------------------------------------------------------------------
122
void vtkDualDepthPeelingPass::ReleaseGraphicsResources(vtkWindow* win)
123
{
124 125 126 127 128
  if (this->VolumetricPass)
  {
    this->VolumetricPass->ReleaseGraphicsResources(win);
  }

129 130 131
  this->FreeGLObjects();
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::PreReplaceShaderValues(
    std::string &vertexShader,
    std::string &geometryShader,
    std::string &fragmentShader,
    vtkAbstractMapper *mapper,
    vtkProp *prop)
{
  switch (this->CurrentPeelType)
  {
    case vtkDualDepthPeelingPass::TranslucentPeel:
      // Do nothing -- these are handled in the post-replacements.
      return true;
    case vtkDualDepthPeelingPass::VolumetricPeel:
      // Forward to volumetric implementation:
      return this->PreReplaceVolumetricShaderValues(vertexShader,
                                                    geometryShader,
                                                    fragmentShader,
                                                    mapper, prop);
    default:
      break;
  }
  return false;
}

157
//------------------------------------------------------------------------------
Ken Martin's avatar
Ken Martin committed
158
bool vtkDualDepthPeelingPass::PostReplaceShaderValues(
159 160
  std::string &vertexShader,
  std::string &geometryShader,
Ken Martin's avatar
Ken Martin committed
161
  std::string &fragmentShader,
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  vtkAbstractMapper *mapper,
  vtkProp *prop)
{
  switch (this->CurrentPeelType)
  {
    case vtkDualDepthPeelingPass::TranslucentPeel:
      // Forward to translucent implementation:
      return this->PostReplaceTranslucentShaderValues(vertexShader,
                                                      geometryShader,
                                                      fragmentShader,
                                                      mapper, prop);
    case vtkDualDepthPeelingPass::VolumetricPeel:
      // Do nothing; these are handled in the pre-replacements.
      return true;

    default:
      break;
  }
  return false;
}

//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::SetShaderParameters(vtkShaderProgram *program,
                                   vtkAbstractMapper *mapper, vtkProp *prop,
                                   vtkOpenGLVertexArrayObject *VAO)
{
  switch (this->CurrentPeelType)
  {
    case vtkDualDepthPeelingPass::TranslucentPeel:
      return this->SetTranslucentShaderParameters(program, mapper, prop, VAO);
    case vtkDualDepthPeelingPass::VolumetricPeel:
      return this->SetVolumetricShaderParameters(program, mapper, prop, VAO);
    default:
      break;
  }
  return false;
}

//------------------------------------------------------------------------------
vtkMTimeType vtkDualDepthPeelingPass::GetShaderStageMTime()
{
  return this->CurrentStageTimeStamp.GetMTime();
}

//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::PostReplaceTranslucentShaderValues(
    std::string &, std::string &, std::string &fragmentShader,
    vtkAbstractMapper *, vtkProp *)
210 211
{
  switch (this->CurrentStage)
212
  {
213
    case vtkDualDepthPeelingPass::InitializingDepth:
214 215 216 217 218 219
      // Set gl_FragDepth if it isn't set already. It may have already been
      // replaced by the mapper, in which case the substitution will fail and
      // the previously set depth value will be used.
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::Depth::Impl",
            "gl_FragDepth = gl_FragCoord.z;");
220 221 222 223 224 225 226
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D opaqueDepth;\n");
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::PreColor",
            "ivec2 pixel = ivec2(gl_FragCoord.xy);\n"
            "  float oDepth = texelFetch(opaqueDepth, pixel, 0).y;\n"
227
            "  if (oDepth != -1. && gl_FragDepth > oDepth)\n"
228 229 230 231
            "    { // Ignore fragments that are occluded by opaque geometry:\n"
            "    gl_FragData[1].xy = vec2(-1., oDepth);\n"
            "    return;\n"
            "    }\n"
232
            "  else\n"
233
            "    {\n"
234
            "    gl_FragData[1].xy = vec2(-gl_FragDepth, gl_FragDepth);\n"
235 236 237 238 239 240
            "    return;\n"
            "    }\n"
            );
      break;

    case vtkDualDepthPeelingPass::Peeling:
241 242 243 244 245 246
      // Set gl_FragDepth if it isn't set already. It may have already been
      // replaced by the mapper, in which case the substitution will fail and
      // the previously set depth value will be used.
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::Depth::Impl",
            "gl_FragDepth = gl_FragCoord.z;");
247 248 249 250 251 252 253 254 255 256 257
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D lastFrontPeel;\n"
            "uniform sampler2D lastDepthPeel;\n");
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::PreColor",
            "  ivec2 pixelCoord = ivec2(gl_FragCoord.xy);\n"
            "  vec4 front = texelFetch(lastFrontPeel, pixelCoord, 0);\n"
            "  vec2 minMaxDepth = texelFetch(lastDepthPeel, pixelCoord, 0).xy;\n"
            "  float minDepth = -minMaxDepth.x;\n"
            "  float maxDepth = minMaxDepth.y;\n"
258 259 260 261 262 263
            "  // Use a tolerance when checking if we're on a current peel.\n"
            "  // Some OSX drivers compute slightly different fragment depths\n"
            "  // from one pass to the next. This value was determined\n"
            "  // through trial-and-error -- it may need to be increased at\n"
            "  // some point. See also the comment in vtkDepthPeelingPass's\n"
            "  // shader.\n"
264
            "  float epsilon = 0.0000001;\n"
265 266 267 268 269 270 271
            "\n"
            "  // Default outputs (no data/change):\n"
            "  gl_FragData[0] = vec4(0.);\n"
            "  gl_FragData[1] = front;\n"
            "  gl_FragData[2].xy = vec2(-1.);\n"
            "\n"
            "  // Is this fragment outside the current peels?\n"
272 273
            "  if (gl_FragDepth < minDepth - epsilon ||\n"
            "      gl_FragDepth > maxDepth + epsilon)\n"
274
            "    {\n"
275
#ifndef NO_PRECOLOR_EARLY_RETURN
276
            "    return;\n"
277 278 279 280 281
#else
            "    // Early return removed to avoid instruction-reordering bug\n"
            "    // with dFdx/dFdy on OSX drivers.\n"
            "    // return;\n"
#endif
282 283 284
            "    }\n"
            "\n"
            "  // Is this fragment inside the current peels?\n"
285 286
            "  if (gl_FragDepth > minDepth + epsilon &&\n"
            "      gl_FragDepth < maxDepth - epsilon)\n"
287 288
            "    {\n"
            "    // Write out depth so this frag will be peeled later:\n"
289
            "    gl_FragData[2].xy = vec2(-gl_FragDepth, gl_FragDepth);\n"
290
#ifndef NO_PRECOLOR_EARLY_RETURN
291
            "    return;\n"
292 293 294 295 296
#else
            "    // Early return removed to avoid instruction-reordering bug\n"
            "    // with dFdx/dFdy on OSX drivers.\n"
            "    // return;\n"
#endif
297 298 299 300 301 302 303 304 305 306
            "    }\n"
            "\n"
            "  // Continue processing for fragments on the current peel:\n"
            );
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Impl",
            "vec4 frag = gl_FragData[0];\n"
            "  // Default outputs (no data/change):\n"
            "\n"
            "  // This fragment is on a current peel:\n"
307 308
            "  if (gl_FragDepth >= minDepth - epsilon &&\n"
            "      gl_FragDepth <= minDepth + epsilon)\n"
309 310 311 312 313 314 315 316 317 318 319 320 321 322
            "    { // Front peel:\n"
            "    // Clear the back color:\n"
            "    gl_FragData[0] = vec4(0.);\n"
            "\n"
            "    // We store the front alpha value as (1-alpha) to allow MAX\n"
            "    // blending. This also means it is really initialized to 1,\n"
            "    // as it should be for under-blending.\n"
            "    front.a = 1. - front.a;\n"
            "\n"
            "    // Use under-blending to combine fragment with front color:\n"
            "    gl_FragData[1].rgb = front.a * frag.a * frag.rgb + front.rgb;\n"
            "    // Write out (1-alpha):\n"
            "    gl_FragData[1].a = 1. - (front.a * (1. - frag.a));\n"
            "    }\n"
323 324
#ifndef NO_PRECOLOR_EARLY_RETURN
            // just 'else' is ok. We'd return earlier in this case.
325
            "  else // (gl_FragDepth == maxDepth)\n"
326 327 328 329 330 331
#else
            // Need to explicitly test if this is the back peel, since early
            // returns are removed.
            "  else if (gl_FragDepth >= maxDepth - epsilon &&\n"
            "           gl_FragDepth <= maxDepth + epsilon)\n"
#endif
332 333 334 335 336
            "    { // Back peel:\n"
            "    // Dump premultiplied fragment, it will be blended later:\n"
            "    frag.rgb *= frag.a;\n"
            "    gl_FragData[0] = frag;\n"
            "    }\n"
337 338 339 340 341 342 343 344 345
#ifdef NO_PRECOLOR_EARLY_RETURN
            // Since the color outputs now get clobbered without the early
            // returns, reset them here.
            "  else\n"
            "    { // Need to clear the colors if not on a current peel.\n"
            "    gl_FragData[0] = vec4(0.);\n"
            "    gl_FragData[1] = front;\n"
            "    }\n"
#endif
346 347 348 349
            );
      break;

    case vtkDualDepthPeelingPass::AlphaBlending:
350 351 352 353 354 355
      // Set gl_FragDepth if it isn't set already. It may have already been
      // replaced by the mapper, in which case the substitution will fail and
      // the previously set depth value will be used.
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::Depth::Impl",
            "gl_FragDepth = gl_FragCoord.z;");
356 357 358 359 360 361 362 363 364 365 366
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D lastDepthPeel;\n");
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::PreColor",
            "  ivec2 pixelCoord = ivec2(gl_FragCoord.xy);\n"
            "  vec2 minMaxDepth = texelFetch(lastDepthPeel, pixelCoord, 0).xy;\n"
            "  float minDepth = -minMaxDepth.x;\n"
            "  float maxDepth = minMaxDepth.y;\n"
            "\n"
            "  // Discard all fragments outside of the last set of peels:\n"
367
            "  if (gl_FragDepth < minDepth || gl_FragDepth > maxDepth)\n"
368 369 370 371 372 373 374 375 376 377 378 379 380 381
            "    {\n"
            "    discard;\n"
            "    }\n"
            );
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Impl",
            "\n"
            "  // Pre-multiply alpha for depth peeling:\n"
            "  gl_FragData[0].rgb *= gl_FragData[0].a;\n"
            );
      break;

    default:
      break;
382
  }
383 384 385 386 387

  return true;
}

//------------------------------------------------------------------------------
388 389 390 391
bool vtkDualDepthPeelingPass::PreReplaceVolumetricShaderValues(
    std::string &, std::string &, std::string &fragmentShader,
    vtkAbstractMapper *, vtkProp *)
{
392 393
  const std::string rayInit =
    "  // Transform zStart and zEnd to texture_coordinates\n"
394
    "  mat4 NDCToTextureCoords = ip_inverseTextureDataAdjusted * in_inverseVolumeMatrix[0] *\n"
395 396 397 398 399 400
    "    in_inverseModelViewMatrix * in_inverseProjectionMatrix;\n"
    "  \n"
    "  // Start point\n"
    "  vec4 startPoint = WindowToNDC(gl_FragCoord.x, gl_FragCoord.y, zStart);\n"
    "  startPoint = NDCToTextureCoords * startPoint;\n"
    "  startPoint /= startPoint.w;\n"
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

    // startPoint could be located outside of the bounding box (bbox), this
    // is the case in:
    // 1. PeelVolumesOutside: Areas external to any geometry.
    // 2. PeelVolumetricGeometry: Areas where the volume is contained within
    // translucent geometry but the containing geometry lies outside of the bbox
    // (startPoint is either in-front or behind the bbox depending on the viewpoint).
    //
    // Given that startPoint could be located either in-front, inside or behind the\n"
    // bbox (the ray exit is unknown hence it is not possible to use clamp() directly),\n"
    // the clamp is divided in these three zones:\n"
    // a. In-front: clamp to ip_textureCoords (bbox's texture coord).\n"
    // b. Inside: use startPoint directly as it is peeling within the bbox.\n"
    // c. Behind: discard by returning vec4(0.f).\n"

416 417 418
    "\n"
    "  // Initialize g_dataPos as if startPoint lies Inside (b.)\n"
    "  g_dataPos = startPoint.xyz;\n"
419 420
    "  bool isInsideBBox = !(any(greaterThan(startPoint.xyz, in_texMax[0])) ||\n"
    "    any(lessThan(startPoint.xyz, in_texMin[0])));\n"
421 422 423 424 425
    "  if (!isInsideBBox)\n"
    "  {\n"
    "    vec3 distStartTexCoord = ip_textureCoords.xyz - startPoint.xyz;\n"
    "    if (dot(distStartTexCoord, g_dirStep) < 0)\n"
    "    {\n"
426 427
    "      // startPoint lies behind the bounding box (c.)\n"
    "      return vec4(0.0);\n"
428 429 430 431
    "    }\n"
    "    // startPoint lies in-front (a.)\n"
    "    g_dataPos = ip_textureCoords.xyz;\n"
    "  }\n"
432
    "  g_dataPos += g_rayJitter;\n"
433 434 435 436 437 438 439 440
    "  \n"
    "  // End point\n"
    "  vec4 endPoint = WindowToNDC(gl_FragCoord.x, gl_FragCoord.y, zEnd);\n"
    "  endPoint = NDCToTextureCoords * endPoint;\n"
    "  endPoint /= endPoint.w;\n"
    "\n"
    "  // Compute the number of steps and reinitialize the step counter.\n"
    "  g_terminatePointMax = length(endPoint.xyz - g_dataPos.xyz) / length(g_dirStep);\n"
441 442
    "  g_currentT = 0.0;\n"
    "  g_fragColor = vec4(0.0);\n"
443 444
    "\n";

445 446 447
  switch (this->CurrentStage)
  {
    case vtkDualDepthPeelingPass::InitializingDepth:
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
      // At this point, both CopyOpaqueDepthBuffer and InitializeDepth have run.
      //
      // DepthSource (inner) has either:
      // a. Same as outer/DepthDestination, or
      // b. (-transGeoDepthMin, transGeoDepthMax)
      // (a) if no transparent geo in front of opaque, (b) otherwise.
      //
      // DepthDestination (outer) has (-1, opaqueDepth), or (-1, -1) if no
      // opaque geometry.
      //
      // All color buffers are empty, so we can draw directly to them. No input
      // passthrough or blending needed.
      //
      // We'll check both of the depth buffers:
      //
      // 1) If the inner.y < 0, there is no geometry here. Render volume from
      //    0 --> 1 into the back buffer.
      // 2) If the outer.x == -1 and inner.y < 0, we have only opaque geometry
      //    here. Render volumes from 0 --> outer.y into the back buffer.
      // 3) If the 'max' depth differs between the buffers, then peel:
      //    0 --> -inner.x into front buffer
      //    inner.y --> outer.y into back buffer. If outer.y < 0, replace with 1

471 472 473 474 475 476
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::Termination::Init",
            "// Termination is defined somewhere else within the pass (CallWorker::Impl \n "
            "// and Ray::Init), so this tag is substituted for an empty implementation\n"
            "// to avoid unnecessary code.\n");

477 478 479 480 481 482 483
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D outerDepthTex;\n"
            "uniform sampler2D innerDepthTex;\n"
            );
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::CallWorker::Impl",
484 485 486
            "  vec2 pixelCoord = vec2(gl_FragCoord.x, gl_FragCoord.y);\n"
            "  vec2 inner = texture2D(innerDepthTex, pixelCoord * in_inverseWindowSize).xy;\n"
            "  vec2 outer = texture2D(outerDepthTex, pixelCoord * in_inverseWindowSize).xy;\n"
487 488 489 490 491 492 493 494 495 496 497
            "\n"
            "  initializeRayCast();\n"
            "  vec4 front = vec4(0.f);\n"
            "  vec4 back = vec4(0.f);\n"
            "\n"
            "  // Check for the presence of opaque/trans geometry:\n"
            "  bool hasOpaqueGeometry = outer.y >= 0.f;\n"
            "  bool hasTranslucentGeometry = inner.x != -1.f;\n"
            "  bool hasAnyGeometry = hasOpaqueGeometry ||\n"
            "                        hasTranslucentGeometry;\n"
            "\n"
498 499 500 501 502
#ifndef DEBUG_VOLUME_PREPASS_PIXELS
            "  vec2 frontRange = vec2(1.f, -1.f);\n"
            "  vec2 backRange = vec2(1.f, -1.f);\n"
            "\n"
#endif // not DEBUG_VOLUME_PREPASS_PIXELS
503 504 505
            "  if (!hasAnyGeometry)\n"
            "  { // No opaque or translucent geometry\n"
#ifndef DEBUG_VOLUME_PREPASS_PIXELS
506
            "    backRange = vec2(0., 1.);\n"
507 508 509 510 511 512 513 514
#else // not DEBUG_VOLUME_PREPASS_PIXELS
            "    back = vec4(1.f, 0.f, 0.f, 1.f);\n"
#endif // not DEBUG_VOLUME_PREPASS_PIXELS
            "  }\n"
            "  else if (!hasTranslucentGeometry)\n"
            "  { // Opaque geometry only.\n"
#ifndef DEBUG_VOLUME_PREPASS_PIXELS
            "    float opaqueDepth = inner.y;\n"
515
            "    backRange = vec2(0.f, opaqueDepth);\n"
516 517 518 519 520 521 522 523
#else // not DEBUG_VOLUME_PREPASS_PIXELS
            "    back = vec4(0.f, 1.f, 0.f, 1.f);\n"
#endif // not DEBUG_VOLUME_PREPASS_PIXELS
            "  }\n"
            "  else // translucent geometry, maybe opaque, too:\n"
            "  {\n"
#ifndef DEBUG_VOLUME_PREPASS_PIXELS
            "    float opaqueDepth = hasOpaqueGeometry ? outer.y : 1.f;\n"
524
            "    frontRange = vec2(0.f, -inner.x);\n"
525 526 527
            "\n"
            "    if (front.a < g_opacityThreshold)\n"
            "    {\n"
528 529
            "      // The color returned by castRay() has alpha pre-multiplied,\n"
            "      // as required for back-blending.\n"
530
            "      backRange = vec2(inner.y, opaqueDepth);\n"
531 532
            "    }\n"
            "\n"
533 534 535 536 537 538
#else // not DEBUG_VOLUME_PREPASS_PIXELS
            "    float blue = hasOpaqueGeometry ? 1.f : 0.f;\n"
            "    back = vec4(blue, 0.f, 1.f, 1.f);\n"
#endif // not DEBUG_VOLUME_PREPASS_PIXELS
            "  }\n"
            "\n"
539 540 541 542 543 544 545 546 547 548 549
#ifndef DEBUG_VOLUME_PREPASS_PIXELS
            "  if (frontRange.x < frontRange.y)\n"
            "  {\n"
            "    front = castRay(frontRange.x, frontRange.y);\n"
            "  }\n"
            "  if (backRange.x < backRange.y)\n"
            "  {\n"
            "    back = castRay(backRange.x, backRange.y);\n"
            "  }\n"
            "\n"
#endif // not DEBUG_VOLUME_PREPASS_PIXELS
550 551 552 553
            "  gl_FragData[0] = back;\n"
            "  gl_FragData[1] = front;\n"
            );

554 555 556 557 558 559 560 561 562
      vtkShaderProgram::Substitute(fragmentShader,
            "//VTK::DepthPeeling::Ray::Init", rayInit);

      vtkShaderProgram::Substitute(fragmentShader, "//VTK::DepthPeeling::Ray::PathCheck",
            "  // Ensure end is not located before start. This could be the case\n"
            "  // if end lies outside of the volume's bounding box. In those cases\n"
            "  // a transparent color is returned.\n"
            "  vec3 rgrif = endPoint.xyz - g_dataPos.xyz;\n"
            "  if (dot(rgrif, g_dirStep) < 0)\n"
563
            "  {\n"
564
            "    return vec4(0.f);\n"
565 566 567 568
            "  }\n"
            );

      return true;
569 570 571 572 573 574 575

    case vtkDualDepthPeelingPass::Peeling:
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D outerDepthTex;\n"
            "uniform sampler2D innerDepthTex;\n"
            "uniform sampler2D lastFrontColorTex;\n"
576
            "uniform sampler2D opaqueDepthTex;\n"
577 578 579
            );
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::CallWorker::Impl",
580 581 582 583
            "  vec2 pixelCoord = vec2(gl_FragCoord.x, gl_FragCoord.y);\n"
            "  vec2 innerDepths = texture2D(innerDepthTex, pixelCoord * in_inverseWindowSize).xy;\n"
            "  vec2 outerDepths = texture2D(outerDepthTex, pixelCoord * in_inverseWindowSize).xy;\n"
            "  vec4 lastFrontColor = texture2D(lastFrontColorTex, pixelCoord * in_inverseWindowSize);\n"
584
            "\n"
585 586 587 588 589 590
            "  // Discard processed fragments\n"
            "  if (outerDepths.x == -1)\n"
            "  {\n"
            "    discard;\n"
            "  }\n"
            "\n"
591 592 593
            "  // Negate the near depths; they're negative for MAX blending:\n"
            "  float frontStartDepth = -outerDepths.x;\n"
            "  float frontEndDepth   = -innerDepths.x;\n"
594 595
            "  float backStartDepth  = innerDepths.y;\n"
            "  float backEndDepth    = outerDepths.y;\n"
596
            "\n"
597 598 599 600
            "  // Only record the back color (for occlusion queries) if the\n"
            "  // front/back ranges are the same:\n"
            "  bool onlyBack = frontStartDepth == backStartDepth &&\n"
            "                  frontEndDepth == backEndDepth;\n"
601
            "\n"
602 603 604 605 606 607 608 609

            // In the last peel, innerDepths may be (-1, -1) for most of the
            // fragments. Casting a ray from [outerDepths.x, 1.0] would result
            // in accumulating areas that have already been accounted for in
            // former volume peels.  In this case frontEndDepth should be the
            // outer max instead. Because of this, the back castRay() is also
            // skipped.

610 611 612 613 614 615
            "  bool noInnerDepths = innerDepths.x == -1.0;\n"
            "  if (noInnerDepths)\n"
            "  {\n"
            "    frontEndDepth = outerDepths.y;\n"
            "  }\n"
            "\n"
616 617 618 619 620 621 622

            // Peel passes set -1 in pixels that contain only opaque geometry,
            // so the opaque depth is fetched in order to z-composite volumes
            // with opaque goemetry. To do this, the end point of front is clamped
            // to opaque-depth and back ray-cast is skipped altogether since it
            // would be covered by opaque geometry anyway.

623
            "  float oDepth = texture2D(opaqueDepthTex, pixelCoord * in_inverseWindowSize).x;\n"
624 625 626 627 628 629 630
            "  bool endBehindOpaque = frontEndDepth >= oDepth;\n"
            "  float clampedFrontEnd = frontEndDepth;\n"
            "  if (endBehindOpaque)\n"
            "  {\n"
            "    clampedFrontEnd = clamp(frontEndDepth, oDepth, oDepth);\n"
            "  }\n"
            "  \n"
631
            "  initializeRayCast();\n"
632 633 634
            "  vec4 frontColor = vec4(0.f);\n"
            "  if (!onlyBack)\n"
            "  {\n"
635 636 637 638 639
            "    frontColor = castRay(frontStartDepth,\n"
            "                         clampedFrontEnd);\n"
            "  }\n"
            "\n"
            "  vec4 backColor = vec4(0.);\n"
640
            "  if (!endBehindOpaque && !noInnerDepths)"
641 642 643
            "  {\n"
            "    backColor = castRay(backStartDepth,\n"
            "                        backEndDepth);\n"
644
            "  }\n"
645
            "\n"
646 647 648
            "  // The color returned by castRay() has alpha pre-multiplied,\n"
            "  // as required for back-blending.\n"
            "  gl_FragData[0] = backColor;\n"
649 650 651 652 653
            "\n"
            "  // Front color is written with negated alpha for MAX blending:\n"
            "  lastFrontColor.a = 1. - lastFrontColor.a;\n"
            "\n"
            "  // Use under-blending to mix the front color on-the-fly:\n"
654 655
            "  // (note that frontColor.rgb is already multiplied by its\n"
            "  // alpha, this is done within castRay())\n"
656
            "  gl_FragData[1].rgb =\n"
657
            "    lastFrontColor.a * frontColor.rgb + lastFrontColor.rgb;\n"
658 659 660 661
            "\n"
            "  // Write out (1-alpha) for MAX blending:\n"
            "  gl_FragData[1].a = 1. - (lastFrontColor.a * (1. - frontColor.a));\n"
            );
662

663 664
      vtkShaderProgram::Substitute(fragmentShader,
            "//VTK::DepthPeeling::Ray::Init", rayInit);
665

666 667 668 669 670 671 672 673
      break;

    case vtkDualDepthPeelingPass::AlphaBlending:
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::DepthPeeling::Dec",
            "uniform sampler2D depthRangeTex;\n");
      vtkShaderProgram::Substitute(
            fragmentShader, "//VTK::CallWorker::Impl",
674 675
            "  vec2 pixelCoord = vec2(gl_FragCoord.x, gl_FragCoord.y);\n"
            "  vec2 depthRange = texture2D(depthRangeTex, pixelCoord * in_inverseWindowSize).xy;\n"
676 677
            "\n"
            "  // Discard processed fragments\n"
678
            "  if (depthRange.x == -1.0)\n"
679 680 681 682
            "  {\n"
            "    discard;\n"
            "  }\n"
            "\n"
683 684 685
            "  float startDepth = -depthRange.x;\n"
            "  float endDepth = depthRange.y;\n"
            "\n"
686
            "  initializeRayCast();\n"
687
            "  vec4 color = castRay(startDepth, endDepth);\n"
688
            "\n"
689 690 691
            "  // The color returned by castRay() has alpha pre-multiplied,\n"
            "  // as required for back-blending.\n"
            "  gl_FragData[0] = color;\n"
692 693 694 695 696 697 698 699 700 701 702 703 704 705
            );
      break;

    default:
      break;
  }

  return true;
}

//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::SetTranslucentShaderParameters(
    vtkShaderProgram *program, vtkAbstractMapper *, vtkProp *,
    vtkOpenGLVertexArrayObject *)
706 707
{
  switch (this->CurrentStage)
708
  {
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    case vtkDualDepthPeelingPass::InitializingDepth:
      program->SetUniformi(
            "opaqueDepth",
            this->Textures[this->DepthDestination]->GetTextureUnit());
      break;

    case vtkDualDepthPeelingPass::Peeling:
      program->SetUniformi(
            "lastDepthPeel",
            this->Textures[this->DepthSource]->GetTextureUnit());
      program->SetUniformi(
            "frontDepthPeel",
            this->Textures[this->FrontSource]->GetTextureUnit());
      break;

    case vtkDualDepthPeelingPass::AlphaBlending:
      program->SetUniformi(
            "lastDepthPeel",
            this->Textures[this->DepthSource]->GetTextureUnit());
      break;

    default:
      break;
732
  }
733 734 735 736 737

  return true;
}

//------------------------------------------------------------------------------
738 739 740
bool vtkDualDepthPeelingPass::SetVolumetricShaderParameters(
    vtkShaderProgram *program, vtkAbstractMapper *, vtkProp *,
    vtkOpenGLVertexArrayObject *)
741
{
742 743 744
  switch (this->CurrentStage)
  {
    case vtkDualDepthPeelingPass::InitializingDepth:
745 746 747 748 749 750 751
      program->SetUniformi(
            "outerDepthTex",
            this->Textures[this->DepthDestination]->GetTextureUnit());
      program->SetUniformi(
            "innerDepthTex",
            this->Textures[this->DepthSource]->GetTextureUnit());
      return true;
752 753 754 755 756 757 758 759 760 761 762

    case vtkDualDepthPeelingPass::Peeling:
      program->SetUniformi(
            "outerDepthTex",
            this->Textures[this->DepthSource]->GetTextureUnit());
      program->SetUniformi(
            "innerDepthTex",
            this->Textures[this->DepthDestination]->GetTextureUnit());
      program->SetUniformi(
            "lastFrontColorTex",
            this->Textures[this->FrontSource]->GetTextureUnit());
763 764
      program->SetUniformi(
            "opaqueDepthTex", this->Textures[OpaqueDepth]->GetTextureUnit());
765 766 767 768 769 770 771 772 773 774 775 776 777
      break;

    case vtkDualDepthPeelingPass::AlphaBlending:
      program->SetUniformi(
            "depthRangeTex",
            this->Textures[this->DepthSource]->GetTextureUnit());
      break;

    default:
      break;
  }

  return true;
778 779 780 781
}

//------------------------------------------------------------------------------
vtkDualDepthPeelingPass::vtkDualDepthPeelingPass()
782 783 784 785 786 787 788 789 790 791 792 793 794 795
  : VolumetricPass(nullptr),
    RenderState(nullptr),
    CopyColorProgram(nullptr),
    CopyColorVAO(nullptr),
    CopyColorVBO(nullptr),
    CopyDepthProgram(nullptr),
    CopyDepthVAO(nullptr),
    CopyDepthVBO(nullptr),
    BackBlendProgram(nullptr),
    BackBlendVAO(nullptr),
    BackBlendVBO(nullptr),
    BlendProgram(nullptr),
    BlendVAO(nullptr),
    BlendVBO(nullptr),
796 797 798 799 800
    FrontSource(FrontA),
    FrontDestination(FrontB),
    DepthSource(DepthA),
    DepthDestination(DepthB),
    CurrentStage(Inactive),
801 802
    CurrentPeelType(TranslucentPeel),
    LastPeelHadVolumes(false),
803
    CurrentPeel(0),
804 805 806 807
    TranslucentOcclusionQueryId(0),
    TranslucentWrittenPixels(0),
    VolumetricOcclusionQueryId(0),
    VolumetricWrittenPixels(0),
808
    OcclusionThreshold(0),
809 810
    TranslucentRenderCount(0),
    VolumetricRenderCount(0),
811 812
    SaveScissorTestState(false),
    CullFaceMode(0),
813 814
    CullFaceEnabled(false),
    DepthTestEnabled(true)
815 816
{
  std::fill(this->Textures, this->Textures + static_cast<int>(NumberOfTextures),
817
            static_cast<vtkTextureObject*>(nullptr));
818 819 820 821 822 823
}

//------------------------------------------------------------------------------
vtkDualDepthPeelingPass::~vtkDualDepthPeelingPass()
{
  this->FreeGLObjects();
824 825 826

  if (this->VolumetricPass)
  {
827
    this->SetVolumetricPass(nullptr);
828
  }
829 830 831 832 833 834
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::SetCurrentStage(ShaderStage stage)
{
  if (stage != this->CurrentStage)
835
  {
836 837
    this->CurrentStage = stage;
    this->CurrentStageTimeStamp.Modified();
838
  }
839 840 841 842 843 844 845 846
}

//------------------------------------------------------------------------------
// Delete the vtkObject subclass pointed at by ptr if it is set.
namespace {
template <typename T> void DeleteHelper(T *& ptr)
{
  if (ptr)
847
  {
848
    ptr->Delete();
849
    ptr = nullptr;
850
  }
851 852 853 854 855 856
}
} // end anon namespace

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::FreeGLObjects()
{
857
  for (int i = 0; i < static_cast<int>(NumberOfTextures); ++i)
858
  {
859
    if (this->Textures[i])
860
    {
861
      this->Textures[i]->Delete();
862
      this->Textures[i] = nullptr;
863
    }
864
  }
865

866 867
  DeleteHelper(this->CopyColorVAO);
  DeleteHelper(this->CopyColorVBO);
868
  DeleteHelper(this->CopyDepthVAO);
869
  DeleteHelper(this->CopyDepthVBO);
870
  DeleteHelper(this->BackBlendVAO);
871
  DeleteHelper(this->BackBlendVBO);
872
  DeleteHelper(this->BlendVAO);
873
  DeleteHelper(this->BlendVBO);
874 875

  // don't delete the shader programs -- let the cache clean them up.
876 877 878 879
  this->CopyColorProgram = nullptr;
  this->CopyDepthProgram = nullptr;
  this->BackBlendProgram = nullptr;
  this->BlendProgram = nullptr;
880 881 882 883 884
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::RenderTranslucentPass()
{
885
  TIME_FUNCTION(vtkDualDepthPeelingPass::RenderTranslucentPass);
886
  this->TranslucentPass->Render(this->RenderState);
887
  ++this->TranslucentRenderCount;
888 889
}

890 891 892
//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::RenderVolumetricPass()
{
893
  TIME_FUNCTION(vtkDualDepthPeelingPass::RenderVolumetricPass);
894
  this->VolumetricPass->Render(this->RenderState);
895
  ++this->VolumetricRenderCount;
896 897 898 899 900 901 902 903 904 905
  this->LastPeelHadVolumes =
      this->VolumetricPass->GetNumberOfRenderedProps() > 0;
}

//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::IsRenderingVolumes()
{
  return this->VolumetricPass && this->LastPeelHadVolumes;
}

906 907 908 909
//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Initialize(const vtkRenderState *s)
{
  this->RenderState = s;
910
  this->LastPeelHadVolumes = true;
911 912

  // Get current viewport size:
913
  vtkRenderer *r = s->GetRenderer();
914
  if(s->GetFrameBuffer()==nullptr)
915
  {
916 917 918
    // get the viewport dimensions
    r->GetTiledSizeAndOrigin(&this->ViewportWidth, &this->ViewportHeight,
                             &this->ViewportX, &this->ViewportY);
919
  }
920
  else
921
  {
922 923 924 925 926 927
    int size[2];
    s->GetWindowSize(size);
    this->ViewportWidth = size[0];
    this->ViewportHeight = size[1];
    this->ViewportX =0 ;
    this->ViewportY = 0;
928
  }
929

930 931 932 933 934 935
  this->Timer = r->GetRenderWindow()->GetRenderTimer();

  // The above code shouldn't touch the OpenGL command stream, so it's okay to
  // start the event here:
  TIME_FUNCTION(vtkDualDepthPeelingPass::Initialize);

936 937 938 939 940 941
  // See if we can reuse existing textures:
  if (this->Textures[Back] &&
      (static_cast<int>(this->Textures[Back]->GetHeight()) !=
       this->ViewportHeight ||
       static_cast<int>(this->Textures[Back]->GetWidth()) !=
       this->ViewportWidth))
942
  {
943
    this->FreeGLObjects();
944
  }
945 946 947

  // Allocate new textures if needed:
  if (!this->Framebuffer)
948
  {
949
    this->Framebuffer = vtkOpenGLFramebufferObject::New();
950
  }
951

952 953
  if (!this->Textures[BackTemp])
  {
954 955 956 957 958 959 960 961 962 963 964
    std::generate(this->Textures,
                  this->Textures + static_cast<int>(NumberOfTextures),
                  &vtkTextureObject::New);

    this->InitColorTexture(this->Textures[BackTemp], s);
    this->InitColorTexture(this->Textures[Back], s);
    this->InitColorTexture(this->Textures[FrontA], s);
    this->InitColorTexture(this->Textures[FrontB], s);
    this->InitDepthTexture(this->Textures[DepthA], s);
    this->InitDepthTexture(this->Textures[DepthB], s);
    this->InitOpaqueDepthTexture(this->Textures[OpaqueDepth], s);
965
  }
966 967

  this->InitFramebuffer(s);
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitColorTexture(vtkTextureObject *tex,
                                               const vtkRenderState *s)
{
  tex->SetContext(static_cast<vtkOpenGLRenderWindow*>(
                    s->GetRenderer()->GetRenderWindow()));
  tex->SetFormat(GL_RGBA);
  tex->SetInternalFormat(GL_RGBA8);
  tex->Allocate2D(this->ViewportWidth, this->ViewportHeight, 4,
                  vtkTypeTraits<vtkTypeUInt8>::VTK_TYPE_ID);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitDepthTexture(vtkTextureObject *tex,
                                               const vtkRenderState *s)
{
  tex->SetContext(static_cast<vtkOpenGLRenderWindow*>(
                    s->GetRenderer()->GetRenderWindow()));
  tex->SetFormat(GL_RG);
  tex->SetInternalFormat(GL_RG32F);
  tex->Allocate2D(this->ViewportWidth, this->ViewportHeight, 2,
                  vtkTypeTraits<vtkTypeFloat32>::VTK_TYPE_ID);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitOpaqueDepthTexture(vtkTextureObject *tex,
                                                     const vtkRenderState *s)
{
  tex->SetContext(static_cast<vtkOpenGLRenderWindow*>(
                    s->GetRenderer()->GetRenderWindow()));
  tex->AllocateDepth(this->ViewportWidth, this->ViewportHeight,
                     vtkTextureObject::Float32);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitFramebuffer(const vtkRenderState *s)
{
  this->Framebuffer->SetContext(static_cast<vtkOpenGLRenderWindow*>(
                                  s->GetRenderer()->GetRenderWindow()));

  // Save the current FBO bindings to restore them later.
1011
  this->Framebuffer->SaveCurrentBindingsAndBuffers(GL_DRAW_FRAMEBUFFER);
1012
}
1013

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::ActivateDrawBuffers(const TextureName *ids,
                                                  size_t numTex)
{
  this->Framebuffer->DeactivateDrawBuffers();
  for (size_t i = 0; i < numTex; ++i)
  {
    this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER,
                                          static_cast<unsigned int>(i),
                                          this->Textures[ids[i]]);
  }
1025 1026 1027 1028

  const unsigned int numBuffers = static_cast<unsigned int>(numTex);
  this->SetActiveDrawBuffers(numBuffers);
  this->Framebuffer->ActivateDrawBuffers(numBuffers);
1029 1030 1031 1032 1033
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Prepare()
{
1034 1035
  TIME_FUNCTION(vtkDualDepthPeelingPass::Prepare);

1036 1037 1038 1039 1040 1041 1042 1043
  // Since we're rendering into a temporary non-default framebuffer, we need to
  // remove the translation from the viewport and disable the scissor test;
  // otherwise we'll capture the wrong area of the rendered geometry.
  glViewport(0, 0,
             this->ViewportWidth, this->ViewportHeight);
  this->SaveScissorTestState = glIsEnabled(GL_SCISSOR_TEST) == GL_TRUE;
  glDisable(GL_SCISSOR_TEST);

1044 1045 1046
  glGetIntegerv(GL_CULL_FACE_MODE, &this->CullFaceMode);
  this->CullFaceEnabled = glIsEnabled(GL_CULL_FACE) == GL_TRUE;

1047 1048
  this->DepthTestEnabled = glIsEnabled(GL_DEPTH_TEST) == GL_TRUE;

1049 1050 1051
  // Prevent vtkOpenGLActor from messing with the depth mask:
  size_t numProps = this->RenderState->GetPropArrayCount();
  for (size_t i = 0; i < numProps; ++i)
1052
  {
1053 1054 1055
    vtkProp *prop = this->RenderState->GetPropArray()[i];
    vtkInformation *info = prop->GetPropertyKeys();
    if (!info)
1056
    {
1057 1058 1059 1060
      info = vtkInformation::New();
      prop->SetPropertyKeys(info);
      info->FastDelete();
    }
1061 1062
    info->Set(vtkOpenGLActor::GLDepthMaskOverride(), -1);
  }
1063 1064 1065 1066 1067

  // Setup GL state:
  glDisable(GL_DEPTH_TEST);
  this->InitializeOcclusionQuery();
  this->CurrentPeel = 0;
1068 1069
  this->TranslucentRenderCount = 0;
  this->VolumetricRenderCount = 0;
1070 1071

  // Save the current FBO bindings to restore them later.
1072
  this->Framebuffer->SaveCurrentBindingsAndBuffers(GL_DRAW_FRAMEBUFFER);
1073 1074 1075 1076 1077 1078
  this->Framebuffer->Bind(GL_DRAW_FRAMEBUFFER);

  // The source front buffer must be initialized, since it simply uses additive
  // blending.
  // The back-blending may discard fragments, so the back peel accumulator needs
  // initialization as well.
1079 1080
  std::array<TextureName, 2> targets = { { Back, this->FrontSource } };
  this->ActivateDrawBuffers(targets);
1081 1082 1083 1084 1085
  glClearColor(0.f, 0.f, 0.f, 0.f);
  glClear(GL_COLOR_BUFFER_BIT);

  // Fill both depth buffers with -1, -1. This lets us discard fragments in
  // CopyOpaqueDepthBuffers, which gives a moderate performance boost.
1086 1087 1088
  targets[0] = this->DepthSource;
  targets[1] = this->DepthDestination;
  this->ActivateDrawBuffers(targets);
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  glClearColor(-1, -1, 0, 0);
  glClear(GL_COLOR_BUFFER_BIT);

  // Pre-fill the depth buffer with opaque pass data:
  this->CopyOpaqueDepthBuffer();

  // Initialize the transparent depths for the peeling algorithm:
  this->InitializeDepth();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitializeOcclusionQuery()
{
1102 1103
  glGenQueries(1, &this->TranslucentOcclusionQueryId);
  glGenQueries(1, &this->VolumetricOcclusionQueryId);
1104 1105 1106

  int numPixels = this->ViewportHeight * this->ViewportWidth;
  this->OcclusionThreshold = numPixels * this->OcclusionRatio;
1107 1108
  this->TranslucentWrittenPixels = this->OcclusionThreshold + 1;
  this->VolumetricWrittenPixels = this->OcclusionThreshold + 1;
1109 1110 1111 1112 1113
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::CopyOpaqueDepthBuffer()
{
1114 1115
  TIME_FUNCTION(vtkDualDepthPeelingPass::CopyOpaqueDepthBuffer);

1116 1117 1118 1119 1120
  // Initialize the peeling depth buffer using the existing opaque depth buffer.
  // Note that the min component is stored as -depth, allowing
  // glBlendEquation = GL_MAX to be used during peeling.

  // Copy from the current (default) framebuffer's depth buffer into a texture:
1121
  this->Framebuffer->RestorePreviousBindingsAndBuffers(GL_DRAW_FRAMEBUFFER);
1122 1123 1124
  this->Textures[OpaqueDepth]->CopyFromFrameBuffer(
        this->ViewportX, this->ViewportY, 0, 0,
        this->ViewportWidth, this->ViewportHeight);
1125
  this->Framebuffer->SaveCurrentBindingsAndBuffers(GL_DRAW_FRAMEBUFFER);
1126 1127 1128 1129 1130 1131 1132
  this->Framebuffer->Bind(GL_DRAW_FRAMEBUFFER);

  // Fill both depth buffers with the opaque fragment depths. InitializeDepth
  // will compare translucent fragment depths with values in DepthDestination
  // and write to DepthSource using MAX blending, so we need both to have opaque
  // fragments (src/dst seem reversed because they're named for their usage in
  // PeelRender).
1133 1134 1135
  std::array<TextureName, 2> targets = { { this->DepthSource,
                                           this->DepthDestination } };
  this->ActivateDrawBuffers(targets);
1136 1137 1138 1139
  this->Textures[OpaqueDepth]->Activate();

  glDisable(GL_BLEND);

1140 1141
  typedef vtkOpenGLRenderUtilities GLUtil;

1142 1143 1144
  vtkOpenGLRenderWindow *renWin = static_cast<vtkOpenGLRenderWindow*>(
        this->RenderState->GetRenderer()->GetRenderWindow());
  if (!this->CopyDepthProgram)
1145
  {
1146 1147 1148
    std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate();
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Decl",
1149
          "uniform float clearValue;\n"
1150 1151 1152
          "uniform sampler2D oDepth;\n");
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Impl",
1153 1154 1155 1156 1157 1158
          "  float d = texture2D(oDepth, texCoord).x;\n"
          "  if (d == clearValue)\n"
          "    { // If no depth value has been written, discard the frag:\n"
          "    discard;\n"
          "    }\n"
          "  gl_FragData[0] = gl_FragData[1] = vec4(-1, d, 0., 0.);\n"
1159 1160 1161 1162 1163
          );
    this->CopyDepthProgram = renWin->GetShaderCache()->ReadyShaderProgram(
          GLUtil::GetFullScreenQuadVertexShader().c_str(),
          fragShader.c_str(),
          GLUtil::GetFullScreenQuadGeometryShader().c_str());
1164
  }
1165
  else
1166
  {
1167
    renWin->GetShaderCache()->ReadyShaderProgram(this->CopyDepthProgram);
1168
  }
1169

1170 1171 1172 1173 1174
  if (!this->CopyDepthProgram)
  {
    return;
  }

1175
  if (!this->CopyDepthVAO)
1176
  {
1177
    this->CopyDepthVBO = vtkOpenGLBufferObject::New();
1178
    this->CopyDepthVAO = vtkOpenGLVertexArrayObject::New();
1179 1180
    GLUtil::PrepFullScreenVAO(this->CopyDepthVBO, this->CopyDepthVAO,
                              this->CopyDepthProgram);
1181
  }
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193

  // Get the clear value. We don't set this, so it should still be what the
  // opaque pass uses:
  GLfloat clearValue = 1.f;
  glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearValue);
  this->CopyDepthProgram->SetUniformf("clearValue", clearValue);
  this->CopyDepthProgram->SetUniformi(
        "oDepth", this->Textures[OpaqueDepth]->GetTextureUnit());

  this->CopyDepthVAO->Bind();

  annotate("Copying opaque depth!");
1194
  GLUtil::DrawFullScreenQuad();
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
  annotate("Opaque depth copied!");

  this->CopyDepthVAO->Release();

  this->Textures[OpaqueDepth]->Deactivate();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::InitializeDepth()
{
1205 1206
  TIME_FUNCTION(vtkDualDepthPeelingPass::InitializeDepth);

1207 1208
  // Add the translucent geometry to our depth peeling buffer:

1209
  // We bind the back temporary buffer as render target 0 -- the data we
1210 1211 1212 1213
  // write to it isn't used, but this makes it easier to work with the existing
  // polydata shaders as they expect gl_FragData[0] to be RGBA. The front
  // destination buffer is cleared prior to peeling, so it's just a dummy
  // buffer at this point.
1214 1215
  std::array<TextureName, 2> targets = { { BackTemp, this->DepthSource } };
  this->ActivateDrawBuffers(targets);
1216 1217

  this->SetCurrentStage(InitializingDepth);
1218
  this->SetCurrentPeelType(TranslucentPeel);
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
  this->Textures[this->DepthDestination]->Activate();

  glEnable(GL_BLEND);
  glBlendEquation(GL_MAX);
  annotate("Initializing depth.");
  this->RenderTranslucentPass();
  annotate("Depth initialized");

  this->Textures[this->DepthDestination]->Deactivate();
}

1230 1231 1232
//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::PeelVolumesOutsideTranslucentRange()
{
1233 1234
  TIME_FUNCTION(vtkDualDepthPeelingPass::PeelVolumesOutsideTranslucentRange);

1235 1236 1237
  // Enable the destination targets. Note that we're rendering directly into
  // the Back accumulation buffer and the FrontSource buffer, since we know
  // this is the first time these buffers will be drawn into.
1238 1239
  std::array<TextureName, 2> targets = { { Back, this->FrontSource } };
  this->ActivateDrawBuffers(targets);
1240

1241 1242 1243 1244
  // Cull back fragments of the volume's proxy geometry since they are
  // not necessary anyway.
  glCullFace(GL_BACK);
  glEnable(GL_CULL_FACE);
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

  this->SetCurrentStage(InitializingDepth);
  this->SetCurrentPeelType(VolumetricPeel);

  this->Textures[this->DepthSource]->Activate();
  this->Textures[this->DepthDestination]->Activate();

  annotate("Peeling volumes external to translucent geometry.");
  this->RenderVolumetricPass();
  annotate("External volume peel done.");

1256 1257 1258
  glCullFace(this->CullFaceMode);
  glDisable(GL_CULL_FACE);

1259 1260
  this->Textures[this->DepthSource]->Deactivate();
  this->Textures[this->DepthDestination]->Deactivate();
1261 1262
}

1263 1264 1265
//------------------------------------------------------------------------------
bool vtkDualDepthPeelingPass::PeelingDone()
{
1266 1267 1268 1269
  // Note that we do NOT check the volumetric occlusion info as an early
  // termination criterion. A volume may not exist for every slice, or may
  // only be found in the front slice (only the back is counted for occlusion
  // tests). This can lead to incorrect early termination of volume peeling.
1270
  return this->CurrentPeel >= this->MaximumNumberOfPeels ||
1271
         this->TranslucentWrittenPixels <= this->OcclusionThreshold;
1272 1273 1274 1275 1276
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::Peel()
{
1277 1278
  TIME_FUNCTION(vtkDualDepthPeelingPass::Peel);

1279 1280
  this->InitializeTargetsForTranslucentPass();
  this->PeelTranslucentGeometry();
1281
  this->StartTranslucentOcclusionQuery();
1282
  this->BlendBackBuffer();
1283
  this->EndTranslucentOcclusionQuery();
1284
  this->SwapFrontBufferSourceDest();
1285 1286 1287 1288 1289

  if (this->IsRenderingVolumes())
  {
    this->InitializeTargetsForVolumetricPass();
    this->PeelVolumetricGeometry();
1290

1291
    this->StartVolumetricOcclusionQuery();
1292
    this->BlendBackBuffer();
1293
    this->EndVolumetricOcclusionQuery();
1294
    this->SwapFrontBufferSourceDest();
1295 1296
  }

1297 1298
  this->SwapDepthBufferSourceDest();

1299 1300 1301
  ++this->CurrentPeel;

#ifdef DEBUG_PEEL
1302 1303 1304
  std::cout << "Peel " << this->CurrentPeel << ": Pixels written: trans="
            << this->TranslucentWrittenPixels << " volume="
            << this->VolumetricWrittenPixels << " (threshold: "
1305 1306 1307 1308
            << this->OcclusionThreshold << ")\n";
#endif // DEBUG_PEEL
}

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::PrepareFrontDestination()
{
  // If we're not using volumes, clear the front destination buffer and just
  // let the shaders pass-through the colors from the previous peel.
  //
  // If we are rendering volumes, we can't rely on the shader pass-through,
  // since the volumetric and translucent geometry may not cover the same
  // pixels, and information would be lost if we simply cleared the front
  // buffer. In this case, we're essentially forcing a fullscreen pass-through
  // prior to the any actual rendering calls.
  if (!this->IsRenderingVolumes())
  {
    this->ClearFrontDestination();
  }
  else
  {
    this->CopyFrontSourceToFrontDestination();
  }
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::ClearFrontDestination()
{
1333
  TIME_FUNCTION(vtkDualDepthPeelingPass::ClearFrontDestination);
1334
  annotate("ClearFrontDestination()");
1335
  this->ActivateDrawBuffer(this->FrontDestination);
1336 1337 1338 1339 1340 1341 1342
  glClearColor(0.f, 0.f, 0.f, 0.f);
  glClear(GL_COLOR_BUFFER_BIT);
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::CopyFrontSourceToFrontDestination()
{
1343 1344
  TIME_FUNCTION(vtkDualDepthPeelingPass::CopyFrontSourceToFrontDestination);

1345
  this->ActivateDrawBuffer(this->FrontDestination);
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399

  glDisable(GL_BLEND);

  typedef vtkOpenGLRenderUtilities GLUtil;

  vtkOpenGLRenderWindow *renWin = static_cast<vtkOpenGLRenderWindow*>(
        this->RenderState->GetRenderer()->GetRenderWindow());
  if (!this->CopyColorProgram)
  {
    std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate();
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Decl",
          "uniform sampler2D inTex;\n");
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Impl",
          "  gl_FragData[0] = texture2D(inTex, texCoord);\n");
    this->CopyColorProgram = renWin->GetShaderCache()->ReadyShaderProgram(
          GLUtil::GetFullScreenQuadVertexShader().c_str(),
          fragShader.c_str(),
          GLUtil::GetFullScreenQuadGeometryShader().c_str());
  }
  else
  {
    renWin->GetShaderCache()->ReadyShaderProgram(this->CopyColorProgram);
  }

  if (!this->CopyColorProgram)
  {
    return;
  }

  if (!this->CopyColorVAO)
  {
    this->CopyColorVBO = vtkOpenGLBufferObject::New();
    this->CopyColorVAO = vtkOpenGLVertexArrayObject::New();
    GLUtil::PrepFullScreenVAO(this->CopyColorVBO, this->CopyColorVAO,
                              this->CopyColorProgram);
  }

  this->Textures[this->FrontSource]->Activate();
  this->CopyColorProgram->SetUniformi(
        "inTex", this->Textures[this->FrontSource]->GetTextureUnit());

  this->CopyColorVAO->Bind();

  annotate("Copying front texture src -> dst for pre-pass initialization!");
  GLUtil::DrawFullScreenQuad();
  annotate("Front texture copied!");

  this->CopyColorVAO->Release();

  this->Textures[this->FrontSource]->Deactivate();
}

1400
//------------------------------------------------------------------------------
1401
void vtkDualDepthPeelingPass::InitializeTargetsForTranslucentPass()
1402
{
1403 1404
  TIME_FUNCTION(vtkDualDepthPeelingPass::InitializeTargetsForTranslucentPass);

1405 1406
  // Initialize destination buffers to their minima, since we're MAX blending,
  // this ensures that valid outputs are captured.
1407
  this->ActivateDrawBuffer(BackTemp);
1408 1409 1410
  glClearColor(0.f, 0.f, 0.f, 0.f);
  glClear(GL_COLOR_BUFFER_BIT);

1411
  this->ActivateDrawBuffer(this->DepthDestination);
1412 1413
  glClearColor(-1.f, -1.f, 0.f, 0.f);
  glClear(GL_COLOR_BUFFER_BIT);
1414 1415

  this->PrepareFrontDestination();
1416 1417 1418
}

//------------------------------------------------------------------------------
1419 1420
void vtkDualDepthPeelingPass::InitializeTargetsForVolumetricPass()
{
1421 1422
  TIME_FUNCTION(vtkDualDepthPeelingPass::InitializeTargetsForVolumetricPass);

1423 1424
  // Clear the back buffer to ensure that current fragments are captured for
  // later blending into the back accumulation buffer:
1425
  this->ActivateDrawBuffer(BackTemp);
1426 1427
  glClearColor(0.f, 0.f, 0.f, 0.f);
  glClear(GL_COLOR_BUFFER_BIT);
1428 1429

  this->PrepareFrontDestination();
1430 1431 1432 1433
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::PeelTranslucentGeometry()
1434
{
1435 1436
  TIME_FUNCTION(vtkDualDepthPeelingPass::PeelTranslucentGeometry);

1437
  // Enable the destination targets:
1438 1439 1440 1441
  std::array<TextureName, 3> targets = { { BackTemp,
                                           this->FrontDestination,
                                           this->DepthDestination } };
  this->ActivateDrawBuffers(targets);
1442 1443 1444 1445 1446 1447

  // Use MAX blending to capture peels:
  glEnable(GL_BLEND);
  glBlendEquation(GL_MAX);

  this->SetCurrentStage(Peeling);
1448
  this->SetCurrentPeelType(TranslucentPeel);
1449 1450 1451
  this->Textures[this->FrontSource]->Activate();
  this->Textures[this->DepthSource]->Activate();

1452
  annotate("Start translucent peeling!");
1453
  this->RenderTranslucentPass();
1454 1455 1456 1457 1458 1459 1460 1461 1462
  annotate("Translucent peeling done!");

  this->Textures[this->FrontSource]->Deactivate();
  this->Textures[this->DepthSource]->Deactivate();
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::PeelVolumetricGeometry()
{
1463 1464
  TIME_FUNCTION(vtkDualDepthPeelingPass::PeelVolumeGeometry);

1465
  // Enable the destination targets:
1466 1467
  std::array<TextureName, 2> targets = { { BackTemp, this->FrontDestination } };
  this->ActivateDrawBuffers(targets);
1468

1469 1470 1471 1472 1473
  // Cull back fragments of the volume's proxy geometry since they are
  // not necessary anyway.
  glCullFace(GL_BACK);
  glEnable(GL_CULL_FACE);

1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
  // Use MAX blending to capture peels:
  glEnable(GL_BLEND);
  glBlendEquation(GL_MAX);

  this->SetCurrentStage(Peeling);
  this->SetCurrentPeelType(VolumetricPeel);

  this->Textures[this->FrontSource]->Activate();
  this->Textures[this->DepthSource]->Activate();
  this->Textures[this->DepthDestination]->Activate();
1484
  this->Textures[OpaqueDepth]->Activate();
1485 1486 1487 1488

  annotate("Start volumetric peeling!");
  this->RenderVolumetricPass();
  annotate("Volumetric peeling done!");
1489 1490 1491

  this->Textures[this->FrontSource]->Deactivate();
  this->Textures[this->DepthSource]->Deactivate();
1492
  this->Textures[this->DepthDestination]->Deactivate();
1493 1494 1495 1496
  this->Textures[OpaqueDepth]->Deactivate();

  glCullFace(this->CullFaceMode);
  glDisable(GL_CULL_FACE);
1497 1498 1499 1500 1501
}

//------------------------------------------------------------------------------
void vtkDualDepthPeelingPass::BlendBackBuffer()
{
1502 1503
  TIME_FUNCTION(vtkDualDepthPeelingPass::BlendBackBuffer);

1504
  this->ActivateDrawBuffer(Back);
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
  this->Textures[BackTemp]->Activate();

  /* For this step, we blend the last peel's back fragments into a back-
   * accumulation buffer. The full over-blending equations are:
   *
   * (f = front frag (incoming peel); b = back frag (current accum. buffer))
   *
   * a = f.a + (1. - f.a) * b.a
   *
   * if a == 0, C == (0, 0, 0). Otherwise,
   *
   * C = ( f.a * f.rgb + (1. - f.a) * b.a * b.rgb ) / a
   *
   * We use premultiplied alphas to save on computations, resulting in:
   *
   * [a * C] = [f.a * f.rgb] + (1 - f.a) * [ b.a * b.rgb ]
   * a = f.a + (1. - f.a) * b.a
   */

  glEnable(GL_BLEND);
  glBlendEquation(GL_FUNC_ADD);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

1528 1529
  typedef vtkOpenGLRenderUtilities GLUtil;

1530 1531 1532
  vtkOpenGLRenderWindow *renWin = static_cast<vtkOpenGLRenderWindow*>(
        this->RenderState->GetRenderer()->GetRenderWindow());
  if (!this->BackBlendProgram)
1533
  {
1534 1535 1536
    std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate();
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Decl",
1537
          "uniform sampler2D newPeel;\n"
1538 1539 1540
          );
    vtkShaderProgram::Substitute(
          fragShader, "//VTK::FSQ::Impl",
1541 1542 1543 1544 1545 1546 1547
          "  vec4 f = texture2D(newPeel, texCoord); // new frag\n"
          "  if (f.a == 0.)\n"
          "    {\n"
          "    discard;\n"
          "    }\n"
          "\n"
          "  gl_FragData[0] = f;\n"
1548 1549 1550 1551 1552
          );
    this->BackBlendProgram = renWin->GetShaderCache()->ReadyShaderProgram(
          GLUtil::GetFullScreenQuadVertexShader().c_str(),
          fragShader.c_str(),
          GLUtil::GetFullScreenQuadGeometryShader().c_str());
1553
  }
1554
  else
1555
  {
1556
    renWin->GetShaderCache()->ReadyShaderProgram(this->BackBlendProgram);
1557
  }
1558

1559 1560 1561 1562 1563
  if (!this->BackBlendProgram)
  {
    return;
  }

1564
  if (!this->BackBlendVAO)
1565
  {
1566
    this->BackBlendVBO = vtkOpenGLBufferObject::New();
1567
    this->BackBlendVAO = vtkOpenGLVertexArrayObject::New();
1568 1569
    GLUtil::PrepFullScreenVAO(this->BackBlendVBO, this->BackBlendVAO,
                              this->BackBlendProgram);
1570
  }
1571 1572 1573 1574 1575 1576 1577

  this->BackBlendProgram->SetUniformi(
        "newPeel", this->Textures[BackTemp]->GetTextureUnit());

  this->BackBlendVAO->Bind();

  annotate("Start blending back!");
1578
  GLUtil::DrawFullScreenQuad();
1579 1580 1581 1582 1583 1584 1585 1586
  annotate("Back blended!");

  this->BackBlendVAO->Release();

  this->Textures[BackTemp]->Deactivate();
}

//------------------------------------------------------------------------------
1587
void vtkDualDepthPeelingPass::StartTranslucentOcclusionQuery()
1588
{
1589 1590 1591 1592
  // ES 3.0 only supports checking if *any* samples passed. We'll just use
  // that query to stop peeling once all frags are processed, and ignore the
  // requested occlusion ratio.
#if GL_ES_VERSION_3_0 == 1
1593
  glBeginQuery(GL_ANY_SAMPLES_PASSED, this->TranslucentOcclusionQueryId);
1594
#else // GL ES 3.0
1595
  glBeginQuery(GL_SAMPLES_PASSED, this->TranslucentOcclusionQueryId);
1596
#endif // GL ES 3.0
1597 1598 1599
}

//------------------------------------------------------------------------------
1600
void vtkDualDepthPeelingPass::EndTranslucentOcclusionQuery()
1601
{
1602 1603 1604 1605
  // We time the end, but not the start, since this is where we stall to
  // sync the stream.
  TIME_FUNCTION(vtkDualDepthPeelingPass::EndTranslucentOcclusionQuery);

1606 1607 1608
#if GL_ES_VERSION_3_0 == 1
  glEndQuery(GL_ANY_SAMPLES_PASSED);
  GLuint anySamplesPassed;
1609
  glGetQueryObjectuiv(this->TranslucentOcclusionQueryId, GL_QUERY_RESULT,
1610
                      &anySamplesPassed);
1611 1612
  this->TranslucentWrittenPixels =
      anySamplesPassed ? this->OcclusionThreshold + 1 : 0;
1613
#else // GL ES 3.0