0031279: Visualization, TKOpenGl - environment background is misplaced within Ray...
[occt.git] / src / OpenGl / OpenGl_View_Raytrace.cxx
index ba286a2..c42998f 100644 (file)
@@ -28,8 +28,7 @@
 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
 #include "../Shaders/Shaders_Display_fs.pxx"
-
-using namespace OpenGl_Raytrace;
+#include "../Shaders/Shaders_TangentSpaceNormal_glsl.pxx"
 
 //! Use this macro to output ray-tracing debug info
 // #define RAY_TRACE_PRINT_INFO
@@ -42,24 +41,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_EnvMapTexture = 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;
 }
 
 // =======================================================================
@@ -101,15 +106,20 @@ Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode
   // of changes in OpenGL scene (only for path tracing)
   std::set<Standard_Integer> aNonRaytraceIDs;
 
-  const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
-
-  if (aLayer.NbStructures() != 0)
+  for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
   {
-    const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
+    const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
+    if (aLayer->NbStructures() == 0
+    || !aLayer->LayerSettings().IsRaytracable()
+    ||  aLayer->LayerSettings().IsImmediate())
+    {
+      continue;
+    }
 
+    const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
     for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
     {
-      for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
+      for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
       {
         const OpenGl_Structure* aStructure = aStructIt.Value();
 
@@ -289,6 +299,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();
@@ -334,115 +348,123 @@ void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BV
 // function : convertMaterial
 // purpose  : Creates ray-tracing material properties
 // =======================================================================
-OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace*      theAspect,
+OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
                                                       const Handle(OpenGl_Context)& theGlContext)
 {
-  OpenGl_RaytraceMaterial theMaterial;
+  OpenGl_RaytraceMaterial aResMat;
 
   const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
   const OpenGl_Vec3& aMatCol  = theAspect->Aspect()->InteriorColor();
   const float        aShine   = 128.0f * float(aSrcMat.Shininess());
-  const bool         isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC) == Standard_True;
 
-  // ambient component
-  if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
+  const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
+  const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
+  const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
+  const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
+  switch (aSrcMat.MaterialType())
   {
-    const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol;
-    theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(),  1.0f);
-  }
-  else
-  {
-    theMaterial.Ambient = THE_BLACK_COLOR;
-  }
-
-  // diffusion component
-  if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
-  {
-    const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol;
-    theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture
-  }
-  else
-  {
-    theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f);
+    case Graphic3d_MATERIAL_ASPECT:
+    {
+      aResMat.Ambient .SetValues (aSrcAmb * aMatCol,  1.0f);
+      aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
+      aResMat.Emission.SetValues (aSrcEms * aMatCol,  1.0f);
+      break;
+    }
+    case Graphic3d_MATERIAL_PHYSIC:
+    {
+      aResMat.Ambient .SetValues (aSrcAmb,  1.0f);
+      aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
+      aResMat.Emission.SetValues (aSrcEms,  1.0f);
+      break;
+    }
   }
 
-  // specular component
-  if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
   {
-    const OpenGl_Vec3& aSrcSpe  = aSrcMat.SpecularColor();
-    const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb();
-    theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine);
-
-    const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
-                                        Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
-                                             theMaterial.Diffuse.z() + theMaterial.Specular.z()));
-
+    // interior color is always ignored for Specular
+    aResMat.Specular.SetValues (aSrcSpe, aShine);
+    const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
+                                        Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
+                                             aResMat.Diffuse.z() + aResMat.Specular.z()));
     const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
-
-    // ignore isPhysic here
-    theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f);
-  }
-  else
-  {
-    theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine);
-  }
-
-  // emission component
-  if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION))
-  {
-    const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol;
-    theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f);
-  }
-  else
-  {
-    theMaterial.Emission = THE_BLACK_COLOR;
+    aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
   }
 
   const float anIndex = (float )aSrcMat.RefractionIndex();
-  theMaterial.Transparency = BVH_Vec4f (1.0f - (float )aSrcMat.Transparency(),
-                                        (float )aSrcMat.Transparency(),
-                                        anIndex == 0 ? 1.0f : anIndex,
-                                        anIndex == 0 ? 1.0f : 1.0f / anIndex);
+  aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
+                                    anIndex == 0 ? 1.0f : anIndex,
+                                    anIndex == 0 ? 1.0f : 1.0f / anIndex);
+
+  aResMat.Ambient  = theGlContext->Vec4FromQuantityColor (aResMat.Ambient);
+  aResMat.Diffuse  = theGlContext->Vec4FromQuantityColor (aResMat.Diffuse);
+  aResMat.Specular = theGlContext->Vec4FromQuantityColor (aResMat.Specular);
+  aResMat.Emission = theGlContext->Vec4FromQuantityColor (aResMat.Emission);
 
   // Serialize physically-based material properties
   const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
 
