0029528: Visualization, TKOpenGl - allow defining sRGB textures
[occt.git] / src / OpenGl / OpenGl_View_Raytrace.cxx
1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <OpenGl_View.hxx>
17
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_PrimitiveArray.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OpenGl_GlCore44.hxx>
22 #include <OSD_Protection.hxx>
23 #include <OSD_File.hxx>
24
25 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30 #include "../Shaders/Shaders_Display_fs.pxx"
31
32 //! Use this macro to output ray-tracing debug info
33 // #define RAY_TRACE_PRINT_INFO
34
35 #ifdef RAY_TRACE_PRINT_INFO
36   #include <OSD_Timer.hxx>
37 #endif
38
39 namespace
40 {
41   static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
42   static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
43 }
44
45 namespace
46 {
47   //! Defines OpenGL texture samplers.
48   static const Graphic3d_TextureUnit OpenGl_RT_EnvironmentMapTexture = Graphic3d_TextureUnit_0;
49
50   static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture  = Graphic3d_TextureUnit_1;
51   static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture  = Graphic3d_TextureUnit_2;
52   static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture  = Graphic3d_TextureUnit_3;
53   static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
54
55   static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
56   static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
57   static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
58   static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
59
60   static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
61   static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
62
63   static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
64   static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
65
66   static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
67 }
68
69 // =======================================================================
70 // function : updateRaytraceGeometry
71 // purpose  : Updates 3D scene geometry for ray-tracing
72 // =======================================================================
73 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode      theMode,
74                                                       const Standard_Integer        theViewId,
75                                                       const Handle(OpenGl_Context)& theGlContext)
76 {
77   // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
78   // modifications. This is light-weight procedure performed on each frame
79   if (theMode == OpenGl_GUM_CHECK)
80   {
81     if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
82     {
83       return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
84     }
85   }
86   else if (theMode == OpenGl_GUM_PREPARE)
87   {
88     myRaytraceGeometry.ClearMaterials();
89
90     myArrayToTrianglesMap.clear();
91
92     myIsRaytraceDataValid = Standard_False;
93   }
94
95   // The set of processed structures (reflected to ray-tracing)
96   // This set is used to remove out-of-date records from the
97   // hash map of structures
98   std::set<const OpenGl_Structure*> anElements;
99
100   // Set to store all currently visible OpenGL primitive arrays
101   // applicable for ray-tracing
102   std::set<Standard_Size> anArrayIDs;
103
104   // Set to store all non-raytracable elements allowing tracking
105   // of changes in OpenGL scene (only for path tracing)
106   std::set<Standard_Integer> aNonRaytraceIDs;
107
108   for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
109   {
110     const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
111     if (aLayer->NbStructures() == 0
112     || !aLayer->LayerSettings().IsRaytracable()
113     ||  aLayer->LayerSettings().IsImmediate())
114     {
115       continue;
116     }
117
118     const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
119     for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
120     {
121       for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
122       {
123         const OpenGl_Structure* aStructure = aStructIt.Value();
124
125         if (theMode == OpenGl_GUM_CHECK)
126         {
127           if (toUpdateStructure (aStructure))
128           {
129             return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
130           }
131           else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
132           {
133             aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
134           }
135         }
136         else if (theMode == OpenGl_GUM_PREPARE)
137         {
138           if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
139           {
140             continue;
141           }
142           else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
143           {
144             continue;
145           }
146
147           for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
148           {
149             // Extract OpenGL elements from the group (primitives arrays)
150             for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
151             {
152               OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
153
154               if (aPrimArray != NULL)
155               {
156                 anArrayIDs.insert (aPrimArray->GetUID());
157               }
158             }
159           }
160         }
161         else if (theMode == OpenGl_GUM_REBUILD)
162         {
163           if (!aStructure->IsRaytracable())
164           {
165             continue;
166           }
167           else if (addRaytraceStructure (aStructure, theGlContext))
168           {
169             anElements.insert (aStructure); // structure was processed
170           }
171         }
172       }
173     }
174   }
175
176   if (theMode == OpenGl_GUM_PREPARE)
177   {
178     BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
179
180     // Filter out unchanged objects so only their transformations and materials
181     // will be updated (and newly added objects will be processed from scratch)
182     for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
183     {
184       OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
185         myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
186
187       if (aTriangleSet == NULL)
188       {
189         continue;
190       }
191
192       if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
193       {
194         anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
195
196         myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
197       }
198     }
199
200     myRaytraceGeometry.Objects() = anUnchangedObjects;
201
202     return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
203   }
204   else if (theMode == OpenGl_GUM_REBUILD)
205   {
206     // Actualize the hash map of structures - remove out-of-date records
207     std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
208
209     while (anIter != myStructureStates.end())
210     {
211       if (anElements.find (anIter->first) == anElements.end())
212       {
213         myStructureStates.erase (anIter++);
214       }
215       else
216       {
217         ++anIter;
218       }
219     }
220
221     // Actualize OpenGL layer list state
222     myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
223
224     // Rebuild two-level acceleration structure
225     myRaytraceGeometry.ProcessAcceleration();
226
227     myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
228       myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
229       myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
230
231     const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
232
233     myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
234
235     return uploadRaytraceData (theGlContext);
236   }
237
238   if (myRaytraceParameters.GlobalIllumination)
239   {
240     Standard_Boolean toRestart =
241       aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
242
243     for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
244     {
245       if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
246       {
247         toRestart = Standard_True;
248       }
249     }
250
251     if (toRestart)
252     {
253       myAccumFrames = 0;
254     }
255
256     myNonRaytraceStructureIDs = aNonRaytraceIDs;
257   }
258
259   return Standard_True;
260 }
261
262 // =======================================================================
263 // function : toUpdateStructure
264 // purpose  : Checks to see if the structure is modified
265 // =======================================================================
266 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
267 {
268   if (!theStructure->IsRaytracable())
269   {
270     if (theStructure->ModificationState() > 0)
271     {
272       theStructure->ResetModificationState();
273
274       return Standard_True; // ray-trace element was removed - need to rebuild
275     }
276
277     return Standard_False; // did not contain ray-trace elements
278   }
279
280   std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
281
282   if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
283   {
284     return Standard_True;
285   }
286   else if (theStructure->InstancedStructure() != NULL)
287   {
288     return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
289   }
290
291   return Standard_False;
292 }
293
294 // =======================================================================
295 // function : buildTextureTransform
296 // purpose  : Constructs texture transformation matrix
297 // =======================================================================
298 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
299 {
300   theMatrix.InitIdentity();
301   if (theParams.IsNull())
302   {
303     return;
304   }
305
306   // Apply scaling
307   const Graphic3d_Vec2& aScale = theParams->Scale();
308
309   theMatrix.ChangeValue (0, 0) *= aScale.x();
310   theMatrix.ChangeValue (1, 0) *= aScale.x();
311   theMatrix.ChangeValue (2, 0) *= aScale.x();
312   theMatrix.ChangeValue (3, 0) *= aScale.x();
313
314   theMatrix.ChangeValue (0, 1) *= aScale.y();
315   theMatrix.ChangeValue (1, 1) *= aScale.y();
316   theMatrix.ChangeValue (2, 1) *= aScale.y();
317   theMatrix.ChangeValue (3, 1) *= aScale.y();
318
319   // Apply translation
320   const Graphic3d_Vec2 aTrans = -theParams->Translation();
321
322   theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
323                                  theMatrix.GetValue (0, 1) * aTrans.y();
324
325   theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
326                                  theMatrix.GetValue (1, 1) * aTrans.y();
327
328   theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
329                                  theMatrix.GetValue (2, 1) * aTrans.y();
330
331   // Apply rotation
332   const Standard_ShortReal aSin = std::sin (
333     -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
334   const Standard_ShortReal aCos = std::cos (
335     -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
336
337   BVH_Mat4f aRotationMat;
338   aRotationMat.SetValue (0, 0,  aCos);
339   aRotationMat.SetValue (1, 1,  aCos);
340   aRotationMat.SetValue (0, 1, -aSin);
341   aRotationMat.SetValue (1, 0,  aSin);
342
343   theMatrix = theMatrix * aRotationMat;
344 }
345
346 // =======================================================================
347 // function : convertMaterial
348 // purpose  : Creates ray-tracing material properties
349 // =======================================================================
350 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
351                                                       const Handle(OpenGl_Context)& theGlContext)
352 {
353   OpenGl_RaytraceMaterial aResMat;
354
355   const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
356   const OpenGl_Vec3& aMatCol  = theAspect->Aspect()->InteriorColor();
357   const float        aShine   = 128.0f * float(aSrcMat.Shininess());
358
359   const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
360   const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
361   const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
362   const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
363   switch (aSrcMat.MaterialType())
364   {
365     case Graphic3d_MATERIAL_ASPECT:
366     {
367       aResMat.Ambient .SetValues (aSrcAmb * aMatCol,  1.0f);
368       aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
369       aResMat.Emission.SetValues (aSrcEms * aMatCol,  1.0f);
370       break;
371     }
372     case Graphic3d_MATERIAL_PHYSIC:
373     {
374       aResMat.Ambient .SetValues (aSrcAmb,  1.0f);
375       aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
376       aResMat.Emission.SetValues (aSrcEms,  1.0f);
377       break;
378     }
379   }
380
381   {
382     // interior color is always ignored for Specular
383     aResMat.Specular.SetValues (aSrcSpe, aShine);
384     const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
385                                         Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
386                                              aResMat.Diffuse.z() + aResMat.Specular.z()));
387     const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
388     aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
389   }
390
391   const float anIndex = (float )aSrcMat.RefractionIndex();
392   aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
393                                     anIndex == 0 ? 1.0f : anIndex,
394                                     anIndex == 0 ? 1.0f : 1.0f / anIndex);
395
396   aResMat.Ambient  = theGlContext->Vec4FromQuantityColor (aResMat.Ambient);
397   aResMat.Diffuse  = theGlContext->Vec4FromQuantityColor (aResMat.Diffuse);
398   aResMat.Specular = theGlContext->Vec4FromQuantityColor (aResMat.Specular);
399   aResMat.Emission = theGlContext->Vec4FromQuantityColor (aResMat.Emission);
400
401   // Serialize physically-based material properties
402   const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
403
404   aResMat.BSDF.Kc = aBSDF.Kc;
405   aResMat.BSDF.Ks = aBSDF.Ks;
406   aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
407   aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt,  0.f);
408   aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le,  0.f);
409
410   aResMat.BSDF.Absorption = aBSDF.Absorption;
411
412   aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
413   aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
414
415   // Handle material textures
416   if (!theAspect->Aspect()->ToMapTexture())
417   {
418     return aResMat;
419   }
420
421   const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
422   if (aTextureSet.IsNull()
423    || aTextureSet->IsEmpty()
424    || aTextureSet->First().IsNull())
425   {
426     return aResMat;
427   }
428
429   if (theGlContext->HasRayTracingTextures())
430   {
431     const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
432     buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
433
434     // write texture ID to diffuse w-component
435     aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
436   }
437   else if (!myIsRaytraceWarnTextures)
438   {
439     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
440                                "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
441                                "Please try to update graphics card driver. At the moment textures will be ignored.");
442     myIsRaytraceWarnTextures = Standard_True;
443   }
444
445   return aResMat;
446 }
447
448 // =======================================================================
449 // function : addRaytraceStructure
450 // purpose  : Adds OpenGL structure to ray-traced scene geometry
451 // =======================================================================
452 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure*       theStructure,
453                                                     const Handle(OpenGl_Context)& theGlContext)
454 {
455   if (!theStructure->IsVisible())
456   {
457     myStructureStates[theStructure] = StructState (theStructure);
458
459     return Standard_True;
460   }
461
462   // Get structure material
463   OpenGl_RaytraceMaterial aDefaultMaterial;
464   Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
465
466   // Process all connected OpenGL structures
467   const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
468
469   if (anInstanced != NULL && anInstanced->IsRaytracable())
470   {
471     aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
472   }
473
474   myStructureStates[theStructure] = StructState (theStructure);
475
476   return aResult;
477 }
478
479 // =======================================================================
480 // function : addRaytraceGroups
481 // purpose  : Adds OpenGL groups to ray-traced scene geometry
482 // =======================================================================
483 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*        theStructure,
484                                                  const OpenGl_RaytraceMaterial& theStructMat,
485                                                  const Handle(Geom_Transformation)& theTrsf,
486                                                  const Handle(OpenGl_Context)&  theGlContext)
487 {
488   OpenGl_Mat4 aMat4;
489   for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
490   {
491     // Get group material
492     OpenGl_RaytraceMaterial aGroupMaterial;
493     if (aGroupIter.Value()->GlAspects() != NULL)
494     {
495       aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
496     }
497
498     Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
499
500     // Use group material if available, otherwise use structure material
501     myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
502
503     // Add OpenGL elements from group (extract primitives arrays and aspects)
504     for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
505     {
506       OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
507
508       if (anAspect != NULL)
509       {
510         aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
511
512         OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
513
514         myRaytraceGeometry.Materials.push_back (aMaterial);
515       }
516       else
517       {
518         OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
519
520         if (aPrimArray != NULL)
521         {
522           std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
523
524           if (aSetIter != myArrayToTrianglesMap.end())
525           {
526             OpenGl_TriangleSet* aSet = aSetIter->second;
527             opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
528             if (!theTrsf.IsNull())
529             {
530               theTrsf->Trsf().GetMat4 (aMat4);
531               aTransform->SetTransform (aMat4);
532             }
533
534             aSet->SetProperties (aTransform);
535             if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
536             {
537               aSet->SetMaterialIndex (aMatID);
538             }
539           }
540           else
541           {
542             if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
543             {
544               opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
545               if (!theTrsf.IsNull())
546               {
547                 theTrsf->Trsf().GetMat4 (aMat4);
548                 aTransform->SetTransform (aMat4);
549               }
550
551               aSet->SetProperties (aTransform);
552               myRaytraceGeometry.Objects().Append (aSet);
553             }
554           }
555         }
556       }
557     }
558   }
559
560   return Standard_True;
561 }
562
563 // =======================================================================
564 // function : addRaytracePrimitiveArray
565 // purpose  : Adds OpenGL primitive array to ray-traced scene geometry
566 // =======================================================================
567 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
568                                                                    const Standard_Integer       theMaterial,
569                                                                    const OpenGl_Mat4*           theTransform)
570 {
571   const Handle(Graphic3d_BoundBuffer)& aBounds   = theArray->Bounds();
572   const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
573   const Handle(Graphic3d_Buffer)&      anAttribs = theArray->Attributes();
574
575   if (theArray->DrawMode() < GL_TRIANGLES
576   #ifndef GL_ES_VERSION_2_0
577    || theArray->DrawMode() > GL_POLYGON
578   #else
579    || theArray->DrawMode() > GL_TRIANGLE_FAN
580   #endif
581    || anAttribs.IsNull())
582   {
583     return Handle(OpenGl_TriangleSet)();
584   }
585
586   OpenGl_Mat4 aNormalMatrix;
587   if (theTransform != NULL)
588   {
589     Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
590       "Error: Failed to compute normal transformation matrix", NULL);
591
592     aNormalMatrix.Transpose();
593   }
594
595   Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
596   {
597     aSet->Vertices.reserve (anAttribs->NbElements);
598     aSet->Normals.reserve  (anAttribs->NbElements);
599     aSet->TexCrds.reserve  (anAttribs->NbElements);
600
601     const size_t aVertFrom = aSet->Vertices.size();
602
603     Standard_Integer anAttribIndex = 0;
604     Standard_Size anAttribStride = 0;
605     if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
606     {
607       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
608       if (anAttrib.DataType == Graphic3d_TOD_VEC2
609        || anAttrib.DataType == Graphic3d_TOD_VEC3
610        || anAttrib.DataType == Graphic3d_TOD_VEC4)
611       {
612         for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
613         {
614           const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
615           aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
616         }
617       }
618     }
619     if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
620     {
621       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
622       if (anAttrib.DataType == Graphic3d_TOD_VEC3
623        || anAttrib.DataType == Graphic3d_TOD_VEC4)
624       {
625         for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
626         {
627           aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
628         }
629       }
630     }
631     if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
632     {
633       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
634       if (anAttrib.DataType == Graphic3d_TOD_VEC2)
635       {
636         for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
637         {
638           aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
639         }
640       }
641     }
642
643     if (aSet->Normals.size() != aSet->Vertices.size())
644     {
645       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
646       {
647         aSet->Normals.push_back (BVH_Vec3f());
648       }
649     }
650
651     if (aSet->TexCrds.size() != aSet->Vertices.size())
652     {
653       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
654       {
655         aSet->TexCrds.push_back (BVH_Vec2f());
656       }
657     }
658
659     if (theTransform != NULL)
660     {
661       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
662       {
663         BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
664
665         BVH_Vec4f aTransVertex = *theTransform *
666           BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
667
668         aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
669       }
670       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
671       {
672         BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
673
674         BVH_Vec4f aTransNormal = aNormalMatrix *
675           BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
676
677         aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
678       }
679     }
680
681     if (!aBounds.IsNull())
682     {
683       for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
684       {
685         const Standard_Integer aVertNum = aBounds->Bounds[aBound];
686
687         if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
688         {
689           aSet.Nullify();
690           return Handle(OpenGl_TriangleSet)();
691         }
692
693         aBoundStart += aVertNum;
694       }
695     }
696     else
697     {
698       const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
699
700       if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
701       {
702         aSet.Nullify();
703         return Handle(OpenGl_TriangleSet)();
704       }
705     }
706   }
707
708   if (aSet->Size() != 0)
709   {
710     aSet->MarkDirty();
711   }
712
713   return aSet;
714 }
715
716 // =======================================================================
717 // function : addRaytraceVertexIndices
718 // purpose  : Adds vertex indices to ray-traced scene geometry
719 // =======================================================================
720 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet&                  theSet,
721                                                         const Standard_Integer               theMatID,
722                                                         const Standard_Integer               theCount,
723                                                         const Standard_Integer               theOffset,
724                                                         const OpenGl_PrimitiveArray&         theArray)
725 {
726   switch (theArray.DrawMode())
727   {
728     case GL_TRIANGLES:      return addRaytraceTriangleArray        (theSet, theMatID, theCount, theOffset, theArray.Indices());
729     case GL_TRIANGLE_FAN:   return addRaytraceTriangleFanArray     (theSet, theMatID, theCount, theOffset, theArray.Indices());
730     case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray   (theSet, theMatID, theCount, theOffset, theArray.Indices());
731   #if !defined(GL_ES_VERSION_2_0)
732     case GL_QUAD_STRIP:     return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
733     case GL_QUADS:          return addRaytraceQuadrangleArray      (theSet, theMatID, theCount, theOffset, theArray.Indices());
734     case GL_POLYGON:        return addRaytracePolygonArray         (theSet, theMatID, theCount, theOffset, theArray.Indices());
735   #endif
736   }
737
738   return Standard_False;
739 }
740
741 // =======================================================================
742 // function : addRaytraceTriangleArray
743 // purpose  : Adds OpenGL triangle array to ray-traced scene geometry
744 // =======================================================================
745 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
746                                                         const Standard_Integer               theMatID,
747                                                         const Standard_Integer               theCount,
748                                                         const Standard_Integer               theOffset,
749                                                         const Handle(Graphic3d_IndexBuffer)& theIndices)
750 {
751   if (theCount < 3)
752   {
753     return Standard_True;
754   }
755
756   theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
757
758   if (!theIndices.IsNull())
759   {
760     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
761     {
762       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
763                                             theIndices->Index (aVert + 1),
764                                             theIndices->Index (aVert + 2),
765                                             theMatID));
766     }
767   }
768   else
769   {
770     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
771     {
772       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
773     }
774   }
775
776   return Standard_True;
777 }
778
779 // =======================================================================
780 // function : addRaytraceTriangleFanArray
781 // purpose  : Adds OpenGL triangle fan array to ray-traced scene geometry
782 // =======================================================================
783 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
784                                                            const Standard_Integer               theMatID,
785                                                            const Standard_Integer               theCount,
786                                                            const Standard_Integer               theOffset,
787                                                            const Handle(Graphic3d_IndexBuffer)& theIndices)
788 {
789   if (theCount < 3)
790   {
791     return Standard_True;
792   }
793
794   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
795
796   if (!theIndices.IsNull())
797   {
798     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
799     {
800       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
801                                             theIndices->Index (aVert + 1),
802                                             theIndices->Index (aVert + 2),
803                                             theMatID));
804     }
805   }
806   else
807   {
808     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
809     {
810       theSet.Elements.push_back (BVH_Vec4i (theOffset,
811                                             aVert + 1,
812                                             aVert + 2,
813                                             theMatID));
814     }
815   }
816
817   return Standard_True;
818 }
819
820 // =======================================================================
821 // function : addRaytraceTriangleStripArray
822 // purpose  : Adds OpenGL triangle strip array to ray-traced scene geometry
823 // =======================================================================
824 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
825                                                              const Standard_Integer               theMatID,
826                                                              const Standard_Integer               theCount,
827                                                              const Standard_Integer               theOffset,
828                                                              const Handle(Graphic3d_IndexBuffer)& theIndices)
829 {
830   if (theCount < 3)
831   {
832     return Standard_True;
833   }
834
835   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
836
837   if (!theIndices.IsNull())
838   {
839     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
840     {
841       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
842                                             theIndices->Index (aVert + (aCW ? 0 : 1)),
843                                             theIndices->Index (aVert + 2),
844                                             theMatID));
845     }
846   }
847   else
848   {
849     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
850     {
851       theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
852                                             aVert + (aCW ? 0 : 1),
853                                             aVert + 2,
854                                             theMatID));
855     }
856   }
857
858   return Standard_True;
859 }
860
861 // =======================================================================
862 // function : addRaytraceQuadrangleArray
863 // purpose  : Adds OpenGL quad array to ray-traced scene geometry
864 // =======================================================================
865 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
866                                                           const Standard_Integer               theMatID,
867                                                           const Standard_Integer               theCount,
868                                                           const Standard_Integer               theOffset,
869                                                           const Handle(Graphic3d_IndexBuffer)& theIndices)
870 {
871   if (theCount < 4)
872   {
873     return Standard_True;
874   }
875
876   theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
877
878   if (!theIndices.IsNull())
879   {
880     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
881     {
882       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
883                                             theIndices->Index (aVert + 1),
884                                             theIndices->Index (aVert + 2),
885                                             theMatID));
886       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
887                                             theIndices->Index (aVert + 2),
888                                             theIndices->Index (aVert + 3),
889                                             theMatID));
890     }
891   }
892   else
893   {
894     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
895     {
896       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
897                                             theMatID));
898       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
899                                             theMatID));
900     }
901   }
902
903   return Standard_True;
904 }
905
906 // =======================================================================
907 // function : addRaytraceQuadrangleStripArray
908 // purpose  : Adds OpenGL quad strip array to ray-traced scene geometry
909 // =======================================================================
910 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
911                                                                const Standard_Integer               theMatID,
912                                                                const Standard_Integer               theCount,
913                                                                const Standard_Integer               theOffset,
914                                                                const Handle(Graphic3d_IndexBuffer)& theIndices)
915 {
916   if (theCount < 4)
917   {
918     return Standard_True;
919   }
920
921   theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
922
923   if (!theIndices.IsNull())
924   {
925     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
926     {
927       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
928                                             theIndices->Index (aVert + 1),
929                                             theIndices->Index (aVert + 2),
930                                             theMatID));
931
932       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
933                                             theIndices->Index (aVert + 3),
934                                             theIndices->Index (aVert + 2),
935                                             theMatID));
936     }
937   }
938   else
939   {
940     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
941     {
942       theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
943                                             aVert + 1,
944                                             aVert + 2,
945                                             theMatID));
946
947       theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
948                                             aVert + 3,
949                                             aVert + 2,
950                                             theMatID));
951     }
952   }
953
954   return Standard_True;
955 }
956
957 // =======================================================================
958 // function : addRaytracePolygonArray
959 // purpose  : Adds OpenGL polygon array to ray-traced scene geometry
960 // =======================================================================
961 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
962                                                        const Standard_Integer               theMatID,
963                                                        const Standard_Integer               theCount,
964                                                        const Standard_Integer               theOffset,
965                                                        const Handle(Graphic3d_IndexBuffer)& theIndices)
966 {
967   if (theCount < 3)
968   {
969     return Standard_True;
970   }
971
972   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
973
974   if (!theIndices.IsNull())
975   {
976     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
977     {
978       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
979                                             theIndices->Index (aVert + 1),
980                                             theIndices->Index (aVert + 2),
981                                             theMatID));
982     }
983   }
984   else
985   {
986     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
987     {
988       theSet.Elements.push_back (BVH_Vec4i (theOffset,
989                                             aVert + 1,
990                                             aVert + 2,
991                                             theMatID));
992     }
993   }
994
995   return Standard_True;
996 }
997
998 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
999
1000 // =======================================================================
1001 // function : Source
1002 // purpose  : Returns shader source combined with prefix
1003 // =======================================================================
1004 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1005 {
1006   const TCollection_AsciiString aVersion = "#version 140";
1007
1008   if (myPrefix.IsEmpty())
1009   {
1010     return aVersion + "\n" + mySource;
1011   }
1012
1013   return aVersion + "\n" + myPrefix + "\n" + mySource;
1014 }
1015
1016 // =======================================================================
1017 // function : LoadFromFiles
1018 // purpose  : Loads shader source from specified files
1019 // =======================================================================
1020 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1021                                                            const TCollection_AsciiString& thePrefix)
1022 {
1023   myError.Clear();
1024   mySource.Clear();
1025   myPrefix = thePrefix;
1026
1027   TCollection_AsciiString aMissingFiles;
1028   for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1029   {
1030     OSD_File aFile (theFileNames[anIndex]);
1031     if (aFile.Exists())
1032     {
1033       aFile.Open (OSD_ReadOnly, OSD_Protection());
1034     }
1035     if (!aFile.IsOpen())
1036     {
1037       if (!aMissingFiles.IsEmpty())
1038       {
1039         aMissingFiles += ", ";
1040       }
1041       aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1042       continue;
1043     }
1044     else if (!aMissingFiles.IsEmpty())
1045     {
1046       aFile.Close();
1047       continue;
1048     }
1049
1050     TCollection_AsciiString aSource;
1051     aFile.Read (aSource, (Standard_Integer) aFile.Size());
1052     if (!aSource.IsEmpty())
1053     {
1054       mySource += TCollection_AsciiString ("\n") + aSource;
1055     }
1056     aFile.Close();
1057   }
1058
1059   if (!aMissingFiles.IsEmpty())
1060   {
1061     myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1062     return Standard_False;
1063   }
1064   return Standard_True;
1065 }
1066
1067 // =======================================================================
1068 // function : LoadFromStrings
1069 // purpose  :
1070 // =======================================================================
1071 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1072                                                              const TCollection_AsciiString& thePrefix)
1073 {
1074   myError.Clear();
1075   mySource.Clear();
1076   myPrefix = thePrefix;
1077
1078   for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1079   {
1080     TCollection_AsciiString aSource = theStrings[anIndex];
1081     if (!aSource.IsEmpty())
1082     {
1083       mySource += TCollection_AsciiString ("\n") + aSource;
1084     }
1085   }
1086   return Standard_True;
1087 }
1088
1089 // =======================================================================
1090 // function : generateShaderPrefix
1091 // purpose  : Generates shader prefix based on current ray-tracing options
1092 // =======================================================================
1093 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1094 {
1095   TCollection_AsciiString aPrefixString =
1096     TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1097     TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1098
1099   if (myRaytraceParameters.TransparentShadows)
1100   {
1101     aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1102   }
1103   if (!theGlContext->ToRenderSRGB())
1104   {
1105     aPrefixString += TCollection_AsciiString ("\n#define THE_SHIFT_sRGB");
1106   }
1107
1108   // If OpenGL driver supports bindless textures and texturing
1109   // is actually used, activate texturing in ray-tracing mode
1110   if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1111   {
1112     aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1113       TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1114   }
1115
1116   if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1117   {
1118     aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1119
1120     if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1121     {
1122       if (theGlContext->IsGlGreaterEqual (4, 4))
1123       {
1124         aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
1125         if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1126          && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1127         {
1128           aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1129         }
1130       }
1131     }
1132
1133     if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1134     {
1135       aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1136     }
1137
1138     switch (myRaytraceParameters.ToneMappingMethod)
1139     {
1140       case Graphic3d_ToneMappingMethod_Disabled:
1141         break;
1142       case Graphic3d_ToneMappingMethod_Filmic:
1143         aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1144         break;
1145     }
1146   }
1147
1148   if (myRaytraceParameters.DepthOfField)
1149   {
1150     aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1151   }
1152
1153   return aPrefixString;
1154 }
1155
1156 // =======================================================================
1157 // function : safeFailBack
1158 // purpose  : Performs safe exit when shaders initialization fails
1159 // =======================================================================
1160 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1161                                             const Handle(OpenGl_Context)&     theGlContext)
1162 {
1163   theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1164     GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1165
1166   myRaytraceInitStatus = OpenGl_RT_FAIL;
1167
1168   releaseRaytraceResources (theGlContext);
1169
1170   return Standard_False;
1171 }
1172
1173 // =======================================================================
1174 // function : initShader
1175 // purpose  : Creates new shader object with specified source
1176 // =======================================================================
1177 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum                  theType,
1178                                                      const ShaderSource&           theSource,
1179                                                      const Handle(OpenGl_Context)& theGlContext)
1180 {
1181   Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1182   if (!aShader->Create (theGlContext))
1183   {
1184     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1185                                TCollection_ExtendedString ("Error: Failed to create ") +
1186                                (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1187     aShader->Release (theGlContext.get());
1188     return Handle(OpenGl_ShaderObject)();
1189   }
1190
1191   if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source()))
1192   {
1193     aShader->Release (theGlContext.get());
1194     return Handle(OpenGl_ShaderObject)();
1195   }
1196   return aShader;
1197 }
1198
1199 // =======================================================================
1200 // function : initProgram
1201 // purpose  : Creates GLSL program from the given shader objects
1202 // =======================================================================
1203 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)&      theGlContext,
1204                                                        const Handle(OpenGl_ShaderObject)& theVertShader,
1205                                                        const Handle(OpenGl_ShaderObject)& theFragShader,
1206                                                        const TCollection_AsciiString& theName)
1207 {
1208   const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1209   Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
1210
1211   if (!aProgram->Create (theGlContext))
1212   {
1213     theVertShader->Release (theGlContext.operator->());
1214
1215     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1216       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1217
1218     return Handle(OpenGl_ShaderProgram)();
1219   }
1220
1221   if (!aProgram->AttachShader (theGlContext, theVertShader)
1222    || !aProgram->AttachShader (theGlContext, theFragShader))
1223   {
1224     theVertShader->Release (theGlContext.operator->());
1225
1226     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1227       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1228
1229     return Handle(OpenGl_ShaderProgram)();
1230   }
1231
1232   aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1233
1234   TCollection_AsciiString aLinkLog;
1235
1236   if (!aProgram->Link (theGlContext))
1237   {
1238     aProgram->FetchInfoLog (theGlContext, aLinkLog);
1239
1240     const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1241       "Failed to link shader program:\n") + aLinkLog;
1242
1243     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1244       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1245
1246     return Handle(OpenGl_ShaderProgram)();
1247   }
1248   else if (theGlContext->caps->glslWarnings)
1249   {
1250     aProgram->FetchInfoLog (theGlContext, aLinkLog);
1251     if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1252     {
1253       const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1254         "Shader program was linked with following warnings:\n") + aLinkLog;
1255
1256       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1257         GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1258     }
1259   }
1260
1261   return aProgram;
1262 }
1263
1264 // =======================================================================
1265 // function : initRaytraceResources
1266 // purpose  : Initializes OpenGL/GLSL shader programs
1267 // =======================================================================
1268 Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1269                                                      const Standard_Integer theSizeY,
1270                                                      const Handle(OpenGl_Context)& theGlContext)
1271 {
1272   if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1273   {
1274     return Standard_False;
1275   }
1276
1277   Standard_Boolean aToRebuildShaders = Standard_False;
1278
1279   if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1280   {
1281     myRaytraceInitStatus = OpenGl_RT_NONE;
1282     releaseRaytraceResources (theGlContext, Standard_True);
1283     myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1284   }
1285
1286   if (myRaytraceInitStatus == OpenGl_RT_INIT)
1287   {
1288     if (!myIsRaytraceDataValid)
1289     {
1290       return Standard_True;
1291     }
1292
1293     const Standard_Integer aRequiredStackSize =
1294       myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1295
1296     if (myRaytraceParameters.StackSize < aRequiredStackSize)
1297     {
1298       myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1299
1300       aToRebuildShaders = Standard_True;
1301     }
1302     else
1303     {
1304       if (aRequiredStackSize < myRaytraceParameters.StackSize)
1305       {
1306         if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1307         {
1308           myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1309           aToRebuildShaders = Standard_True;
1310         }
1311       }
1312     }
1313
1314     if (myRenderParams.RaytracingDepth             != myRaytraceParameters.NbBounces
1315      || myRenderParams.IsTransparentShadowEnabled  != myRaytraceParameters.TransparentShadows
1316      || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1317      || myRenderParams.TwoSidedBsdfModels          != myRaytraceParameters.TwoSidedBsdfModels
1318      || myRaytraceGeometry.HasTextures()           != myRaytraceParameters.UseBindlessTextures)
1319     {
1320       myRaytraceParameters.NbBounces           = myRenderParams.RaytracingDepth;
1321       myRaytraceParameters.TransparentShadows  = myRenderParams.IsTransparentShadowEnabled;
1322       myRaytraceParameters.GlobalIllumination  = myRenderParams.IsGlobalIlluminationEnabled;
1323       myRaytraceParameters.TwoSidedBsdfModels  = myRenderParams.TwoSidedBsdfModels;
1324       myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1325       aToRebuildShaders = Standard_True;
1326     }
1327
1328     if (myRenderParams.AdaptiveScreenSampling       != myRaytraceParameters.AdaptiveScreenSampling
1329      || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1330     {
1331       myRaytraceParameters.AdaptiveScreenSampling       = myRenderParams.AdaptiveScreenSampling;
1332       myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
1333       if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1334       {
1335         if (!theGlContext->HasRayTracingAdaptiveSampling())
1336         {
1337           // disable the feature if it is not supported
1338           myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1339           theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1340                                      "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1341         }
1342         else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1343              && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1344         {
1345           // disable the feature if it is not supported
1346           myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1347           theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1348                                      "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
1349         }
1350       }
1351
1352       aToRebuildShaders = Standard_True;
1353     }
1354     myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
1355
1356     const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1357     if (myRaytraceParameters.DepthOfField != toEnableDof)
1358     {
1359       myRaytraceParameters.DepthOfField = toEnableDof;
1360       aToRebuildShaders = Standard_True;
1361     }
1362
1363     if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1364     {
1365       myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1366       aToRebuildShaders = true;
1367     }
1368
1369     if (aToRebuildShaders)
1370     {
1371       // Reject accumulated frames
1372       myAccumFrames = 0;
1373
1374       // Environment map should be updated
1375       myToUpdateEnvironmentMap = Standard_True;
1376
1377       const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1378
1379 #ifdef RAY_TRACE_PRINT_INFO
1380       std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1381 #endif
1382
1383       myRaytraceShaderSource.SetPrefix (aPrefixString);
1384       myPostFSAAShaderSource.SetPrefix (aPrefixString);
1385       myOutImageShaderSource.SetPrefix (aPrefixString);
1386
1387       if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source())
1388        || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source())
1389        || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source()))
1390       {
1391         return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1392       }
1393
1394       myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1395       myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1396       myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1397
1398       if (!myRaytraceProgram->Link (theGlContext)
1399        || !myPostFSAAProgram->Link (theGlContext)
1400        || !myOutImageProgram->Link (theGlContext))
1401       {
1402         return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1403       }
1404     }
1405   }
1406
1407   if (myRaytraceInitStatus == OpenGl_RT_NONE)
1408   {
1409     myAccumFrames = 0; // accumulation should be restarted
1410
1411     if (!theGlContext->IsGlGreaterEqual (3, 1))
1412     {
1413       return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1414     }
1415     else if (!theGlContext->arbTboRGB32)
1416     {
1417       return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1418     }
1419     else if (!theGlContext->arbFBOBlit)
1420     {
1421       return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1422     }
1423
1424     myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1425
1426     const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1427     if (myIsRaytraceDataValid)
1428     {
1429       myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1430         myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1431     }
1432
1433     const TCollection_AsciiString aPrefixString  = generateShaderPrefix (theGlContext);
1434
1435 #ifdef RAY_TRACE_PRINT_INFO
1436     std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1437 #endif
1438
1439     ShaderSource aBasicVertShaderSrc;
1440     {
1441       if (!aShaderFolder.IsEmpty())
1442       {
1443         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1444         if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1445         {
1446           return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1447         }
1448       }
1449       else
1450       {
1451         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1452         aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1453       }
1454     }
1455
1456     {
1457       if (!aShaderFolder.IsEmpty())
1458       {
1459         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1460                                                    aShaderFolder + "/PathtraceBase.fs",
1461                                                    aShaderFolder + "/RaytraceRender.fs",
1462                                                    "" };
1463         if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1464         {
1465           return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1466         }
1467       }
1468       else
1469       {
1470         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1471                                                         Shaders_PathtraceBase_fs,
1472                                                         Shaders_RaytraceRender_fs,
1473                                                         "" };
1474         myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1475       }
1476
1477       Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1478       if (aBasicVertShader.IsNull())
1479       {
1480         return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1481       }
1482
1483       myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1484       if (myRaytraceShader.IsNull())
1485       {
1486         aBasicVertShader->Release (theGlContext.operator->());
1487         return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1488       }
1489
1490       myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
1491       if (myRaytraceProgram.IsNull())
1492       {
1493         return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1494       }
1495     }
1496
1497     {
1498       if (!aShaderFolder.IsEmpty())
1499       {
1500         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1501         if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1502         {
1503           return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1504         }
1505       }
1506       else
1507       {
1508         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1509         myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1510       }
1511
1512       Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1513       if (aBasicVertShader.IsNull())
1514       {
1515         return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1516       }
1517
1518       myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1519       if (myPostFSAAShader.IsNull())
1520       {
1521         aBasicVertShader->Release (theGlContext.operator->());
1522         return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1523       }
1524
1525       myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
1526       if (myPostFSAAProgram.IsNull())
1527       {
1528         return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1529       }
1530     }
1531
1532     {
1533       if (!aShaderFolder.IsEmpty())
1534       {
1535         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1536         if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1537         {
1538           return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1539         }
1540       }
1541       else
1542       {
1543         const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1544         myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1545       }
1546
1547       Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1548       if (aBasicVertShader.IsNull())
1549       {
1550         return safeFailBack ("Failed to set vertex shader source", theGlContext);
1551       }
1552
1553       myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1554       if (myOutImageShader.IsNull())
1555       {
1556         aBasicVertShader->Release (theGlContext.operator->());
1557         return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1558       }
1559
1560       myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
1561       if (myOutImageProgram.IsNull())
1562       {
1563         return safeFailBack ("Failed to initialize display shader program", theGlContext);
1564       }
1565     }
1566   }
1567
1568   if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1569   {
1570     for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1571     {
1572       Handle(OpenGl_ShaderProgram)& aShaderProgram =
1573         (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1574
1575       theGlContext->BindProgram (aShaderProgram);
1576
1577       aShaderProgram->SetSampler (theGlContext,
1578         "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1579       aShaderProgram->SetSampler (theGlContext,
1580         "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1581       aShaderProgram->SetSampler (theGlContext,
1582         "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1583       aShaderProgram->SetSampler (theGlContext,
1584         "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1585       aShaderProgram->SetSampler (theGlContext,
1586         "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1587       aShaderProgram->SetSampler (theGlContext,
1588         "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1589       aShaderProgram->SetSampler (theGlContext,
1590         "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1591       aShaderProgram->SetSampler (theGlContext, 
1592         "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1593       aShaderProgram->SetSampler (theGlContext,
1594         "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1595       aShaderProgram->SetSampler (theGlContext,
1596         "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1597       aShaderProgram->SetSampler (theGlContext,
1598         "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1599
1600       if (anIndex == 1)
1601       {
1602         aShaderProgram->SetSampler (theGlContext,
1603           "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1604       }
1605       else
1606       {
1607         aShaderProgram->SetSampler (theGlContext,
1608           "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1609       }
1610
1611       myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1612         aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1613
1614       myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1615         aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1616       myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1617         aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1618       myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1619         aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1620       myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1621         aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1622       myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1623         aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1624       myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1625         aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1626       myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1627         aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1628       myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1629         aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1630       myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1631         aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1632       myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1633         aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1634
1635       myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1636         aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1637       myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1638         aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1639       myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1640         aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1641       myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1642         aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1643
1644       myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1645         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1646       myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1647         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1648       myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1649         aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1650
1651       myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1652         aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1653
1654       myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1655         aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1656       myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1657         aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1658       myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1659         aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1660       myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1661         aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1662       myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1663         aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1664
1665       myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1666         aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1667       myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1668         aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1669
1670       myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1671         aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1672       myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1673         aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1674
1675       myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1676         aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1677       myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1678         aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
1679       myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1680         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1681       myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1682         aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1683       myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1684         aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
1685
1686       myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1687         aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1688       myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1689         aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1690
1691       myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1692         aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1693     }
1694
1695     theGlContext->BindProgram (myOutImageProgram);
1696
1697     myOutImageProgram->SetSampler (theGlContext,
1698       "uInputTexture", OpenGl_RT_PrevAccumTexture);
1699
1700     myOutImageProgram->SetSampler (theGlContext,
1701       "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1702
1703     theGlContext->BindProgram (NULL);
1704   }
1705
1706   if (myRaytraceInitStatus != OpenGl_RT_NONE)
1707   {
1708     return myRaytraceInitStatus == OpenGl_RT_INIT;
1709   }
1710
1711   const GLfloat aVertices[] = { -1.f, -1.f,  0.f,
1712                                 -1.f,  1.f,  0.f,
1713                                  1.f,  1.f,  0.f,
1714                                  1.f,  1.f,  0.f,
1715                                  1.f, -1.f,  0.f,
1716                                 -1.f, -1.f,  0.f };
1717
1718   myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1719
1720   myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1721
1722   return Standard_True;
1723 }
1724
1725 // =======================================================================
1726 // function : nullifyResource
1727 // purpose  : Releases OpenGL resource
1728 // =======================================================================
1729 template <class T>
1730 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1731 {
1732   if (!theResource.IsNull())
1733   {
1734     theResource->Release (theGlContext.get());
1735     theResource.Nullify();
1736   }
1737 }
1738
1739 // =======================================================================
1740 // function : releaseRaytraceResources
1741 // purpose  : Releases OpenGL/GLSL shader programs
1742 // =======================================================================
1743 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1744 {
1745   // release shader resources
1746   nullifyResource (theGlContext, myRaytraceShader);
1747   nullifyResource (theGlContext, myPostFSAAShader);
1748
1749   nullifyResource (theGlContext, myRaytraceProgram);
1750   nullifyResource (theGlContext, myPostFSAAProgram);
1751   nullifyResource (theGlContext, myOutImageProgram);
1752
1753   if (!theToRebuild) // complete release
1754   {
1755     myRaytraceFBO1[0]->Release (theGlContext.get());
1756     myRaytraceFBO1[1]->Release (theGlContext.get());
1757     myRaytraceFBO2[0]->Release (theGlContext.get());
1758     myRaytraceFBO2[1]->Release (theGlContext.get());
1759
1760     nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1761     nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1762
1763     nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1764     nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1765     nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1766     nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1767     nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1768     nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
1769
1770     nullifyResource (theGlContext, mySceneNodeInfoTexture);
1771     nullifyResource (theGlContext, mySceneMinPointTexture);
1772     nullifyResource (theGlContext, mySceneMaxPointTexture);
1773
1774     nullifyResource (theGlContext, myGeometryVertexTexture);
1775     nullifyResource (theGlContext, myGeometryNormalTexture);
1776     nullifyResource (theGlContext, myGeometryTexCrdTexture);
1777     nullifyResource (theGlContext, myGeometryTriangTexture);
1778     nullifyResource (theGlContext, mySceneTransformTexture);
1779
1780     nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1781     nullifyResource (theGlContext, myRaytraceMaterialTexture);
1782
1783     myRaytraceGeometry.ReleaseResources (theGlContext);
1784
1785     if (myRaytraceScreenQuad.IsValid ())
1786     {
1787       myRaytraceScreenQuad.Release (theGlContext.get());
1788     }
1789   }
1790 }
1791
1792 // =======================================================================
1793 // function : updateRaytraceBuffers
1794 // purpose  : Updates auxiliary OpenGL frame buffers.
1795 // =======================================================================
1796 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer        theSizeX,
1797                                                      const Standard_Integer        theSizeY,
1798                                                      const Handle(OpenGl_Context)& theGlContext)
1799 {
1800   // Auxiliary buffers are not used
1801   if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1802   {
1803     myRaytraceFBO1[0]->Release (theGlContext.operator->());
1804     myRaytraceFBO2[0]->Release (theGlContext.operator->());
1805     myRaytraceFBO1[1]->Release (theGlContext.operator->());
1806     myRaytraceFBO2[1]->Release (theGlContext.operator->());
1807
1808     return Standard_True;
1809   }
1810
1811   if (myRaytraceParameters.AdaptiveScreenSampling)
1812   {
1813     Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1814     myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1815     myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1816     if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1817     {
1818       myRaytraceFBO1[1]->Release (theGlContext.operator->());
1819       myRaytraceFBO2[1]->Release (theGlContext.operator->());
1820     }
1821   }
1822
1823   for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
1824   {
1825     if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
1826     {
1827       myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1828       myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
1829       myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
1830       myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
1831     }
1832
1833     if (aViewIter == 1
1834      && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
1835     {
1836       myRaytraceFBO1[1]->Release (theGlContext.operator->());
1837       myRaytraceFBO2[1]->Release (theGlContext.operator->());
1838       myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1839       myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1840       myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1841       continue;
1842     }
1843
1844     if (myRaytraceParameters.AdaptiveScreenSampling)
1845     {
1846       if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1847        && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1848        && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1849        && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1850       {
1851         if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1852         {
1853           continue; // offsets texture is dynamically resized
1854         }
1855         else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1856               && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1857         {
1858           continue;
1859         }
1860       }
1861
1862       myAccumFrames = 0;
1863
1864       // Due to limitations of OpenGL image load-store extension
1865       // atomic operations are supported only for single-channel
1866       // images, so we define GL_R32F image. It is used as array
1867       // of 6D floating point vectors:
1868       // 0 - R color channel
1869       // 1 - G color channel
1870       // 2 - B color channel
1871       // 3 - hit time transformed into OpenGL NDC space
1872       // 4 - luminance accumulated for odd samples only
1873       myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1874
1875       // workaround for some NVIDIA drivers
1876       myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
1877       myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
1878       myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext,
1879                                                      OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1880                                                      Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1881                                                      Graphic3d_TOT_2D);
1882       if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1883       {
1884         myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext,
1885                                                        OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1886                                                        Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1887                                                        Graphic3d_TOT_2D);
1888       }
1889     }
1890     else // non-adaptive mode
1891     {
1892       if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1893        || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1894       {
1895         myAccumFrames = 0; // accumulation should be restarted
1896       }
1897
1898       myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1899       myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1900     }
1901   }
1902   return Standard_True;
1903 }
1904
1905 // =======================================================================
1906 // function : updateCamera
1907 // purpose  : Generates viewing rays for corners of screen quad
1908 // =======================================================================
1909 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1910                                 const OpenGl_Mat4& theViewMapping,
1911                                 OpenGl_Vec3*       theOrigins,
1912                                 OpenGl_Vec3*       theDirects,
1913                                 OpenGl_Mat4&       theViewPr,
1914                                 OpenGl_Mat4&       theUnview)
1915 {
1916   // compute view-projection matrix
1917   theViewPr = theViewMapping * theOrientation;
1918
1919   // compute inverse view-projection matrix
1920   theViewPr.Inverted (theUnview);
1921
1922   Standard_Integer aOriginIndex = 0;
1923   Standard_Integer aDirectIndex = 0;
1924
1925   for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1926   {
1927     for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1928     {
1929       OpenGl_Vec4 aOrigin (GLfloat(aX),
1930                            GLfloat(aY),
1931                            -1.0f,
1932                            1.0f);
1933
1934       aOrigin = theUnview * aOrigin;
1935
1936       aOrigin.x() = aOrigin.x() / aOrigin.w();
1937       aOrigin.y() = aOrigin.y() / aOrigin.w();
1938       aOrigin.z() = aOrigin.z() / aOrigin.w();
1939
1940       OpenGl_Vec4 aDirect (GLfloat(aX),
1941                            GLfloat(aY),
1942                            1.0f,
1943                            1.0f);
1944
1945       aDirect = theUnview * aDirect;
1946
1947       aDirect.x() = aDirect.x() / aDirect.w();
1948       aDirect.y() = aDirect.y() / aDirect.w();
1949       aDirect.z() = aDirect.z() / aDirect.w();
1950
1951       aDirect = aDirect - aOrigin;
1952
1953       theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1954                                                 static_cast<GLfloat> (aOrigin.y()),
1955                                                 static_cast<GLfloat> (aOrigin.z()));
1956
1957       theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
1958                                                 static_cast<GLfloat> (aDirect.y()),
1959                                                 static_cast<GLfloat> (aDirect.z()));
1960     }
1961   }
1962 }
1963
1964 // =======================================================================
1965 // function : updatePerspCameraPT
1966 // purpose  : Generates viewing rays (path tracing, perspective camera)
1967 // =======================================================================
1968 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4&           theOrientation,
1969                                        const OpenGl_Mat4&           theViewMapping,
1970                                        Graphic3d_Camera::Projection theProjection,
1971                                        OpenGl_Mat4&                 theViewPr,
1972                                        OpenGl_Mat4&                 theUnview,
1973                                        const int                    theWinSizeX,
1974                                        const int                    theWinSizeY)
1975 {
1976   // compute view-projection matrix
1977   theViewPr = theViewMapping * theOrientation;
1978
1979   // compute inverse view-projection matrix
1980   theViewPr.Inverted(theUnview);
1981   
1982   // get camera stereo params
1983   float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
1984     ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
1985     : static_cast<float> (myCamera->IOD());
1986
1987   float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
1988     ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
1989     : static_cast<float> (myCamera->ZFocus());
1990
1991   // get camera view vectors
1992   const gp_Pnt anOrig = myCamera->Eye();
1993
1994   myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
1995                            static_cast<float> (anOrig.Y()),
1996                            static_cast<float> (anOrig.Z()));
1997
1998   const gp_Dir aView = myCamera->Direction();
1999
2000   OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2001                                            static_cast<float> (aView.Y()),
2002                                            static_cast<float> (aView.Z()));
2003
2004   const gp_Dir anUp = myCamera->Up();
2005
2006   myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2007                            static_cast<float> (anUp.Y()),
2008                            static_cast<float> (anUp.Z()));
2009
2010   myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2011
2012   const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2013   const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2014  
2015   myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2016                            static_cast<float> (aScaleY));
2017
2018   if (theProjection == Graphic3d_Camera::Projection_Perspective)
2019   {
2020     myEyeView = anEyeViewMono;
2021   }
2022   else // stereo camera
2023   {
2024     // compute z-focus point
2025     OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2026
2027     // compute stereo camera shift
2028     float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2029     myEyeOrig += myEyeSide.Normalized() * aDx;
2030
2031     // estimate new camera direction vector and correct its length
2032     myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2033     myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2034   }
2035 }
2036
2037 // =======================================================================
2038 // function : uploadRaytraceData
2039 // purpose  : Uploads ray-trace data to the GPU
2040 // =======================================================================
2041 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2042 {
2043   if (!theGlContext->IsGlGreaterEqual (3, 1))
2044   {
2045 #ifdef RAY_TRACE_PRINT_INFO
2046     std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2047 #endif
2048     return Standard_False;
2049   }
2050
2051   myAccumFrames = 0; // accumulation should be restarted
2052
2053   /////////////////////////////////////////////////////////////////////////////
2054   // Prepare OpenGL textures
2055
2056   if (theGlContext->arbTexBindless != NULL)
2057   {
2058     // If OpenGL driver supports bindless textures we need
2059     // to get unique 64- bit handles for using on the GPU
2060     if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2061     {
2062 #ifdef RAY_TRACE_PRINT_INFO
2063       std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2064 #endif
2065       return Standard_False;
2066     }
2067   }
2068
2069   /////////////////////////////////////////////////////////////////////////////
2070   // Create OpenGL BVH buffers
2071
2072   if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2073   {
2074     mySceneNodeInfoTexture  = new OpenGl_TextureBufferArb;
2075     mySceneMinPointTexture  = new OpenGl_TextureBufferArb;
2076     mySceneMaxPointTexture  = new OpenGl_TextureBufferArb;
2077     mySceneTransformTexture = new OpenGl_TextureBufferArb;
2078
2079     if (!mySceneNodeInfoTexture->Create  (theGlContext)
2080      || !mySceneMinPointTexture->Create  (theGlContext)
2081      || !mySceneMaxPointTexture->Create  (theGlContext)
2082      || !mySceneTransformTexture->Create (theGlContext))
2083     {
2084 #ifdef RAY_TRACE_PRINT_INFO
2085       std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2086 #endif
2087       return Standard_False;
2088     }
2089   }
2090
2091   if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2092   {
2093     myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2094     myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2095     myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2096     myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2097
2098     if (!myGeometryVertexTexture->Create (theGlContext)
2099      || !myGeometryNormalTexture->Create (theGlContext)
2100      || !myGeometryTexCrdTexture->Create (theGlContext)
2101      || !myGeometryTriangTexture->Create (theGlContext))
2102     {
2103 #ifdef RAY_TRACE_PRINT_INFO
2104       std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2105 #endif
2106       return Standard_False;
2107     }
2108   }
2109
2110   if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2111   {
2112     myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2113
2114     if (!myRaytraceMaterialTexture->Create (theGlContext))
2115     {
2116 #ifdef RAY_TRACE_PRINT_INFO
2117       std::cout << "Error: Failed to create buffers for material data" << std::endl;
2118 #endif
2119       return Standard_False;
2120     }
2121   }
2122   
2123   /////////////////////////////////////////////////////////////////////////////
2124   // Write transform buffer
2125
2126   BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2127
2128   bool aResult = true;
2129
2130   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2131   {
2132     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2133       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2134
2135     const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2136     Standard_ASSERT_RETURN (aTransform != NULL,
2137       "OpenGl_TriangleSet does not contain transform", Standard_False);
2138
2139     aNodeTransforms[anElemIndex] = aTransform->Inversed();
2140   }
2141
2142   aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2143     myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2144
2145   delete [] aNodeTransforms;
2146
2147   /////////////////////////////////////////////////////////////////////////////
2148   // Write geometry and bottom-level BVH buffers
2149
2150   Standard_Size aTotalVerticesNb = 0;
2151   Standard_Size aTotalElementsNb = 0;
2152   Standard_Size aTotalBVHNodesNb = 0;
2153
2154   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2155   {
2156     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2157       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2158
2159     Standard_ASSERT_RETURN (aTriangleSet != NULL,
2160       "Error: Failed to get triangulation of OpenGL element", Standard_False);
2161
2162     aTotalVerticesNb += aTriangleSet->Vertices.size();
2163     aTotalElementsNb += aTriangleSet->Elements.size();
2164
2165     Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2166       "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2167
2168     aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2169   }
2170
2171   aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2172
2173   if (aTotalBVHNodesNb != 0)
2174   {
2175     aResult &= mySceneNodeInfoTexture->Init (
2176       theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*>  (NULL));
2177     aResult &= mySceneMinPointTexture->Init (
2178       theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2179     aResult &= mySceneMaxPointTexture->Init (
2180       theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2181   }
2182
2183   if (!aResult)
2184   {
2185 #ifdef RAY_TRACE_PRINT_INFO
2186     std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2187 #endif
2188     return Standard_False;
2189   }
2190
2191   if (aTotalElementsNb != 0)
2192   {
2193     aResult &= myGeometryTriangTexture->Init (
2194       theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2195   }
2196
2197   if (aTotalVerticesNb != 0)
2198   {
2199     aResult &= myGeometryVertexTexture->Init (
2200       theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2201     aResult &= myGeometryNormalTexture->Init (
2202       theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2203     aResult &= myGeometryTexCrdTexture->Init (
2204       theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2205   }
2206
2207   if (!aResult)
2208   {
2209 #ifdef RAY_TRACE_PRINT_INFO
2210     std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2211 #endif
2212     return Standard_False;
2213   }
2214
2215   const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2216
2217   if (aBVH->Length() > 0)
2218   {
2219     aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2220       reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2221     aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2222       reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2223     aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2224       reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2225   }
2226
2227   for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2228   {
2229     if (!aBVH->IsOuter (aNodeIdx))
2230       continue;
2231
2232     OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2233
2234     Standard_ASSERT_RETURN (aTriangleSet != NULL,
2235       "Error: Failed to get triangulation of OpenGL element", Standard_False);
2236
2237     Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2238
2239     Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2240       "Error: Failed to get offset for bottom-level BVH", Standard_False);
2241
2242     const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2243
2244     if (aBvhBuffersSize != 0)
2245     {
2246       aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2247         reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2248       aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2249         reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2250       aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2251         reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2252
2253       if (!aResult)
2254       {
2255 #ifdef RAY_TRACE_PRINT_INFO
2256         std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2257 #endif
2258         return Standard_False;
2259       }
2260     }
2261
2262     const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2263
2264     Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2265       "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2266
2267     if (!aTriangleSet->Vertices.empty())
2268     {
2269       aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2270         GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2271       aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2272         GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2273       aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2274         GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2275     }
2276
2277     const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2278
2279     Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2280       "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2281
2282     if (!aTriangleSet->Elements.empty())
2283     {
2284       aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2285                                                    reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2286     }
2287
2288     if (!aResult)
2289     {
2290 #ifdef RAY_TRACE_PRINT_INFO
2291       std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2292 #endif
2293       return Standard_False;
2294     }
2295   }
2296
2297   /////////////////////////////////////////////////////////////////////////////
2298   // Write material buffer
2299
2300   if (myRaytraceGeometry.Materials.size() != 0)
2301   {
2302     aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2303       GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2304
2305     if (!aResult)
2306     {
2307 #ifdef RAY_TRACE_PRINT_INFO
2308       std::cout << "Error: Failed to upload material buffer" << std::endl;
2309 #endif
2310       return Standard_False;
2311     }
2312   }
2313
2314   myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2315
2316 #ifdef RAY_TRACE_PRINT_INFO
2317
2318   Standard_ShortReal aMemTrgUsed = 0.f;
2319   Standard_ShortReal aMemBvhUsed = 0.f;
2320
2321   for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2322   {
2323     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2324
2325     aMemTrgUsed += static_cast<Standard_ShortReal> (
2326       aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2327     aMemTrgUsed += static_cast<Standard_ShortReal> (
2328       aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2329     aMemTrgUsed += static_cast<Standard_ShortReal> (
2330       aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2331     aMemTrgUsed += static_cast<Standard_ShortReal> (
2332       aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2333
2334     aMemBvhUsed += static_cast<Standard_ShortReal> (
2335       aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2336     aMemBvhUsed += static_cast<Standard_ShortReal> (
2337       aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2338     aMemBvhUsed += static_cast<Standard_ShortReal> (
2339       aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2340   }
2341
2342   aMemBvhUsed += static_cast<Standard_ShortReal> (
2343     myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2344   aMemBvhUsed += static_cast<Standard_ShortReal> (
2345     myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2346   aMemBvhUsed += static_cast<Standard_ShortReal> (
2347     myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2348
2349   std::cout << "GPU Memory Used (Mb):\n"
2350     << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2351     << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2352
2353 #endif
2354
2355   return aResult;
2356 }
2357
2358 // =======================================================================
2359 // function : updateRaytraceLightSources
2360 // purpose  : Updates 3D scene light sources for ray-tracing
2361 // =======================================================================
2362 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2363 {
2364   std::vector<Handle(Graphic3d_CLight)> aLightSources;
2365   myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2366   if (myShadingModel != Graphic3d_TOSM_UNLIT
2367   && !myLights.IsNull())
2368   {
2369     const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
2370     myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
2371
2372     // move positional light sources at the front of the list
2373     aLightSources.reserve (myLights->Extent());
2374     for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2375          aLightIter.More(); aLightIter.Next())
2376     {
2377       const Graphic3d_CLight& aLight = *aLightIter.Value();
2378       if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2379       {
2380         aLightSources.push_back (aLightIter.Value());
2381       }
2382     }
2383
2384     for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2385          aLightIter.More(); aLightIter.Next())
2386     {
2387       if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2388       {
2389         aLightSources.push_back (aLightIter.Value());
2390       }
2391     }
2392   }
2393
2394   // get number of 'real' (not ambient) light sources
2395   const size_t aNbLights = aLightSources.size();
2396   Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2397   if (wasUpdated)
2398   {
2399     myRaytraceGeometry.Sources.resize (aNbLights);
2400   }
2401
2402   for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2403   {
2404     const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2405     const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2406     BVH_Vec4f aEmission  (aLightColor.r() * aLight.Intensity(),
2407                           aLightColor.g() * aLight.Intensity(),
2408                           aLightColor.b() * aLight.Intensity(),
2409                           1.0f);
2410
2411     BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
2412                          -aLight.PackedDirection().y(),
2413                          -aLight.PackedDirection().z(),
2414                          0.0f);
2415
2416     if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2417     {
2418       aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2419                              static_cast<float>(aLight.Position().Y()),
2420                              static_cast<float>(aLight.Position().Z()),
2421                              1.0f);
2422
2423       // store smoothing radius in W-component
2424       aEmission.w() = Max (aLight.Smoothness(), 0.f);
2425     }
2426     else
2427     {
2428       // store cosine of smoothing angle in W-component
2429       aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2430     }
2431
2432     if (aLight.IsHeadlight())
2433     {
2434       aPosition = theInvModelView * aPosition;
2435     }
2436
2437     for (int aK = 0; aK < 4; ++aK)
2438     {
2439       wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2440                  || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2441     }
2442
2443     if (wasUpdated)
2444     {
2445       myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2446     }
2447
2448     ++aRealIdx;
2449   }
2450
2451   if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2452   {
2453     myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2454   }
2455
2456   if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2457   {
2458     const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2459     if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2460     {
2461 #ifdef RAY_TRACE_PRINT_INFO
2462       std::cout << "Error: Failed to upload light source buffer" << std::endl;
2463 #endif
2464       return Standard_False;
2465     }
2466
2467     myAccumFrames = 0; // accumulation should be restarted
2468   }
2469
2470   return Standard_True;
2471 }
2472
2473 // =======================================================================
2474 // function : setUniformState
2475 // purpose  : Sets uniform state for the given ray-tracing shader program
2476 // =======================================================================
2477 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        theProgramId,
2478                                                const Standard_Integer        theWinSizeX,
2479                                                const Standard_Integer        theWinSizeY,
2480                                                Graphic3d_Camera::Projection  theProjection,
2481                                                const Handle(OpenGl_Context)& theGlContext)
2482 {
2483   // Get projection state
2484   OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2485
2486   OpenGl_Mat4 aViewPrjMat;
2487   OpenGl_Mat4 anUnviewMat;
2488   OpenGl_Vec3 aOrigins[4];
2489   OpenGl_Vec3 aDirects[4];
2490
2491   if (myCamera->IsOrthographic()
2492    || !myRenderParams.IsGlobalIlluminationEnabled)
2493   {
2494     updateCamera (myCamera->OrientationMatrixF(),
2495                   aCntxProjectionState.Current(),
2496                   aOrigins,
2497                   aDirects,
2498                   aViewPrjMat,
2499                   anUnviewMat);
2500   }
2501   else
2502   {
2503     updatePerspCameraPT (myCamera->OrientationMatrixF(),
2504                          aCntxProjectionState.Current(),
2505                          theProjection,
2506                          aViewPrjMat,
2507                          anUnviewMat,
2508                          theWinSizeX,
2509                          theWinSizeY);
2510   }
2511
2512   Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2513                                            ? myRaytraceProgram
2514                                            : myPostFSAAProgram;
2515
2516   if (theProgram.IsNull())
2517   {
2518     return Standard_False;
2519   }
2520   
2521   theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2522   theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2523   theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2524   theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2525   theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2526
2527   theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2528   theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2529   
2530   // Set camera state
2531   theProgram->SetUniform (theGlContext,
2532     myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2533   theProgram->SetUniform (theGlContext,
2534     myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2535   theProgram->SetUniform (theGlContext,
2536     myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2537   theProgram->SetUniform (theGlContext,
2538     myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2539   theProgram->SetUniform (theGlContext,
2540     myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2541   theProgram->SetUniform (theGlContext,
2542     myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2543   theProgram->SetUniform (theGlContext,
2544     myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2545   theProgram->SetUniform (theGlContext,
2546     myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2547   theProgram->SetUniform (theGlContext,
2548     myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2549   theProgram->SetUniform (theGlContext,
2550     myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2551
2552   // Set screen dimensions
2553   myRaytraceProgram->SetUniform (theGlContext,
2554     myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2555   myRaytraceProgram->SetUniform (theGlContext,
2556     myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2557
2558   // Set 3D scene parameters
2559   theProgram->SetUniform (theGlContext,
2560     myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2561   theProgram->SetUniform (theGlContext,
2562     myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2563
2564   // Set light source parameters
2565   const Standard_Integer aLightSourceBufferSize =
2566     static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2567   
2568   theProgram->SetUniform (theGlContext,
2569     myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2570
2571   // Set array of 64-bit texture handles
2572   if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2573   {
2574     const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2575
2576     theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2577       static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2578   }
2579
2580   // Set background colors (only vertical gradient background supported)
2581   OpenGl_Vec4 aBackColorTop = myBgColor, aBackColorBot = myBgColor;
2582   if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2583    && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
2584   {
2585     aBackColorTop = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0);
2586     aBackColorBot = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1);
2587   }
2588   aBackColorTop = theGlContext->Vec4FromQuantityColor (aBackColorTop);
2589   aBackColorBot = theGlContext->Vec4FromQuantityColor (aBackColorBot);
2590   theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColorTop);
2591   theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColorBot);
2592
2593   // Set environment map parameters
2594   const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
2595                                                ||  myTextureEnv->IsEmpty()
2596                                                || !myTextureEnv->First()->IsValid();
2597
2598   theProgram->SetUniform (theGlContext,
2599     myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2600
2601   theProgram->SetUniform (theGlContext,
2602     myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ?  1 : 0);
2603
2604   if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2605   {
2606     theProgram->SetUniform (theGlContext,
2607       myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2608
2609     theProgram->SetUniform (theGlContext,
2610       myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2611
2612     // Check whether we should restart accumulation for run-time parameters
2613     if (myRenderParams.RadianceClampingValue       != myRaytraceParameters.RadianceClampingValue
2614      || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2615     {
2616       myAccumFrames = 0; // accumulation should be restarted
2617
2618       myRaytraceParameters.RadianceClampingValue  = myRenderParams.RadianceClampingValue;
2619       myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2620     }
2621   }
2622   else // RT parameters
2623   {
2624     // Set ambient light source
2625     theProgram->SetUniform (theGlContext,
2626       myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2627
2628     // Enable/disable run-time ray-tracing effects
2629     theProgram->SetUniform (theGlContext,
2630       myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ?  1 : 0);
2631     theProgram->SetUniform (theGlContext,
2632       myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ?  1 : 0);
2633   }
2634
2635   return Standard_True;
2636 }
2637
2638 // =======================================================================
2639 // function : bindRaytraceTextures
2640 // purpose  : Binds ray-trace textures to corresponding texture units
2641 // =======================================================================
2642 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2643                                         int theStereoView)
2644 {
2645   if (myRaytraceParameters.AdaptiveScreenSampling
2646    && myRaytraceParameters.GlobalIllumination)
2647   {
2648   #if !defined(GL_ES_VERSION_2_0)
2649     theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2650                                               myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2651     theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2652                                               myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2653     if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2654     {
2655       theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2656                                                 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2657     }
2658     else
2659     {
2660       theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2661                                                 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2662     }
2663   #else
2664     (void )theStereoView;
2665   #endif
2666   }
2667
2668   if (!myTextureEnv.IsNull()
2669    && !myTextureEnv->IsEmpty()
2670    &&  myTextureEnv->First()->IsValid())
2671   {
2672     myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
2673   }
2674
2675   mySceneMinPointTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2676   mySceneMaxPointTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2677   mySceneNodeInfoTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2678   myGeometryVertexTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2679   myGeometryNormalTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2680   myGeometryTexCrdTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2681   myGeometryTriangTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2682   mySceneTransformTexture  ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2683   myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2684   myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2685 }
2686
2687 // =======================================================================
2688 // function : unbindRaytraceTextures
2689 // purpose  : Unbinds ray-trace textures from corresponding texture units
2690 // =======================================================================
2691 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2692 {
2693   mySceneMinPointTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2694   mySceneMaxPointTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2695   mySceneNodeInfoTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2696   myGeometryVertexTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2697   myGeometryNormalTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2698   myGeometryTexCrdTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2699   myGeometryTriangTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2700   mySceneTransformTexture  ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2701   myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2702   myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2703
2704   theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2705 }
2706
2707 // =======================================================================
2708 // function : runRaytraceShaders
2709 // purpose  : Runs ray-tracing shader programs
2710 // =======================================================================
2711 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer        theSizeX,
2712                                                   const Standard_Integer        theSizeY,
2713                                                   Graphic3d_Camera::Projection  theProjection,
2714                                                   OpenGl_FrameBuffer*           theReadDrawFbo,
2715                                                   const Handle(OpenGl_Context)& theGlContext)
2716 {
2717   Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2718
2719   aResult &= setUniformState (0,
2720                               theSizeX,
2721                               theSizeY,
2722                               theProjection,
2723                               theGlContext);
2724
2725   if (myRaytraceParameters.GlobalIllumination) // path tracing
2726   {
2727     aResult &= runPathtrace    (theSizeX, theSizeY, theProjection, theGlContext);
2728     aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
2729   }
2730   else // Whitted-style ray-tracing
2731   {
2732     aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2733   }
2734
2735   return aResult;
2736 }
2737
2738 // =======================================================================
2739 // function : runRaytrace
2740 // purpose  : Runs Whitted-style ray-tracing
2741 // =======================================================================
2742 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSizeX,
2743                                            const Standard_Integer        theSizeY,
2744                                            Graphic3d_Camera::Projection  theProjection,
2745                                            OpenGl_FrameBuffer*           theReadDrawFbo,
2746                                            const Handle(OpenGl_Context)& theGlContext)
2747 {
2748   Standard_Boolean aResult = Standard_True;
2749
2750   // Choose proper set of frame buffers for stereo rendering
2751   const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2752   bindRaytraceTextures (theGlContext, aFBOIdx);
2753
2754   if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2755   {
2756     myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2757
2758     glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2759   }
2760
2761   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2762
2763   if (myRenderParams.IsAntialiasingEnabled)
2764   {
2765     glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2766
2767     // bind ray-tracing output image as input
2768     myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2769
2770     aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2771
2772     aResult &= setUniformState (1 /* FSAA ID */,
2773                                 theSizeX,
2774                                 theSizeY,
2775                                 theProjection,
2776                                 theGlContext);
2777
2778     // Perform multi-pass adaptive FSAA using ping-pong technique.
2779     // We use 'FLIPTRI' sampling pattern changing for every pixel
2780     // (3 additional samples per pixel, the 1st sample is already
2781     // available from initial ray-traced image).
2782     for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2783     {
2784       GLfloat aOffsetX = 1.f / theSizeX;
2785       GLfloat aOffsetY = 1.f / theSizeY;
2786
2787       if (anIt == 1)
2788       {
2789         aOffsetX *= -0.55f;
2790         aOffsetY *=  0.55f;
2791       }
2792       else if (anIt == 2)
2793       {
2794         aOffsetX *=  0.00f;
2795         aOffsetY *= -0.55f;
2796       }
2797       else if (anIt == 3)
2798       {
2799         aOffsetX *= 0.55f;
2800         aOffsetY *= 0.00f;
2801       }
2802
2803       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2804         myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2805       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2806         myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2807       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2808         myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2809
2810       Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2811                                                ? myRaytraceFBO2[aFBOIdx]
2812                                                : myRaytraceFBO1[aFBOIdx];
2813
2814       aFramebuffer->BindBuffer (theGlContext);
2815
2816       // perform adaptive FSAA pass
2817       theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2818
2819       aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2820     }
2821
2822     const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2823     const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2824
2825     glEnable (GL_DEPTH_TEST);
2826
2827     // Display filtered image
2828     theGlContext->BindProgram (myOutImageProgram);
2829
2830     if (theReadDrawFbo != NULL)
2831     {
2832       theReadDrawFbo->BindBuffer (theGlContext);
2833     }
2834     else
2835     {
2836       aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2837     }
2838
2839     aRenderImageFramebuffer->ColorTexture()       ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2840     aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2841
2842     // copy the output image with depth values
2843     theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2844
2845     aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2846     aRenderImageFramebuffer->ColorTexture()       ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2847   }
2848
2849   unbindRaytraceTextures (theGlContext);
2850
2851   theGlContext->BindProgram (NULL);
2852
2853   return aResult;
2854 }
2855
2856 // =======================================================================
2857 // function : runPathtrace
2858 // purpose  : Runs path tracing shader
2859 // =======================================================================
2860 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer              theSizeX,
2861                                             const Standard_Integer              theSizeY,
2862                                             const Graphic3d_Camera::Projection  theProjection,
2863                                             const Handle(OpenGl_Context)&       theGlContext)
2864 {
2865   if (myToUpdateEnvironmentMap) // check whether the map was changed
2866   {
2867     myAccumFrames = myToUpdateEnvironmentMap = 0;
2868   }
2869   
2870   if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2871    || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2872   {
2873     myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2874     myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2875     myAccumFrames = 0;
2876   }
2877
2878   // Choose proper set of frame buffers for stereo rendering
2879   const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2880
2881   if (myRaytraceParameters.AdaptiveScreenSampling)
2882   {
2883     if (myAccumFrames == 0)
2884     {
2885       myTileSampler.Reset(); // reset tile sampler to its initial state
2886
2887       // Adaptive sampling is starting at the second frame
2888       if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2889       {
2890         myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2891       }
2892       else
2893       {
2894         myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2895       }
2896
2897     #if !defined(GL_ES_VERSION_2_0)
2898       theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2899     #endif
2900     }
2901
2902     // Clear adaptive screen sampling images
2903   #if !defined(GL_ES_VERSION_2_0)
2904     theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2905   #endif
2906   }
2907
2908   bindRaytraceTextures (theGlContext, aFBOIdx);
2909
2910   const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2911   anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2912
2913   // Set frame accumulation weight
2914   myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
2915
2916   // Set image uniforms for render program
2917   if (myRaytraceParameters.AdaptiveScreenSampling)
2918   {
2919     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
2920     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage],  OpenGl_RT_TileSamplesImage);
2921     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2922     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
2923   }
2924
2925   const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2926   aRenderImageFramebuffer->BindBuffer (theGlContext);
2927   if (myRaytraceParameters.AdaptiveScreenSampling
2928    && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2929   {
2930     // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
2931     // redirected to inner tiles (full tile size) are drawn entirely
2932     const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
2933     glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
2934   }
2935
2936   // Generate for the given RNG seed
2937   glDisable (GL_DEPTH_TEST);
2938
2939   // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
2940   // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
2941   //
2942   // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
2943   // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
2944   // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
2945   //
2946   // Single-pass rendering is more optimal due to smaller amount of draw calls,
2947   // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
2948   // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
2949   // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
2950   const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
2951                     && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
2952                       ? myTileSampler.MaxTileSamples()
2953                       : 1;
2954   if (myAccumFrames == 0)
2955   {
2956     myRNG.SetSeed(); // start RNG from beginning
2957   }
2958   for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
2959   {
2960     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2961     theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2962     if (myRaytraceParameters.AdaptiveScreenSampling)
2963     {
2964     #if !defined(GL_ES_VERSION_2_0)
2965       theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
2966     #endif
2967     }
2968   }
2969   aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2970
2971   if (myRaytraceParameters.AdaptiveScreenSampling
2972    && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2973   {
2974     glViewport (0, 0, theSizeX, theSizeY);
2975   }
2976   return true;
2977 }
2978
2979 // =======================================================================
2980 // function : runPathtraceOut
2981 // purpose  :
2982 // =======================================================================
2983 Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection  theProjection,
2984                                                OpenGl_FrameBuffer*                 theReadDrawFbo,
2985                                                const Handle(OpenGl_Context)&       theGlContext)
2986 {
2987   // Output accumulated path traced image
2988   theGlContext->BindProgram (myOutImageProgram);
2989
2990   // Choose proper set of frame buffers for stereo rendering
2991   const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2992
2993   if (myRaytraceParameters.AdaptiveScreenSampling)
2994   {
2995     // Set uniforms for display program
2996     myOutImageProgram->SetUniform (theGlContext, "uRenderImage",   OpenGl_RT_OutputImage);
2997     myOutImageProgram->SetUniform (theGlContext, "uAccumFrames",   myAccumFrames);
2998     myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
2999     myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ?  1 : 0);
3000     myOutImageProgram->SetUniform (theGlContext, "uTileSize",      myTileSampler.TileSize());
3001     myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
3002   }
3003
3004   if (myRaytraceParameters.GlobalIllumination)
3005   {
3006     myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3007     switch (myRaytraceParameters.ToneMappingMethod)
3008     {
3009       case Graphic3d_ToneMappingMethod_Disabled:
3010         break;
3011       case Graphic3d_ToneMappingMethod_Filmic:
3012         myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3013         break;
3014     }
3015   }
3016
3017   if (theReadDrawFbo != NULL)
3018   {
3019     theReadDrawFbo->BindBuffer (theGlContext);
3020   }
3021
3022   const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3023   aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3024
3025   // Copy accumulated image with correct depth values
3026   glEnable (GL_DEPTH_TEST);
3027   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3028
3029   aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3030
3031   if (myRaytraceParameters.AdaptiveScreenSampling)
3032   {
3033     // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3034     myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
3035     if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3036     {
3037       myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3038     }
3039     else
3040     {
3041       myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3042     }
3043   }
3044
3045   unbindRaytraceTextures (theGlContext);
3046   theGlContext->BindProgram (NULL);
3047   return true;
3048 }
3049
3050 // =======================================================================
3051 // function : raytrace
3052 // purpose  : Redraws the window using OpenGL/GLSL ray-tracing
3053 // =======================================================================
3054 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer        theSizeX,
3055                                         const Standard_Integer        theSizeY,
3056                                         Graphic3d_Camera::Projection  theProjection,
3057                                         OpenGl_FrameBuffer*           theReadDrawFbo,
3058                                         const Handle(OpenGl_Context)& theGlContext)
3059 {
3060   if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
3061   {
3062     return Standard_False;
3063   }
3064
3065   if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3066   {
3067     return Standard_False;
3068   }
3069
3070   OpenGl_Mat4 aLightSourceMatrix;
3071
3072   // Get inversed model-view matrix for transforming lights
3073   myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3074
3075   if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3076   {
3077     return Standard_False;
3078   }
3079
3080   // Generate image using Whitted-style ray-tracing or path tracing
3081   if (myIsRaytraceDataValid)
3082   {
3083     myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3084
3085     if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3086     {
3087       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3088         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3089     }
3090
3091     glDisable (GL_BLEND);
3092
3093     const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3094                                                          theSizeY,
3095                                                          theProjection,
3096                                                          theReadDrawFbo,
3097                                                          theGlContext);
3098
3099     if (!aResult)
3100     {
3101       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3102         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3103     }
3104
3105     if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3106     {
3107       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3108         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3109     }
3110
3111     myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3112   }
3113
3114   return Standard_True;
3115 }