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