-  theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le,               0.f);
-  theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f /* no tex */);
-  theMaterial.BSDF.Kr = BVH_Vec4f (aBSDF.Kr,               0.f);
-  theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt,               0.f);
-  theMaterial.BSDF.Ks = BVH_Vec4f (aBSDF.Ks,   aBSDF.Roughness);
+  aResMat.BSDF.Kc = aBSDF.Kc;
+  aResMat.BSDF.Ks = aBSDF.Ks;
+  aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.0f); // no base color texture
+  aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, -1.0f); // no metallic-roughness texture
+  aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le, -1.0f); // no emissive texture
 
-  theMaterial.BSDF.Fresnel = aBSDF.Fresnel.Serialize();
+  aResMat.BSDF.Absorption = aBSDF.Absorption;
 
-  theMaterial.BSDF.Absorption = BVH_Vec4f (aBSDF.AbsorptionColor,
-                                           aBSDF.AbsorptionCoeff);
+  aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
+  aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
+  aResMat.BSDF.FresnelBase.w() = -1.0; // no normal map texture
 
   // Handle material textures
-  if (theAspect->Aspect()->ToMapTexture())
+  if (!theAspect->Aspect()->ToMapTexture())
   {
-    if (theGlContext->HasRayTracingTextures())
-    {
-      buildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
-
-      // 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.";
+    return aResMat;
+  }
 
-      theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
-        GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
+  const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
+  if (aTextureSet.IsNull()
+   || aTextureSet->IsEmpty()
+   || aTextureSet->First().IsNull())
+  {
+    return aResMat;
+  }
 
-      myIsRaytraceWarnTextures = Standard_True;
+  if (theGlContext->HasRayTracingTextures())
+  {
+    // write texture ID to diffuse w-components
+    for (OpenGl_TextureSet::Iterator aTexIter (aTextureSet); aTexIter.More(); aTexIter.Next())
+    {
+      const Handle(OpenGl_Texture)& aTexture = aTexIter.Value();
+      if (aTexIter.Unit() == Graphic3d_TextureUnit_BaseColor)
+      {
+        buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
+        aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
+      }
+      else if (aTexIter.Unit() == Graphic3d_TextureUnit_MetallicRoughness)
+      {
+        buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
+        aResMat.BSDF.Kt.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
+      }
+      else if (aTexIter.Unit() == Graphic3d_TextureUnit_Emissive)
+      {
+        buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
+        aResMat.BSDF.Le.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
+      }
+      else if (aTexIter.Unit() == Graphic3d_TextureUnit_Normal)
+      {
+        buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
+        aResMat.BSDF.FresnelBase.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
+      }
     }
   }
+  else if (!myIsRaytraceWarnTextures)
+  {
+    theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
+                               "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.");
+    myIsRaytraceWarnTextures = Standard_True;
+  }
 
-  return theMaterial;
+  return aResMat;
 }
 
 // =======================================================================
@@ -482,7 +504,7 @@ Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure*
 // =======================================================================
 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*        theStructure,
                                                  const OpenGl_RaytraceMaterial& theStructMat,
-                                                 const Handle(Geom_Transformation)& theTrsf,
+                                                 const Handle(TopLoc_Datum3D)&  theTrsf,
                                                  const Handle(OpenGl_Context)&  theGlContext)
 {
   OpenGl_Mat4 aMat4;
@@ -490,22 +512,20 @@ Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*
   {
     // Get group material
     OpenGl_RaytraceMaterial aGroupMaterial;
-    if (aGroupIter.Value()->AspectFace() != NULL)
+    if (aGroupIter.Value()->GlAspects() != NULL)
     {
-      aGroupMaterial = convertMaterial (
-        aGroupIter.Value()->AspectFace(), theGlContext);
+      aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
     }
 
     Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
 
     // Use group material if available, otherwise use structure material
-    myRaytraceGeometry.Materials.push_back (
-      aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
+    myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
 
     // Add OpenGL elements from group (extract primitives arrays and aspects)
     for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
     {
-      OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
+      OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
 
       if (anAspect != NULL)
       {
@@ -526,9 +546,7 @@ Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*
           if (aSetIter != myArrayToTrianglesMap.end())
           {
             OpenGl_TriangleSet* aSet = aSetIter->second;
-
-            BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
-
+            opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
             if (!theTrsf.IsNull())
             {
               theTrsf->Trsf().GetMat4 (aMat4);
@@ -536,7 +554,6 @@ Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*
             }
 
             aSet->SetProperties (aTransform);
-
             if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
             {
               aSet->SetMaterialIndex (aMatID);
@@ -544,13 +561,9 @@ Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*
           }
           else
           {
-            NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
-              addRaytracePrimitiveArray (aPrimArray, aMatID, 0);
-
-            if (!aSet.IsNull())
+            if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
             {
-              BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
-
+              opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
               if (!theTrsf.IsNull())
               {
                 theTrsf->Trsf().GetMat4 (aMat4);
@@ -558,7 +571,6 @@ Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*
               }
 
               aSet->SetProperties (aTransform);
-
               myRaytraceGeometry.Objects().Append (aSet);
             }
           }
@@ -574,9 +586,9 @@ Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*
 // function : addRaytracePrimitiveArray
 // purpose  : Adds OpenGL primitive array to ray-traced scene geometry
 // =======================================================================
-OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
-                                                            const Standard_Integer       theMaterial,
-                                                            const OpenGl_Mat4*           theTransform)
+Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
+                                                                   const Standard_Integer       theMaterial,
+                                                                   const OpenGl_Mat4*           theTransform)
 {
   const Handle(Graphic3d_BoundBuffer)& aBounds   = theArray->Bounds();
   const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
@@ -590,11 +602,10 @@ OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_Primiti
   #endif
    || anAttribs.IsNull())
   {
-    return NULL;
+    return Handle(OpenGl_TriangleSet)();
   }
 
   OpenGl_Mat4 aNormalMatrix;
-
   if (theTransform != NULL)
   {
     Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
@@ -603,7 +614,7 @@ OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_Primiti
     aNormalMatrix.Transpose();
   }
 
-  OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
+  Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
   {
     aSet->Vertices.reserve (anAttribs->NbElements);
     aSet->Normals.reserve  (anAttribs->NbElements);
@@ -611,53 +622,42 @@ OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_Primiti
 
     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));
         }
       }
     }
