0030483: Visualization, Path Tracing - make Tile Size configurable
[occt.git] / src / OpenGl / OpenGl_View_Raytrace.cxx
index aac555f..12177f3 100644 (file)
@@ -42,24 +42,30 @@ namespace
 {
   static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
   static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
+}
 
-  //! Operator returning TRUE for positional light sources.
-  struct IsLightPositional
-  {
-    bool operator() (const OpenGl_Light& theLight)
-    {
-      return theLight.Type != Graphic3d_TOLS_DIRECTIONAL;
-    }
-  };
+namespace
+{
+  //! Defines OpenGL texture samplers.
+  static const Graphic3d_TextureUnit OpenGl_RT_EnvironmentMapTexture = Graphic3d_TextureUnit_0;
 
-  //! Operator returning TRUE for any non-ambient light sources.
-  struct IsNotAmbient
-  {
-    bool operator() (const OpenGl_Light& theLight)
-    {
-      return theLight.Type != Graphic3d_TOLS_AMBIENT;
-    }
-  };
+  static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture  = Graphic3d_TextureUnit_1;
+  static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture  = Graphic3d_TextureUnit_2;
+  static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture  = Graphic3d_TextureUnit_3;
+  static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
+
+  static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
+  static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
+  static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
+  static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
+
+  static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
+  static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
+
+  static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
+  static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
+
+  static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
 }
 
 // =======================================================================
@@ -289,6 +295,10 @@ Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStru
 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
 {
   theMatrix.InitIdentity();
+  if (theParams.IsNull())
+  {
+    return;
+  }
 
   // Apply scaling
   const Graphic3d_Vec2& aScale = theParams->Scale();
@@ -418,27 +428,37 @@ OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace*
   theMaterial.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
 
   // Handle material textures
-  if (theAspect->Aspect()->ToMapTexture())
+  if (!theAspect->Aspect()->ToMapTexture())
   {
-    if (theGlContext->HasRayTracingTextures())
-    {
-      buildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
+    return theMaterial;
+  }
 
-      // write texture ID to diffuse w-component
-      theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() =
-        static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (theAspect->TextureRes (theGlContext)));
-    }
-    else if (!myIsRaytraceWarnTextures)
-    {
-      const TCollection_ExtendedString aWarnMessage =
-        "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
-        "Please try to update graphics card driver. At the moment textures will be ignored.";
+  const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
+  if (aTextureSet.IsNull()
+   || aTextureSet->IsEmpty()
+   || aTextureSet->First().IsNull())
+  {
+    return theMaterial;
+  }
 
-      theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
-        GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
+  if (theGlContext->HasRayTracingTextures())
+  {
+    const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
+    buildTextureTransform (aTexture->Sampler()->Parameters(), theMaterial.TextureTransform);
 
-      myIsRaytraceWarnTextures = Standard_True;
-    }
+    // write texture ID to diffuse w-component
+    theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
+  }
+  else if (!myIsRaytraceWarnTextures)
+  {
+    const TCollection_ExtendedString aWarnMessage =
+      "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
+      "Please try to update graphics card driver. At the moment textures will be ignored.";
+
+    theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+      GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
+
+    myIsRaytraceWarnTextures = Standard_True;
   }
 
   return theMaterial;
@@ -600,53 +620,43 @@ Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_
     aSet->TexCrds.reserve  (anAttribs->NbElements);
 
     const size_t aVertFrom = aSet->Vertices.size();
