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