@@ -708,8 +708,8 @@ OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_Primiti
 
         if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
         {
-          delete aSet;
-          return NULL;
+          aSet.Nullify();
+          return Handle(OpenGl_TriangleSet)();
         }
 
         aBoundStart += aVertNum;
@@ -721,8 +721,8 @@ OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_Primiti
 
       if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
       {
-        delete aSet;
-        return NULL;
+        aSet.Nullify();
+        return Handle(OpenGl_TriangleSet)();
       }
     }
   }
@@ -1122,6 +1122,10 @@ TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_C
   {
     aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
   }
+  if (!theGlContext->ToRenderSRGB())
+  {
+    aPrefixString += TCollection_AsciiString ("\n#define THE_SHIFT_sRGB");
+  }
 
   // If OpenGL driver supports bindless textures and texturing
   // is actually used, activate texturing in ray-tracing mode
@@ -1137,11 +1141,14 @@ TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_C
 
     if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
     {
-      // 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"))
+      if (theGlContext->IsGlGreaterEqual (4, 4))
       {
-        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");
+        if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
+         && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
+        {
+          aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
+        }
       }
     }
 
@@ -1149,6 +1156,30 @@ TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_C
     {
       aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
     }
+
+    switch (myRaytraceParameters.ToneMappingMethod)
+    {
+      case Graphic3d_ToneMappingMethod_Disabled:
+        break;
+      case Graphic3d_ToneMappingMethod_Filmic:
+        aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
+        break;
+    }
+  }
+
+  if (myRaytraceParameters.ToIgnoreNormalMap)
+  {
+    aPrefixString += TCollection_AsciiString("\n#define IGNORE_NORMAL_MAP");
+  }
+
+  if (myRaytraceParameters.CubemapForBack)
+  {
+    aPrefixString += TCollection_AsciiString("\n#define BACKGROUND_CUBEMAP");
+  }
+
+  if (myRaytraceParameters.DepthOfField)
+  {
+    aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
   }
 
   return aPrefixString;