-    for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
+
+    Standard_Integer anAttribIndex = 0;
+    Standard_Size anAttribStride = 0;
+    if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
     {
-      const Graphic3d_Attribute& anAttrib = anAttribs->Attribute       (anAttribIter);
-      const size_t               anOffset = anAttribs->AttributeOffset (anAttribIter);
-      if (anAttrib.Id == Graphic3d_TOA_POS)
+      const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
+      if (anAttrib.DataType == Graphic3d_TOD_VEC2
+       || anAttrib.DataType == Graphic3d_TOD_VEC3
+       || anAttrib.DataType == Graphic3d_TOD_VEC4)
       {
-        if (anAttrib.DataType == Graphic3d_TOD_VEC3
-         || anAttrib.DataType == Graphic3d_TOD_VEC4)
+        for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
         {
-          for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
-          {
-            aSet->Vertices.push_back (
-              *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
-          }
-        }
-        else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
-        {
-          for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
-          {
-            const Standard_ShortReal* aCoords =
-              reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
-
-            aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
-          }
+          const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
+          aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
         }
       }
-      else if (anAttrib.Id == Graphic3d_TOA_NORM)
+    }
+    if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
+    {
+      const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
+      if (anAttrib.DataType == Graphic3d_TOD_VEC3
+       || anAttrib.DataType == Graphic3d_TOD_VEC4)
       {
-        if (anAttrib.DataType == Graphic3d_TOD_VEC3
-         || anAttrib.DataType == Graphic3d_TOD_VEC4)
+        for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
         {
-          for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
-          {
-            aSet->Normals.push_back (
-              *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
-          }
+          aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
         }
       }
-      else if (anAttrib.Id == Graphic3d_TOA_UV)
+    }
+    if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
+    {
+      const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
+      if (anAttrib.DataType == Graphic3d_TOD_VEC2)
       {
-        if (anAttrib.DataType == Graphic3d_TOD_VEC2)
+        for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
         {
-          for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
-          {
-            aSet->TexCrds.push_back (
-              *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
-          }
+          aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
         }
       }
     }
@@ -1129,8 +1139,7 @@ TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_C
       // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
       if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
       {
-        aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") +
-          TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize());
+        aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
       }
     }
 
@@ -1149,6 +1158,11 @@ TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_C
     }
   }
 
+  if (myRaytraceParameters.DepthOfField)
+  {
+    aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
+  }
+
   return aPrefixString;
 }
 
@@ -1313,7 +1327,9 @@ Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Conte
 // function : initRaytraceResources
 // purpose  : Initializes OpenGL/GLSL shader programs
 // =======================================================================
-Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
+Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
+                                                     const Standard_Integer theSizeY,
+                                                     const Handle(OpenGl_Context)& theGlContext)
 {
   if (myRaytraceInitStatus == OpenGl_RT_FAIL)
   {
@@ -1357,40 +1373,17 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
       }
     }
 
-    Standard_Integer aNbTilesX = 8;
-    Standard_Integer aNbTilesY = 8;
-
-    for (Standard_Integer anIdx = 0; aNbTilesX * aNbTilesY < myRenderParams.NbRayTracingTiles; ++anIdx)
-    {
-      (anIdx % 2 == 0 ? aNbTilesX : aNbTilesY) <<= 1;
-    }
-
     if (myRenderParams.RaytracingDepth             != myRaytraceParameters.NbBounces
      || myRenderParams.IsTransparentShadowEnabled  != myRaytraceParameters.TransparentShadows
      || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
      || myRenderParams.TwoSidedBsdfModels          != myRaytraceParameters.TwoSidedBsdfModels
-     || myRaytraceGeometry.HasTextures()           != myRaytraceParameters.UseBindlessTextures
-     || aNbTilesX                                  != myRaytraceParameters.NbTilesX
-     || aNbTilesY                                  != myRaytraceParameters.NbTilesY)
+     || myRaytraceGeometry.HasTextures()           != myRaytraceParameters.UseBindlessTextures)
     {
       myRaytraceParameters.NbBounces           = myRenderParams.RaytracingDepth;
       myRaytraceParameters.TransparentShadows  = myRenderParams.IsTransparentShadowEnabled;
       myRaytraceParameters.GlobalIllumination  = myRenderParams.IsGlobalIlluminationEnabled;
       myRaytraceParameters.TwoSidedBsdfModels  = myRenderParams.TwoSidedBsdfModels;
       myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
-
-#ifdef RAY_TRACE_PRINT_INFO
-      if (aNbTilesX != myRaytraceParameters.NbTilesX
-       || aNbTilesY != myRaytraceParameters.NbTilesY)
-      {
-        std::cout << "Number of tiles X: " << aNbTilesX << "\n";
-        std::cout << "Number of tiles Y: " << aNbTilesY << "\n";
-      }
-#endif
-
-      myRaytraceParameters.NbTilesX = aNbTilesX;
-      myRaytraceParameters.NbTilesY = aNbTilesY;
-
       aToRebuildShaders = Standard_True;
     }
 
@@ -1410,6 +1403,14 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
 
       aToRebuildShaders = Standard_True;
     }