@@ -1180,71 +1211,20 @@ Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum
                                                      const Handle(OpenGl_Context)& theGlContext)
 {
   Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
-
   if (!aShader->Create (theGlContext))
   {
-    const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
-      (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
-
-    theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
-      GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
-
-    aShader->Release (theGlContext.operator->());
-
+    theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
+                               TCollection_ExtendedString ("Error: Failed to create ") +
+                               (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
+    aShader->Release (theGlContext.get());
     return Handle(OpenGl_ShaderObject)();
   }
 
-  if (!aShader->LoadSource (theGlContext, theSource.Source()))
+  if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source()))
   {
-    const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
-      (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
-
-    theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
-      GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
-
-    aShader->Release (theGlContext.operator->());
-
+    aShader->Release (theGlContext.get());
     return Handle(OpenGl_ShaderObject)();
   }
-
-  TCollection_AsciiString aBuildLog;
-
-  if (!aShader->Compile (theGlContext))
-  {
-    aShader->FetchInfoLog (theGlContext, aBuildLog);
-
-    const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
-      (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
-
-    theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
-      GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
-
-    aShader->Release (theGlContext.operator->());
-
-#ifdef RAY_TRACE_PRINT_INFO
-    std::cout << "Shader build log:\n" << aBuildLog << "\n";
-#endif
-
-    return Handle(OpenGl_ShaderObject)();
-  }
-  else if (theGlContext->caps->glslWarnings)
-  {
-    aShader->FetchInfoLog (theGlContext, aBuildLog);
-
-    if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
-    {
-      const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
-        "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
-
-      theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
-        GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
-    }
-
-#ifdef RAY_TRACE_PRINT_INFO
-    std::cout << "Shader build log:\n" << aBuildLog << "\n";
-#endif
-  }
-
   return aShader;
 }
 
@@ -1254,9 +1234,11 @@ Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum
 // =======================================================================
 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)&      theGlContext,
                                                        const Handle(OpenGl_ShaderObject)& theVertShader,
-                                                       const Handle(OpenGl_ShaderObject)& theFragShader)
+                                                       const Handle(OpenGl_ShaderObject)& theFragShader,
+                                                       const TCollection_AsciiString& theName)
 {
-  Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
+  const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
+  Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
 
   if (!aProgram->Create (theGlContext))
   {
@@ -1315,7 +1297,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)
   {
@@ -1363,20 +1347,23 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
      || myRenderParams.IsTransparentShadowEnabled  != myRaytraceParameters.TransparentShadows
      || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
      || myRenderParams.TwoSidedBsdfModels          != myRaytraceParameters.TwoSidedBsdfModels
-     || myRaytraceGeometry.HasTextures()           != myRaytraceParameters.UseBindlessTextures)
+     || myRaytraceGeometry.HasTextures()           != myRaytraceParameters.UseBindlessTextures
+     || myRenderParams.ToIgnoreNormalMapInRayTracing != myRaytraceParameters.ToIgnoreNormalMap)
     {
       myRaytraceParameters.NbBounces           = myRenderParams.RaytracingDepth;
       myRaytraceParameters.TransparentShadows  = myRenderParams.IsTransparentShadowEnabled;
       myRaytraceParameters.GlobalIllumination  = myRenderParams.IsGlobalIlluminationEnabled;
       myRaytraceParameters.TwoSidedBsdfModels  = myRenderParams.TwoSidedBsdfModels;
       myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
-
+      myRaytraceParameters.ToIgnoreNormalMap     = myRenderParams.ToIgnoreNormalMapInRayTracing;
       aToRebuildShaders = Standard_True;
     }
 
-    if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
+    if (myRenderParams.AdaptiveScreenSampling       != myRaytraceParameters.AdaptiveScreenSampling
+     || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
     {
-      myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
+      myRaytraceParameters.AdaptiveScreenSampling       = myRenderParams.AdaptiveScreenSampling;
+      myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
       if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
       {
         if (!theGlContext->HasRayTracingAdaptiveSampling())
@@ -1384,12 +1371,41 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
           // disable the feature if it is not supported
           myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
           theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
-                                     "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
+                                     "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
+        }
+        else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
+             && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
+        {
+          // disable the feature if it is not supported
+          myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
+          theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
+                                     "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
         }
       }
 
       aToRebuildShaders = Standard_True;
     }
+    myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
+
+    const bool isCubemapForBack = !myBackgroundCubeMap.IsNull();
+    if (myRaytraceParameters.CubemapForBack != isCubemapForBack)
+    {
+      myRaytraceParameters.CubemapForBack = isCubemapForBack;
+      aToRebuildShaders = Standard_True;
+    }
+
+    const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
+    if (myRaytraceParameters.DepthOfField != toEnableDof)
+    {
+      myRaytraceParameters.DepthOfField = toEnableDof;
+      aToRebuildShaders = Standard_True;
+    }
+
+    if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
+    {
+      myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
+      aToRebuildShaders = true;
+    }
 
     if (aToRebuildShaders)
     {
@@ -1409,27 +1425,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()))
+      if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source())
+       || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source())
+       || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), 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))
-      {
-#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);
       }
 
@@ -1441,14 +1440,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);
       }
     }
@@ -1507,6 +1498,7 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
       if (!aShaderFolder.IsEmpty())
       {
         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
+                                                   aShaderFolder + "/TangentSpaceNormal.glsl",
                                                    aShaderFolder + "/PathtraceBase.fs",
                                                    aShaderFolder + "/RaytraceRender.fs",
                                                    "" };
@@ -1518,6 +1510,7 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
       else
       {
         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
+                                                        Shaders_TangentSpaceNormal_glsl,
                                                         Shaders_PathtraceBase_fs,
                                                         Shaders_RaytraceRender_fs,
                                                         "" };
@@ -1537,7 +1530,7 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
         return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
       }
 
-      myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
+      myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
       if (myRaytraceProgram.IsNull())
       {
         return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
@@ -1572,7 +1565,7 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
         return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
       }
 
-      myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
+      myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
       if (myPostFSAAProgram.IsNull())
       {
         return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
@@ -1607,7 +1600,7 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
         return safeFailBack ("Failed to set display fragment shader source", theGlContext);
       }
 
-      myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
+      myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
       if (myOutImageProgram.IsNull())
       {
         return safeFailBack ("Failed to initialize display shader program", theGlContext);
@@ -1641,7 +1634,7 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
       aShaderProgram->SetSampler (theGlContext, 
         "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
       aShaderProgram->SetSampler (theGlContext,
-        "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
+        "uEnvMapTexture", OpenGl_RT_EnvMapTexture);
       aShaderProgram->SetSampler (theGlContext,
         "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
       aShaderProgram->SetSampler (theGlContext,
@@ -1705,10 +1698,10 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
         aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
       myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
         aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
-      myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
-        aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
-      myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
-        aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
+      myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnabled] =
+        aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapEnabled");
+      myUniformLocations[anIndex][OpenGl_RT_uEnvMapForBack] =
+        aShaderProgram->GetUniformLocation (theGlContext, "uEnvMapForBack");
       myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
         aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
 
@@ -1724,13 +1717,22 @@ Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context
 
       myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
         aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
+      myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
+        aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
       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");
       myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
         aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
+
+      myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
+        aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
     }
 
     theGlContext->BindProgram (myOutImageProgram);
@@ -1772,7 +1774,7 @@ inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(
 {
   if (!theResource.IsNull())
   {
-    theResource->Release (theGlContext.operator->());
+    theResource->Release (theGlContext.get());
     theResource.Nullify();
   }
 }
@@ -1793,16 +1795,20 @@ void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlC
 
   if (!theToRebuild) // complete release
   {
-    myRaytraceFBO1[0]->Release (theGlContext.operator->());
-    myRaytraceFBO1[1]->Release (theGlContext.operator->());
-    myRaytraceFBO2[0]->Release (theGlContext.operator->());
-    myRaytraceFBO2[1]->Release (theGlContext.operator->());
+    myRaytraceFBO1[0]->Release (theGlContext.get());
+    myRaytraceFBO1[1]->Release (theGlContext.get());
+    myRaytraceFBO2[0]->Release (theGlContext.get());
+    myRaytraceFBO2[1]->Release (theGlContext.get());
 
     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, myRaytraceTileSamplesTexture[0]);
+    nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
 
     nullifyResource (theGlContext, mySceneNodeInfoTexture);
     nullifyResource (theGlContext, mySceneMinPointTexture);
@@ -1821,7 +1827,7 @@ void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlC
 
     if (myRaytraceScreenQuad.IsValid ())
     {
-      myRaytraceScreenQuad.Release (theGlContext.operator->());
+      myRaytraceScreenQuad.Release (theGlContext.get());
     }
   }
 }
@@ -1845,78 +1851,97 @@ Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer
     return Standard_True;
   }
 
-  if (myRaytraceFBO1[0]->GetSizeX() != theSizeX
-   || myRaytraceFBO1[0]->GetSizeY() != theSizeY)
-  {
-    myAccumFrames = 0;
-  }
-
-  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
-  {
-    myRaytraceFBO1[1]->Release (theGlContext.operator->());
-    myRaytraceFBO2[1]->Release (theGlContext.operator->());
-  }
-
-  myTileSampler.SetSize (theSizeX, theSizeY);
-
-  if (myRaytraceTileOffsetsTexture.IsNull())
+  if (myRaytraceParameters.AdaptiveScreenSampling)
   {
-    myRaytraceOutputTexture[0] = new OpenGl_Texture();
-    myRaytraceOutputTexture[1] = new OpenGl_Texture();
-
-    myRaytraceTileOffsetsTexture = new OpenGl_Texture();
-    myRaytraceVisualErrorTexture = new OpenGl_Texture();
+    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->());
+    }
   }
 
-  if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
-   || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
+  for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
   {
-    // 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>());
+    if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
+    {
+      myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
+      myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
+      myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
+      myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
+    }
 
-    // workaround for some NVIDIA drivers
-    myRaytraceVisualErrorTexture->Release (theGlContext.operator->());
-    myRaytraceTileOffsetsTexture->Release (theGlContext.operator->());
+    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;
+    }
 