+    myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
+
+    const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
+    if (myRaytraceParameters.DepthOfField != toEnableDof)
+    {
+      myRaytraceParameters.DepthOfField = toEnableDof;
+      aToRebuildShaders = Standard_True;
+    }
 
     if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
     {
@@ -1435,27 +1436,10 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
       myPostFSAAShaderSource.SetPrefix (aPrefixString);
       myOutImageShaderSource.SetPrefix (aPrefixString);
 
-      if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
-       || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source())
-       || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source()))
-      {
-        return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
-      }
-
-      TCollection_AsciiString aLog;
-
-      if (!myRaytraceShader->Compile (theGlContext)
-       || !myPostFSAAShader->Compile (theGlContext)
-       || !myOutImageShader->Compile (theGlContext))
+      if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceShaderSource.Source())
+       || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAShaderSource.Source())
+       || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageShaderSource.Source()))
       {
-#ifdef RAY_TRACE_PRINT_INFO
-        myRaytraceShader->FetchInfoLog (theGlContext, aLog);
-
-        if (!aLog.IsEmpty())
-        {
-          std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
-        }
-#endif
         return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
       }
 
@@ -1467,14 +1451,6 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
        || !myPostFSAAProgram->Link (theGlContext)
        || !myOutImageProgram->Link (theGlContext))
       {
-#ifdef RAY_TRACE_PRINT_INFO
-        myRaytraceProgram->FetchInfoLog (theGlContext, aLog);
-
-        if (!aLog.IsEmpty())
-        {
-          std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
-        }
-#endif
         return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
       }
     }
@@ -1752,6 +1728,10 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
         aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
       myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
+      myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
+        aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
+      myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
+        aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
 
       myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
         aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
@@ -1830,8 +1810,10 @@ void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlC
     nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
     nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
 
-    nullifyResource (theGlContext, myRaytraceTileOffsetsTexture);
-    nullifyResource (theGlContext, myRaytraceVisualErrorTexture);
+    nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
+    nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
+    nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
+    nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
 
     nullifyResource (theGlContext, mySceneNodeInfoTexture);
     nullifyResource (theGlContext, mySceneMinPointTexture);