-    myRaytraceVisualErrorTexture->Init (theGlContext,
-      GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
+    if (myRaytraceParameters.AdaptiveScreenSampling)
+    {
+      if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
+       && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
+       && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
+       && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
+      {
+        if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
+        {
+          continue; // offsets texture is dynamically resized
+        }
+        else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
+              && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
+        {
+          continue;
+        }
+      }
 
-    myRaytraceTileOffsetsTexture->Init (theGlContext,
-      GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
-  }
+      myAccumFrames = 0;
 
-  if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
-  {
-    if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
-     || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
+      // 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->());
+      myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
+      myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext,
+                                                     OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
+                                                     Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
+                                                     Graphic3d_TOT_2D);
+      if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
+      {
+        myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext,
+                                                       OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
+                                                       Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
+                                                       Graphic3d_TOT_2D);
+      }
+    }
+    else // non-adaptive mode
     {
-      myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
-        theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
+      if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
+       || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
+      {
+        myAccumFrames = 0; // accumulation should be restarted
+      }
+
+      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;
 }
 
@@ -1946,7 +1971,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;
@@ -1979,6 +2004,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
@@ -2077,9 +2175,7 @@ Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)&
     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
 
-    const BVH_Transform<Standard_ShortReal, 4>* aTransform = 
-      dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
-
+    const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
     Standard_ASSERT_RETURN (aTransform != NULL,
       "OpenGl_TriangleSet does not contain transform", Standard_False);
 
@@ -2247,7 +2343,7 @@ Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)&
   if (myRaytraceGeometry.Materials.size() != 0)
   {
     aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
-      GLsizei (myRaytraceGeometry.Materials.size() * 18), myRaytraceGeometry.Materials.front().Packed());
+      GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
 
     if (!aResult)
     {
@@ -2308,68 +2404,80 @@ 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;
+  Graphic3d_Vec4 aNewAmbient (0.0f);
+  if (myShadingModel != Graphic3d_TOSM_UNLIT
+  && !myLights.IsNull())
   {
-    aLightSources.assign (myLights.begin(), myLights.end());
+    aNewAmbient.SetValues (myLights->AmbientColor().rgb(), 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());
+  if (!myRaytraceGeometry.Ambient.IsEqual (aNewAmbient))
+  {
+    myAccumFrames = 0;
+    myRaytraceGeometry.Ambient = aNewAmbient;
+  }
 
+  // get number of 'real' (not ambient) light sources
+  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.PackedDirectionRange().x(),
+                         -aLight.PackedDirectionRange().y(),
+                         -aLight.PackedDirectionRange().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;
     }
@@ -2417,6 +2525,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
@@ -2427,12 +2536,40 @@ 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);
+
+    if (myRenderParams.UseEnvironmentMapBackground
+     || myRaytraceParameters.CubemapForBack)
+    {
+      OpenGl_Mat4 aTempMat;
+      OpenGl_Mat4 aTempInvMat;
+      updatePerspCameraPT (myCamera->OrientationMatrixF(),
+                           aCntxProjectionState.Current(),
+                           theProjection,
+                           aTempMat,
+                           aTempInvMat,
+                           theWinSizeX,
+                           theWinSizeY);
+    }
+  }
+  else
+  {
+    updatePerspCameraPT (myCamera->OrientationMatrixF(),
+                         aCntxProjectionState.Current(),
+                         theProjection,
+                         aViewPrjMat,
+                         anUnviewMat,
+                         theWinSizeX,
+                         theWinSizeY);
+  }
 
   Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
                                            ? myRaytraceProgram