@@ -1876,95 +1858,76 @@ Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer
 
   if (myRaytraceParameters.AdaptiveScreenSampling)
   {
-    const Standard_Integer aSizeX = std::max (myRaytraceParameters.NbTilesX * 64, theSizeX);
-    const Standard_Integer aSizeY = std::max (myRaytraceParameters.NbTilesY * 64, theSizeY);
-
-    myRaytraceFBO1[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
-    myRaytraceFBO2[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
-
+    Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
+    myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
+    myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
     if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
     {
       myRaytraceFBO1[1]->Release (theGlContext.operator->());
       myRaytraceFBO2[1]->Release (theGlContext.operator->());
     }
   }
-  else // non-adaptive mode
+
+  for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
   {
-    if (myRaytraceFBO1[0]->GetSizeX() != theSizeX
-     || myRaytraceFBO1[0]->GetSizeY() != theSizeY)
+    if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
     {
-      myAccumFrames = 0; // accumulation should be restarted
+      myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
+      myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
+      myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
     }
 
-    myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
-    myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
-
-    // Init second set of buffers for stereographic rendering
-    if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
-    {
-      myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
-      myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
-    }
-    else if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
+    if (aViewIter == 1
+     && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
     {
       myRaytraceFBO1[1]->Release (theGlContext.operator->());
       myRaytraceFBO2[1]->Release (theGlContext.operator->());
+      myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
+      myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
+      myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
+      continue;
     }
-  }
-
-  myTileSampler.SetSize (theSizeX, theSizeY);
-
-  if (myRaytraceTileOffsetsTexture.IsNull())
-  {
-    myRaytraceOutputTexture[0] = new OpenGl_Texture();
-    myRaytraceOutputTexture[1] = new OpenGl_Texture();
 
-    myRaytraceTileOffsetsTexture = new OpenGl_Texture();
-    myRaytraceVisualErrorTexture = new OpenGl_Texture();
-  }
-
-  if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
-   || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
-  {
-    myAccumFrames = 0;
-
-    // Due to limitations of OpenGL image load-store extension
-    // atomic operations are supported only for single-channel
-    // images, so we define GL_R32F image. It is used as array
-    // of 6D floating point vectors:
-    // 0 - R color channel
-    // 1 - G color channel
-    // 2 - B color channel
-    // 3 - hit time transformed into OpenGL NDC space
-    // 4 - luminance accumulated for odd samples only
-    myRaytraceOutputTexture[0]->InitRectangle (theGlContext,
-      theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
-
-    // workaround for some NVIDIA drivers
-    myRaytraceVisualErrorTexture->Release (theGlContext.operator->());
-    myRaytraceTileOffsetsTexture->Release (theGlContext.operator->());
+    if (myRaytraceParameters.AdaptiveScreenSampling)
+    {
+      if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
+       && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
+       && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
+       && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
+      {
+        continue;
+      }
 
-    myRaytraceVisualErrorTexture->Init (theGlContext,
-      GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
+      myAccumFrames = 0;
 
-    myRaytraceTileOffsetsTexture->Init (theGlContext,
-      GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
-  }
+      // Due to limitations of OpenGL image load-store extension
+      // atomic operations are supported only for single-channel
+      // images, so we define GL_R32F image. It is used as array
+      // of 6D floating point vectors:
+      // 0 - R color channel
+      // 1 - G color channel
+      // 2 - B color channel
+      // 3 - hit time transformed into OpenGL NDC space
+      // 4 - luminance accumulated for odd samples only
+      myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
+
+      // workaround for some NVIDIA drivers
+      myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
+      myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext, GL_R32I, GL_RED_INTEGER, GL_INT,
+                                                     myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
+    }
+    else // non-adaptive mode
+    {
+      if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
+       || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
+      {
+        myAccumFrames = 0; // accumulation should be restarted
+      }
 
-  if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
-  {
-    if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
-     || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
-    {
-      myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
-        theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
+      myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
+      myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
     }
   }
-  else
-  {
-    myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
-  }
-
   return Standard_True;
 }
 
@@ -1994,7 +1957,7 @@ void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
     {
       OpenGl_Vec4 aOrigin (GLfloat(aX),
                            GLfloat(aY),
-                          -1.0f,
+                           -1.0f,
                            1.0f);
 
       aOrigin = theUnview * aOrigin;
@@ -2027,6 +1990,79 @@ void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
   }
 }
 
+// =======================================================================
+// function : updatePerspCameraPT
+// purpose  : Generates viewing rays (path tracing, perspective camera)
+// =======================================================================
+void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4&           theOrientation,
+                                       const OpenGl_Mat4&           theViewMapping,
+                                       Graphic3d_Camera::Projection theProjection,
+                                       OpenGl_Mat4&                 theViewPr,
+                                       OpenGl_Mat4&                 theUnview,
+                                       const int                    theWinSizeX,
+                                       const int                    theWinSizeY)
+{
+  // compute view-projection matrix
+  theViewPr = theViewMapping * theOrientation;
+
+  // compute inverse view-projection matrix
+  theViewPr.Inverted(theUnview);
+  
+  // get camera stereo params
+  float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
+    ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
+    : static_cast<float> (myCamera->IOD());
+
+  float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
+    ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
+    : static_cast<float> (myCamera->ZFocus());
+
+  // get camera view vectors
+  const gp_Pnt anOrig = myCamera->Eye();
+
+  myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
+                           static_cast<float> (anOrig.Y()),
+                           static_cast<float> (anOrig.Z()));
+
+  const gp_Dir aView = myCamera->Direction();
+
+  OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
+                                           static_cast<float> (aView.Y()),
+                                           static_cast<float> (aView.Z()));
+
+  const gp_Dir anUp = myCamera->Up();
+
+  myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
+                           static_cast<float> (anUp.Y()),
+                           static_cast<float> (anUp.Z()));
+
+  myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
+
+  const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
+  const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
+  myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
+                           static_cast<float> (aScaleY));
+
+  if (theProjection == Graphic3d_Camera::Projection_Perspective)
+  {
+    myEyeView = anEyeViewMono;
+  }
+  else // stereo camera
+  {
+    // compute z-focus point
+    OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
+
+    // compute stereo camera shift
+    float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
+    myEyeOrig += myEyeSide.Normalized() * aDx;
+
+    // estimate new camera direction vector and correct its length
+    myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
+    myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
+  }
+}
+
 // =======================================================================
 // function : uploadRaytraceData
 // purpose  : Uploads ray-trace data to the GPU