@@ -2442,6 +2579,15 @@ 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,
@@ -2465,38 +2611,24 @@ Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        the
   theProgram->SetUniform (theGlContext,
     myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
 
-  // Set ray-tracing intersection parameters
+  // Set screen dimensions
+  myRaytraceProgram->SetUniform (theGlContext,
+    myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
+  myRaytraceProgram->SetUniform (theGlContext,
+    myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
+
+  // Set 3D scene parameters
   theProgram->SetUniform (theGlContext,
     myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
   theProgram->SetUniform (theGlContext,
     myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
 
+  // Set light source parameters
   const Standard_Integer aLightSourceBufferSize =
     static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
-
-  // Set ray-tracing light source parameters
+  
   theProgram->SetUniform (theGlContext,
     myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
-  theProgram->SetUniform (theGlContext,
-    myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
-
-  // Enable/disable run-time rendering effects
-  theProgram->SetUniform (theGlContext,
-    myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ?  1 : 0);
-  theProgram->SetUniform (theGlContext,
-    myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ?  1 : 0);
-
-  // Set screen dimensions
-  myRaytraceProgram->SetUniform (theGlContext,
-    myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
-  myRaytraceProgram->SetUniform (theGlContext,
-    myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
-
-  if (myRenderParams.IsGlobalIlluminationEnabled) // if Monte-Carlo sampling enabled
-  {
-    theProgram->SetUniform (theGlContext,
-      myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ?  1 : 0);
-  }
 
   // Set array of 64-bit texture handles
   if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
@@ -2507,31 +2639,80 @@ Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        the
       static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
   }
 
-  // Set background colors (only gradient background supported)
-  if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
+  // Set background colors (only vertical gradient background supported)
+  OpenGl_Vec4 aBackColorTop = myBgColor, aBackColorBot = myBgColor;
+  if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
+   && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
   {
-    theProgram->SetUniform (theGlContext,
-      myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
-    theProgram->SetUniform (theGlContext,
-      myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
+    aBackColorTop = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0);
+    aBackColorBot = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1);
+
+    if (myCamera->Tile().IsValid())
+    {
+      Standard_Integer aTileOffset = myCamera->Tile().OffsetLowerLeft().y();
+      Standard_Integer aTileSize = myCamera->Tile().TileSize.y();
+      Standard_Integer aViewSize = myCamera->Tile().TotalSize.y();
+      OpenGl_Vec4 aColorRange = aBackColorTop - aBackColorBot;
+      aBackColorBot = aBackColorBot + aColorRange * ((float) aTileOffset / aViewSize);
+      aBackColorTop = aBackColorBot + aColorRange * ((float) aTileSize / aViewSize);
+    }
+  }
+  aBackColorTop = theGlContext->Vec4FromQuantityColor (aBackColorTop);
+  aBackColorBot = theGlContext->Vec4FromQuantityColor (aBackColorBot);
+  theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColorTop);
+  theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColorBot);
+
+  // Set environment map parameters
+  const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
+                                                   ? myCubeMapParams->TextureSet (theGlContext)
+                                                   : myTextureEnv;
+  const bool toDisableEnvironmentMap = anEnvTextureSet.IsNull()
+                                   ||  anEnvTextureSet->IsEmpty()
+                                   || !anEnvTextureSet->First()->IsValid();
+  theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapEnabled],
+                          toDisableEnvironmentMap ? 0 : 1);
+  if (myRaytraceParameters.CubemapForBack)
+  {
+    theProgram->SetUniform (theGlContext, "uZCoeff", myBackgroundCubeMap->ZIsInverted() ? -1 :  1);
+    theProgram->SetUniform (theGlContext, "uYCoeff", myBackgroundCubeMap->IsTopDown()   ?  1 : -1);
+    theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
+                            myBackgroundType == Graphic3d_TOB_CUBEMAP ? 1 : 0);
   }
   else
   {
-    const OpenGl_Vec4& aBackColor = myBgColor;
+    theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uEnvMapForBack],
+                            myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
+  }
 
+  // Set ambient light source
+  theProgram->SetUniform (theGlContext,
+                          myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
+  if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
+  {
     theProgram->SetUniform (theGlContext,
-      myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
+      myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
+
     theProgram->SetUniform (theGlContext,
-      myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
-  }
+      myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
 
-  const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull() || !myTextureEnv->IsValid();
-  
-  theProgram->SetUniform (theGlContext,
-    myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
+    // Check whether we should restart accumulation for run-time parameters
+    if (myRenderParams.RadianceClampingValue       != myRaytraceParameters.RadianceClampingValue
+     || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
+    {
+      myAccumFrames = 0; // accumulation should be restarted
 
-  theProgram->SetUniform (theGlContext,
-    myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ?  1 : 0);
+      myRaytraceParameters.RadianceClampingValue  = myRenderParams.RadianceClampingValue;
+      myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
+    }
+  }
+  else // RT parameters
+  {
+    // Enable/disable run-time ray-tracing effects
+    theProgram->SetUniform (theGlContext,
+      myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ?  1 : 0);
+    theProgram->SetUniform (theGlContext,
+      myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ?  1 : 0);
+  }
 
   return Standard_True;
 }
@@ -2540,38 +2721,52 @@ 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);
-    theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
-      myRaytraceTileOffsetsTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
+                                              myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
+    if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
+    {
+      theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
+                                                myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
+    }
+    else
+    {
+      theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
+                                                myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
+    }
+  #else
+    (void )theStereoView;
   #endif
   }
 
-  if (!myTextureEnv.IsNull() && myTextureEnv->IsValid())
+  const Handle(OpenGl_TextureSet)& anEnvTextureSet = myRaytraceParameters.CubemapForBack
+                                                   ? myCubeMapParams->TextureSet (theGlContext)
+                                                   : myTextureEnv;
+  if (!anEnvTextureSet.IsNull()
+   && !anEnvTextureSet->IsEmpty()
+   &&  anEnvTextureSet->First()->IsValid())
   {
-    myTextureEnv->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
+    anEnvTextureSet->First()->Bind (theGlContext, OpenGl_RT_EnvMapTexture);
   }
 
-  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);
 }
 
 // =======================================================================
@@ -2580,16 +2775,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);
 }