@@ -2354,68 +2390,75 @@ Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)&
 // =======================================================================
 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
 {
-  std::vector<OpenGl_Light> aLightSources;
-
-  if (myShadingModel != Graphic3d_TOSM_NONE)
+  std::vector<Handle(Graphic3d_CLight)> aLightSources;
+  myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
+  if (myShadingModel != Graphic3d_TOSM_UNLIT
+  && !myLights.IsNull())
   {
-    aLightSources.assign (myLights.begin(), myLights.end());
+    const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
+    myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
 
     // move positional light sources at the front of the list
-    std::partition (aLightSources.begin(), aLightSources.end(), IsLightPositional());
+    aLightSources.reserve (myLights->Extent());
+    for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
+         aLightIter.More(); aLightIter.Next())
+    {
+      const Graphic3d_CLight& aLight = *aLightIter.Value();
+      if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
+      {
+        aLightSources.push_back (aLightIter.Value());
+      }
+    }
+
+    for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
+         aLightIter.More(); aLightIter.Next())
+    {
+      if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
+      {
+        aLightSources.push_back (aLightIter.Value());
+      }
+    }
   }
 
   // get number of 'real' (not ambient) light sources
-  const size_t aNbLights = std::count_if (aLightSources.begin(), aLightSources.end(), IsNotAmbient());
-
+  const size_t aNbLights = aLightSources.size();
   Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
-
   if (wasUpdated)
   {
     myRaytraceGeometry.Sources.resize (aNbLights);
   }
 
-  myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
-
   for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
   {
-    const OpenGl_Light& aLight = aLightSources[aLightIdx];
-
-    if (aLight.Type == Graphic3d_TOLS_AMBIENT)
-    {
-      myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r() * aLight.Intensity,
-                                               aLight.Color.g() * aLight.Intensity,
-                                               aLight.Color.b() * aLight.Intensity,
-                                               0.0f);
-      continue;
-    }
-
-    BVH_Vec4f aEmission  (aLight.Color.r() * aLight.Intensity,
-                          aLight.Color.g() * aLight.Intensity,
-                          aLight.Color.b() * aLight.Intensity,
+    const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
+    const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
+    BVH_Vec4f aEmission  (aLightColor.r() * aLight.Intensity(),
+                          aLightColor.g() * aLight.Intensity(),
+                          aLightColor.b() * aLight.Intensity(),
                           1.0f);
 
-    BVH_Vec4f aPosition (-aLight.Direction.x(),
-                         -aLight.Direction.y(),
-                         -aLight.Direction.z(),
+    BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
+                         -aLight.PackedDirection().y(),
+                         -aLight.PackedDirection().z(),
                          0.0f);
 
-    if (aLight.Type != Graphic3d_TOLS_DIRECTIONAL)
+    if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
     {
-      aPosition = BVH_Vec4f (static_cast<float>(aLight.Position.x()),
-                             static_cast<float>(aLight.Position.y()),
-                             static_cast<float>(aLight.Position.z()),
+      aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
+                             static_cast<float>(aLight.Position().Y()),
+                             static_cast<float>(aLight.Position().Z()),
                              1.0f);
 
       // store smoothing radius in W-component
-      aEmission.w() = Max (aLight.Smoothness, 0.f);
+      aEmission.w() = Max (aLight.Smoothness(), 0.f);
     }
     else
     {
       // store cosine of smoothing angle in W-component
-      aEmission.w() = cosf (Min (Max (aLight.Smoothness, 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
+      aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
     }
 
-    if (aLight.IsHeadlight)
+    if (aLight.IsHeadlight())
     {
       aPosition = theInvModelView * aPosition;
     }
@@ -2463,6 +2506,7 @@ Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& the
 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        theProgramId,
                                                const Standard_Integer        theWinSizeX,
                                                const Standard_Integer        theWinSizeY,
+                                               Graphic3d_Camera::Projection  theProjection,
                                                const Handle(OpenGl_Context)& theGlContext)
 {
   // Get projection state
@@ -2473,12 +2517,26 @@ Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        the
   OpenGl_Vec3 aOrigins[4];
   OpenGl_Vec3 aDirects[4];
 
-  updateCamera (myCamera->OrientationMatrixF(),
-                aCntxProjectionState.Current(),
-                aOrigins,
-                aDirects,
-                aViewPrjMat,
-                anUnviewMat);
+  if (myCamera->IsOrthographic()
+   || !myRenderParams.IsGlobalIlluminationEnabled)
+  {
+    updateCamera (myCamera->OrientationMatrixF(),
+                  aCntxProjectionState.Current(),
+                  aOrigins,
+                  aDirects,
+                  aViewPrjMat,
+                  anUnviewMat);
+  }
+  else
+  {
+    updatePerspCameraPT (myCamera->OrientationMatrixF(),
+                         aCntxProjectionState.Current(),
+                         theProjection,
+                         aViewPrjMat,
+                         anUnviewMat,
+                         theWinSizeX,
+                         theWinSizeY);
+  }
 
   Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
                                            ? myRaytraceProgram
@@ -2488,7 +2546,16 @@ Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        the
   {
     return Standard_False;
   }
-
+  
+  theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
+  theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
+  theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
+  theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
+  theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
+
+  theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
+  theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
+  
   // Set camera state
   theProgram->SetUniform (theGlContext,
     myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
@@ -2558,8 +2625,10 @@ Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        the
   }
 
   // Set environment map parameters
-  const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull() || !myTextureEnv->IsValid();
-  
+  const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
+                                               ||  myTextureEnv->IsEmpty()
+                                               || !myTextureEnv->First()->IsValid();
+
   theProgram->SetUniform (theGlContext,
     myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
 
@@ -2604,38 +2673,41 @@ Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        the
 // function : bindRaytraceTextures
 // purpose  : Binds ray-trace textures to corresponding texture units
 // =======================================================================
-void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
+void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
+                                        int theStereoView)
 {
-  if (myRaytraceParameters.AdaptiveScreenSampling)
+  if (myRaytraceParameters.AdaptiveScreenSampling
+   && myRaytraceParameters.GlobalIllumination)
   {
   #if !defined(GL_ES_VERSION_2_0)
-    theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft,
-      myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
-    theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh,
-      myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
-
+    theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
+                                              myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
     theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
-      myRaytraceVisualErrorTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
+                                              myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
     theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
-      myRaytraceTileOffsetsTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
+                                              myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
+  #else
+    (void )theStereoView;
   #endif
   }
 
-  if (!myTextureEnv.IsNull() && myTextureEnv->IsValid())
+  if (!myTextureEnv.IsNull()
+   && !myTextureEnv->IsEmpty()
+   &&  myTextureEnv->First()->IsValid())
   {
-    myTextureEnv->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
+    myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
   }
 
-  mySceneMinPointTexture->BindTexture    (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
-  mySceneMaxPointTexture->BindTexture    (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
-  mySceneNodeInfoTexture->BindTexture    (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
-  myGeometryVertexTexture->BindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
-  myGeometryNormalTexture->BindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
-  myGeometryTexCrdTexture->BindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
-  myGeometryTriangTexture->BindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
-  mySceneTransformTexture->BindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
-  myRaytraceMaterialTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
-  myRaytraceLightSrcTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
+  mySceneMinPointTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
+  mySceneMaxPointTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
+  mySceneNodeInfoTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
+  myGeometryVertexTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
+  myGeometryNormalTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
+  myGeometryTexCrdTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
+  myGeometryTriangTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
+  mySceneTransformTexture  ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
+  myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
+  myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
 }
 
 // =======================================================================
@@ -2644,16 +2716,16 @@ void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlConte
 // =======================================================================
 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
 {
-  mySceneMinPointTexture->UnbindTexture    (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
-  mySceneMaxPointTexture->UnbindTexture    (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
-  mySceneNodeInfoTexture->UnbindTexture    (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
-  myGeometryVertexTexture->UnbindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
-  myGeometryNormalTexture->UnbindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
-  myGeometryTexCrdTexture->UnbindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
-  myGeometryTriangTexture->UnbindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
-  mySceneTransformTexture->UnbindTexture   (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
-  myRaytraceMaterialTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
-  myRaytraceLightSrcTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
+  mySceneMinPointTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
+  mySceneMaxPointTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
+  mySceneNodeInfoTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
+  myGeometryVertexTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
+  myGeometryNormalTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
+  myGeometryTexCrdTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
+  myGeometryTriangTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
+  mySceneTransformTexture  ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
+  myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
+  myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
 
   theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
 }
@@ -2673,11 +2745,13 @@ Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer
   aResult &= setUniformState (0,
                               theSizeX,
                               theSizeY,
+                              theProjection,
                               theGlContext);
 
   if (myRaytraceParameters.GlobalIllumination) // path tracing
   {
-    aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
+    aResult &= runPathtrace    (theSizeX, theSizeY, theProjection, theGlContext);
+    aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
   }
   else // Whitted-style ray-tracing
   {
@@ -2699,13 +2773,9 @@ Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSize
 {
   Standard_Boolean aResult = Standard_True;
 
-  bindRaytraceTextures (theGlContext);
-
-  Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
-  Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
-
   // Choose proper set of frame buffers for stereo rendering
-  const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
+  const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
+  bindRaytraceTextures (theGlContext, aFBOIdx);
 
   if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
   {
@@ -2721,13 +2791,14 @@ Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSize
     glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
 
     // bind ray-tracing output image as input
-    myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
+    myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
 
     aResult &= theGlContext->BindProgram (myPostFSAAProgram);
 
     aResult &= setUniformState (1 /* FSAA ID */,
                                 theSizeX,
                                 theSizeY,
+                                theProjection,
                                 theGlContext);
 
     // Perform multi-pass adaptive FSAA using ping-pong technique.
@@ -2771,11 +2842,11 @@ Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSize
       // perform adaptive FSAA pass
       theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
 
-      aFramebuffer->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
+      aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
     }
 
-    aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
-    aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
+    const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
+    const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
 
     glEnable (GL_DEPTH_TEST);
 
@@ -2791,20 +2862,14 @@ Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSize
       aRenderImageFramebuffer->UnbindBuffer (theGlContext);
     }
 
-    aRenderImageFramebuffer->ColorTexture()->Bind (
-      theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
-
-    aDepthSourceFramebuffer->DepthStencilTexture()->Bind (
-      theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
+    aRenderImageFramebuffer->ColorTexture()       ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
+    aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
 
     // copy the output image with depth values
     theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
 
-    aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (
-      theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
-
-    aRenderImageFramebuffer->ColorTexture()->Unbind (
-      theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
+    aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
+    aRenderImageFramebuffer->ColorTexture()       ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
   }
 
   unbindRaytraceTextures (theGlContext);
@@ -2821,117 +2886,113 @@ Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSize
 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer              theSizeX,
                                             const Standard_Integer              theSizeY,
                                             const Graphic3d_Camera::Projection  theProjection,
-                                            OpenGl_FrameBuffer*                 theReadDrawFbo,
                                             const Handle(OpenGl_Context)&       theGlContext)
 {
-  Standard_Boolean aResult = Standard_True;
-
   if (myToUpdateEnvironmentMap) // check whether the map was changed
   {
     myAccumFrames = myToUpdateEnvironmentMap = 0;
   }
+  
+  if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
+   || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
+  {
+    myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
+    myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
+    myAccumFrames = 0;
+  }
+
+  // Choose proper set of frame buffers for stereo rendering
+  const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
 
   if (myRaytraceParameters.AdaptiveScreenSampling)
   {
     if (myAccumFrames == 0)
     {
       myTileSampler.Reset(); // reset tile sampler to its initial state
-    }
 
-    // Adaptive sampling is starting at the second frame
-    myTileSampler.Upload (theGlContext,
-                          myRaytraceTileOffsetsTexture,
-                          myRaytraceParameters.NbTilesX,
-                          myRaytraceParameters.NbTilesY,
-                          myAccumFrames > 0);
-  }
-
-  bindRaytraceTextures (theGlContext);
+      // Adaptive sampling is starting at the second frame
+      myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
 
-  Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
-  Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
-  Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
-
-  // Choose proper set of frame buffers for stereo rendering
-  const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
-
-  const Standard_Integer anImageId = (aFBOIdx != 0)
-                                   ? OpenGl_RT_OutputImageRgh
-                                   : OpenGl_RT_OutputImageLft;
+    #if !defined(GL_ES_VERSION_2_0)
+      theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
+    #endif
+    }
 
-  aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
-  anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
+    // Clear adaptive screen sampling images
+  #if !defined(GL_ES_VERSION_2_0)
+    theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
+  #endif
+  }
 
-  aDepthSourceFramebuffer = aRenderImageFramebuffer;
+  bindRaytraceTextures (theGlContext, aFBOIdx);
 
-  anAccumImageFramebuffer->ColorTexture()->Bind (
-    theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
+  const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
+  anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
 
-  aRenderImageFramebuffer->BindBuffer (theGlContext);
+  // Set frame accumulation weight
+  myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
 
+  // Set random number generator seed
   if (myAccumFrames == 0)
   {
     myRNG.SetSeed(); // start RNG from beginning
   }
+  myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
 
-  // Clear adaptive screen sampling images
+  // Set image uniforms for render program
   if (myRaytraceParameters.AdaptiveScreenSampling)
   {
-  #if !defined(GL_ES_VERSION_2_0)
-    if (myAccumFrames == 0)
-    {
-      theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
-    }
-
-    theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
-  #endif
+    myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
+    myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
+    myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
   }
 
-  // Set frame accumulation weight
-  myRaytraceProgram->SetUniform (theGlContext,
-    myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
-
-  // Set random number generator seed
-  myRaytraceProgram->SetUniform (theGlContext,
-    myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
-
-  // Set image uniforms for render program
-  myRaytraceProgram->SetUniform (theGlContext,
-    myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId);
-  myRaytraceProgram->SetUniform (theGlContext,
-    myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
-
-  glDisable (GL_DEPTH_TEST);
-
-  if (myRaytraceParameters.AdaptiveScreenSampling && myAccumFrames > 0)
+  const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
+  aRenderImageFramebuffer->BindBuffer (theGlContext);
+  if (myRaytraceParameters.AdaptiveScreenSampling)
   {
-    glViewport (0,
-                0,
-                myTileSampler.TileSize() * myRaytraceParameters.NbTilesX,
-                myTileSampler.TileSize() * myRaytraceParameters.NbTilesY);
+    // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
+    // redirected to inner tiles (full tile size) are drawn entirely
+    const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
+    glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
   }
 
   // Generate for the given RNG seed
+  glDisable (GL_DEPTH_TEST);
   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
 
-  if (myRaytraceParameters.AdaptiveScreenSampling && myAccumFrames > 0)
+  aRenderImageFramebuffer->UnbindBuffer (theGlContext);
+
+  if (myRaytraceParameters.AdaptiveScreenSampling)
   {
-    glViewport (0,
-                0,
-                theSizeX,
-                theSizeY);
+    glViewport (0, 0, theSizeX, theSizeY);
   }
+  return true;
+}
 
+// =======================================================================
+// function : runPathtraceOut
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection  theProjection,
+                                               OpenGl_FrameBuffer*                 theReadDrawFbo,
+                                               const Handle(OpenGl_Context)&       theGlContext)
+{
   // Output accumulated path traced image
   theGlContext->BindProgram (myOutImageProgram);
 
+  // Choose proper set of frame buffers for stereo rendering
+  const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
+
   if (myRaytraceParameters.AdaptiveScreenSampling)
   {
     // Set uniforms for display program
-    myOutImageProgram->SetUniform (theGlContext, "uRenderImage",   anImageId);
+    myOutImageProgram->SetUniform (theGlContext, "uRenderImage",   OpenGl_RT_OutputImage);
     myOutImageProgram->SetUniform (theGlContext, "uAccumFrames",   myAccumFrames);
     myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
     myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ?  1 : 0);
+    myOutImageProgram->SetUniform (theGlContext, "uTileSize",      myTileSampler.TileSize());
+    myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
   }
 
   if (myRaytraceParameters.GlobalIllumination)
@@ -2951,36 +3012,26 @@ Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer
   {
     theReadDrawFbo->BindBuffer (theGlContext);
   }
-  else
-  {
-    aRenderImageFramebuffer->UnbindBuffer (theGlContext);
-  }
 
-  aRenderImageFramebuffer->ColorTexture()->Bind (
-    theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
-
-  glEnable (GL_DEPTH_TEST);
+  const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
+  aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
 
   // Copy accumulated image with correct depth values
+  glEnable (GL_DEPTH_TEST);
   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
 
-  aRenderImageFramebuffer->ColorTexture()->Unbind (
-    theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
+  aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
 
   if (myRaytraceParameters.AdaptiveScreenSampling)
   {
-    myRaytraceVisualErrorTexture->Bind (theGlContext);
-
-    // Download visual error map from the GPU and build
-    // adjusted tile offsets for optimal image sampling
-    myTileSampler.GrabVarianceMap (theGlContext);
+    // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
+    myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
+    myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
   }
 
   unbindRaytraceTextures (theGlContext);
-
   theGlContext->BindProgram (NULL);
-
-  return aResult;
+  return true;
 }
 
 // =======================================================================
@@ -2993,7 +3044,7 @@ Standard_Boolean OpenGl_View::raytrace (const Standard_Integer        theSizeX,
                                         OpenGl_FrameBuffer*           theReadDrawFbo,
                                         const Handle(OpenGl_Context)& theGlContext)
 {
-  if (!initRaytraceResources (theGlContext))
+  if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
   {
     return Standard_False;
   }