@@ -2609,11 +2804,13 @@ Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer
   aResult &= setUniformState (0,
                               theSizeX,
                               theSizeY,
+                              theProjection,
                               theGlContext);
 
   if (myRaytraceParameters.GlobalIllumination) // path tracing
   {
-    aResult &= runPathtrace (theProjection, theReadDrawFbo, theGlContext);
+    aResult &= runPathtrace    (theSizeX, theSizeY, theProjection, theGlContext);
+    aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
   }
   else // Whitted-style ray-tracing
   {
@@ -2635,13 +2832,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
   {
@@ -2657,13 +2850,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.
@@ -2707,11 +2901,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);
 
@@ -2727,20 +2921,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);
@@ -2754,139 +2942,194 @@ Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSize
 // function : runPathtrace
 // purpose  : Runs path tracing shader
 // =======================================================================
-Standard_Boolean OpenGl_View::runPathtrace (const Graphic3d_Camera::Projection  theProjection,
-                                            OpenGl_FrameBuffer*                 theReadDrawFbo,
+Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer              theSizeX,
+                                            const Standard_Integer              theSizeY,
+                                            const Graphic3d_Camera::Projection  theProjection,
                                             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
-    }
 
-    // We upload tile offset texture each 4 frames in order
-    // to minimize overhead of additional memory bandwidth.
-    // Adaptive sampling is starting after first 30 frames.
-    if (myAccumFrames % 4 == 0)
-    {
-      myTileSampler.Upload (theGlContext, myRaytraceTileOffsetsTexture, myAccumFrames > 30);
-    }
-  }
-
-  bindRaytraceTextures (theGlContext);
+      // Adaptive sampling is starting at the second frame
+      if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
+      {
+        myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
+      }
+      else
+      {
+        myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
+      }
 
-  Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
-  Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
-  Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
+    #if !defined(GL_ES_VERSION_2_0)
+      theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
+    #endif
+    }
 
-  // Choose proper set of frame buffers for stereo rendering
-  const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
+    // 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
+  }
 
-  const Standard_Integer anImageId = (aFBOIdx != 0)
-                                   ? OpenGl_RT_OutputImageRgh
-                                   : OpenGl_RT_OutputImageLft;
+  bindRaytraceTextures (theGlContext, aFBOIdx);
 
-  aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
-  anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
+  const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
+  anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
 
-  aDepthSourceFramebuffer = aRenderImageFramebuffer;
+  // Set frame accumulation weight
+  myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
 
-  anAccumImageFramebuffer->ColorTexture()->Bind (
-    theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
+  // Set image uniforms for render program
+  if (myRaytraceParameters.AdaptiveScreenSampling)
+  {
+    myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
+    myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage],  OpenGl_RT_TileSamplesImage);
+    myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
+    myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
+  }
 
+  const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
   aRenderImageFramebuffer->BindBuffer (theGlContext);
+  if (myRaytraceParameters.AdaptiveScreenSampling
+   && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
+  {
+    // 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);
+
+  // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
+  // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
+  //
+  // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
+  // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
+  // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
+  //
+  // Single-pass rendering is more optimal due to smaller amount of draw calls,
+  // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
+  // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
+  // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
+  const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
+                    && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
+                      ? myTileSampler.MaxTileSamples()
+                      : 1;
   if (myAccumFrames == 0)
   {
     myRNG.SetSeed(); // start RNG from beginning
   }
-
-  // Clear adaptive screen sampling images
-  if (myRaytraceParameters.AdaptiveScreenSampling)
+  for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
   {
-  #if !defined(GL_ES_VERSION_2_0)
-    if (myAccumFrames == 0)
+    myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
+    theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
+    if (myRaytraceParameters.AdaptiveScreenSampling)
     {
-      theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
+    #if !defined(GL_ES_VERSION_2_0)
+      theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
+    #endif
     }
-
-    theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
-  #endif
   }
+  aRenderImageFramebuffer->UnbindBuffer (theGlContext);
 
-  // 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);
-
-  // Generate for the given RNG seed
-  theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
+  if (myRaytraceParameters.AdaptiveScreenSampling
+   && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
+  {
+    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 (theReadDrawFbo != NULL)
+  if (myRaytraceParameters.GlobalIllumination)
   {
-    theReadDrawFbo->BindBuffer (theGlContext);
+    myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
+    switch (myRaytraceParameters.ToneMappingMethod)
+    {
+      case Graphic3d_ToneMappingMethod_Disabled:
+        break;
+      case Graphic3d_ToneMappingMethod_Filmic:
+        myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
+        break;
+    }
   }
-  else
+
+  if (theReadDrawFbo != NULL)
   {
-    aRenderImageFramebuffer->UnbindBuffer (theGlContext);
+    theReadDrawFbo->BindBuffer (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]);
+    if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
+    {
+      myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
+    }
+    else
+    {
+      myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
+    }
   }
 
   unbindRaytraceTextures (theGlContext);
-
   theGlContext->BindProgram (NULL);
-
-  return aResult;
+  return true;
 }
 
 // =======================================================================
@@ -2899,7 +3142,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;
   }