adaeb09ce145203849f623580eea42f0d7738210
[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     for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
624     {
625       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute       (anAttribIter);
626       const size_t               anOffset = anAttribs->AttributeOffset (anAttribIter);
627       if (anAttrib.Id == Graphic3d_TOA_POS)
628       {
629         if (anAttrib.DataType == Graphic3d_TOD_VEC3
630          || anAttrib.DataType == Graphic3d_TOD_VEC4)
631         {
632           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
633           {
634             aSet->Vertices.push_back (
635               *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
636           }
637         }
638         else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
639         {
640           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
641           {
642             const Standard_ShortReal* aCoords =
643               reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
644
645             aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
646           }
647         }
648       }
649       else if (anAttrib.Id == Graphic3d_TOA_NORM)
650       {
651         if (anAttrib.DataType == Graphic3d_TOD_VEC3
652          || anAttrib.DataType == Graphic3d_TOD_VEC4)
653         {
654           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
655           {
656             aSet->Normals.push_back (
657               *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
658           }
659         }
660       }
661       else if (anAttrib.Id == Graphic3d_TOA_UV)
662       {
663         if (anAttrib.DataType == Graphic3d_TOD_VEC2)
664         {
665           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
666           {
667             aSet->TexCrds.push_back (
668               *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
669           }
670         }
671       }
672     }
673
674     if (aSet->Normals.size() != aSet->Vertices.size())
675     {
676       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
677       {
678         aSet->Normals.push_back (BVH_Vec3f());
679       }
680     }
681
682     if (aSet->TexCrds.size() != aSet->Vertices.size())
683     {
684       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
685       {
686         aSet->TexCrds.push_back (BVH_Vec2f());
687       }
688     }
689
690     if (theTransform != NULL)
691     {
692       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
693       {
694         BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
695
696         BVH_Vec4f aTransVertex = *theTransform *
697           BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
698
699         aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
700       }
701       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
702       {
703         BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
704
705         BVH_Vec4f aTransNormal = aNormalMatrix *
706           BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
707
708         aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
709       }
710     }
711
712     if (!aBounds.IsNull())
713     {
714       for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
715       {
716         const Standard_Integer aVertNum = aBounds->Bounds[aBound];
717
718         if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
719         {
720           aSet.Nullify();
721           return Handle(OpenGl_TriangleSet)();
722         }
723
724         aBoundStart += aVertNum;
725       }
726     }
727     else
728     {
729       const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
730
731       if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
732       {
733         aSet.Nullify();
734         return Handle(OpenGl_TriangleSet)();
735       }
736     }
737   }
738
739   if (aSet->Size() != 0)
740   {
741     aSet->MarkDirty();
742   }
743
744   return aSet;
745 }
746
747 // =======================================================================
748 // function : addRaytraceVertexIndices
749 // purpose  : Adds vertex indices to ray-traced scene geometry
750 // =======================================================================
751 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet&                  theSet,
752                                                         const Standard_Integer               theMatID,
753                                                         const Standard_Integer               theCount,
754                                                         const Standard_Integer               theOffset,
755                                                         const OpenGl_PrimitiveArray&         theArray)
756 {
757   switch (theArray.DrawMode())
758   {
759     case GL_TRIANGLES:      return addRaytraceTriangleArray        (theSet, theMatID, theCount, theOffset, theArray.Indices());
760     case GL_TRIANGLE_FAN:   return addRaytraceTriangleFanArray     (theSet, theMatID, theCount, theOffset, theArray.Indices());
761     case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray   (theSet, theMatID, theCount, theOffset, theArray.Indices());
762   #if !defined(GL_ES_VERSION_2_0)
763     case GL_QUAD_STRIP:     return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
764     case GL_QUADS:          return addRaytraceQuadrangleArray      (theSet, theMatID, theCount, theOffset, theArray.Indices());
765     case GL_POLYGON:        return addRaytracePolygonArray         (theSet, theMatID, theCount, theOffset, theArray.Indices());
766   #endif
767   }
768
769   return Standard_False;
770 }
771
772 // =======================================================================
773 // function : addRaytraceTriangleArray
774 // purpose  : Adds OpenGL triangle array to ray-traced scene geometry
775 // =======================================================================
776 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
777                                                         const Standard_Integer               theMatID,
778                                                         const Standard_Integer               theCount,
779                                                         const Standard_Integer               theOffset,
780                                                         const Handle(Graphic3d_IndexBuffer)& theIndices)
781 {
782   if (theCount < 3)
783   {
784     return Standard_True;
785   }
786
787   theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
788
789   if (!theIndices.IsNull())
790   {
791     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
792     {
793       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
794                                             theIndices->Index (aVert + 1),
795                                             theIndices->Index (aVert + 2),
796                                             theMatID));
797     }
798   }
799   else
800   {
801     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
802     {
803       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
804     }
805   }
806
807   return Standard_True;
808 }
809
810 // =======================================================================
811 // function : addRaytraceTriangleFanArray
812 // purpose  : Adds OpenGL triangle fan array to ray-traced scene geometry
813 // =======================================================================
814 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
815                                                            const Standard_Integer               theMatID,
816                                                            const Standard_Integer               theCount,
817                                                            const Standard_Integer               theOffset,
818                                                            const Handle(Graphic3d_IndexBuffer)& theIndices)
819 {
820   if (theCount < 3)
821   {
822     return Standard_True;
823   }
824
825   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
826
827   if (!theIndices.IsNull())
828   {
829     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
830     {
831       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
832                                             theIndices->Index (aVert + 1),
833                                             theIndices->Index (aVert + 2),
834                                             theMatID));
835     }
836   }
837   else
838   {
839     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
840     {
841       theSet.Elements.push_back (BVH_Vec4i (theOffset,
842                                             aVert + 1,
843                                             aVert + 2,
844                                             theMatID));
845     }
846   }
847
848   return Standard_True;
849 }
850
851 // =======================================================================
852 // function : addRaytraceTriangleStripArray
853 // purpose  : Adds OpenGL triangle strip array to ray-traced scene geometry
854 // =======================================================================
855 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
856                                                              const Standard_Integer               theMatID,
857                                                              const Standard_Integer               theCount,
858                                                              const Standard_Integer               theOffset,
859                                                              const Handle(Graphic3d_IndexBuffer)& theIndices)
860 {
861   if (theCount < 3)
862   {
863     return Standard_True;
864   }
865
866   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
867
868   if (!theIndices.IsNull())
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 (theIndices->Index (aVert + (aCW ? 1 : 0)),
873                                             theIndices->Index (aVert + (aCW ? 0 : 1)),
874                                             theIndices->Index (aVert + 2),
875                                             theMatID));
876     }
877   }
878   else
879   {
880     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
881     {
882       theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
883                                             aVert + (aCW ? 0 : 1),
884                                             aVert + 2,
885                                             theMatID));
886     }
887   }
888
889   return Standard_True;
890 }
891
892 // =======================================================================
893 // function : addRaytraceQuadrangleArray
894 // purpose  : Adds OpenGL quad array to ray-traced scene geometry
895 // =======================================================================
896 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
897                                                           const Standard_Integer               theMatID,
898                                                           const Standard_Integer               theCount,
899                                                           const Standard_Integer               theOffset,
900                                                           const Handle(Graphic3d_IndexBuffer)& theIndices)
901 {
902   if (theCount < 4)
903   {
904     return Standard_True;
905   }
906
907   theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
908
909   if (!theIndices.IsNull())
910   {
911     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
912     {
913       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
914                                             theIndices->Index (aVert + 1),
915                                             theIndices->Index (aVert + 2),
916                                             theMatID));
917       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
918                                             theIndices->Index (aVert + 2),
919                                             theIndices->Index (aVert + 3),
920                                             theMatID));
921     }
922   }
923   else
924   {
925     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
926     {
927       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
928                                             theMatID));
929       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
930                                             theMatID));
931     }
932   }
933
934   return Standard_True;
935 }
936
937 // =======================================================================
938 // function : addRaytraceQuadrangleStripArray
939 // purpose  : Adds OpenGL quad strip array to ray-traced scene geometry
940 // =======================================================================
941 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
942                                                                const Standard_Integer               theMatID,
943                                                                const Standard_Integer               theCount,
944                                                                const Standard_Integer               theOffset,
945                                                                const Handle(Graphic3d_IndexBuffer)& theIndices)
946 {
947   if (theCount < 4)
948   {
949     return Standard_True;
950   }
951
952   theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
953
954   if (!theIndices.IsNull())
955   {
956     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
957     {
958       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
959                                             theIndices->Index (aVert + 1),
960                                             theIndices->Index (aVert + 2),
961                                             theMatID));
962
963       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
964                                             theIndices->Index (aVert + 3),
965                                             theIndices->Index (aVert + 2),
966                                             theMatID));
967     }
968   }
969   else
970   {
971     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
972     {
973       theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
974                                             aVert + 1,
975                                             aVert + 2,
976                                             theMatID));
977
978       theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
979                                             aVert + 3,
980                                             aVert + 2,
981                                             theMatID));
982     }
983   }
984
985   return Standard_True;
986 }
987
988 // =======================================================================
989 // function : addRaytracePolygonArray
990 // purpose  : Adds OpenGL polygon array to ray-traced scene geometry
991 // =======================================================================
992 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
993                                                        const Standard_Integer               theMatID,
994                                                        const Standard_Integer               theCount,
995                                                        const Standard_Integer               theOffset,
996                                                        const Handle(Graphic3d_IndexBuffer)& theIndices)
997 {
998   if (theCount < 3)
999   {
1000     return Standard_True;
1001   }
1002
1003   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
1004
1005   if (!theIndices.IsNull())
1006   {
1007     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1008     {
1009       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
1010                                             theIndices->Index (aVert + 1),
1011                                             theIndices->Index (aVert + 2),
1012                                             theMatID));
1013     }
1014   }
1015   else
1016   {
1017     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1018     {
1019       theSet.Elements.push_back (BVH_Vec4i (theOffset,
1020                                             aVert + 1,
1021                                             aVert + 2,
1022                                             theMatID));
1023     }
1024   }
1025
1026   return Standard_True;
1027 }
1028
1029 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1030
1031 // =======================================================================
1032 // function : Source
1033 // purpose  : Returns shader source combined with prefix
1034 // =======================================================================
1035 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1036 {
1037   const TCollection_AsciiString aVersion = "#version 140";
1038
1039   if (myPrefix.IsEmpty())
1040   {
1041     return aVersion + "\n" + mySource;
1042   }
1043
1044   return aVersion + "\n" + myPrefix + "\n" + mySource;
1045 }
1046
1047 // =======================================================================
1048 // function : LoadFromFiles
1049 // purpose  : Loads shader source from specified files
1050 // =======================================================================
1051 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1052                                                            const TCollection_AsciiString& thePrefix)
1053 {
1054   myError.Clear();
1055   mySource.Clear();
1056   myPrefix = thePrefix;
1057
1058   TCollection_AsciiString aMissingFiles;
1059   for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1060   {
1061     OSD_File aFile (theFileNames[anIndex]);
1062     if (aFile.Exists())
1063     {
1064       aFile.Open (OSD_ReadOnly, OSD_Protection());
1065     }
1066     if (!aFile.IsOpen())
1067     {
1068       if (!aMissingFiles.IsEmpty())
1069       {
1070         aMissingFiles += ", ";
1071       }
1072       aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1073       continue;
1074     }
1075     else if (!aMissingFiles.IsEmpty())
1076     {
1077       aFile.Close();
1078       continue;
1079     }
1080
1081     TCollection_AsciiString aSource;
1082     aFile.Read (aSource, (Standard_Integer) aFile.Size());
1083     if (!aSource.IsEmpty())
1084     {
1085       mySource += TCollection_AsciiString ("\n") + aSource;
1086     }
1087     aFile.Close();
1088   }
1089
1090   if (!aMissingFiles.IsEmpty())
1091   {
1092     myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1093     return Standard_False;
1094   }
1095   return Standard_True;
1096 }
1097
1098 // =======================================================================
1099 // function : LoadFromStrings
1100 // purpose  :
1101 // =======================================================================
1102 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1103                                                              const TCollection_AsciiString& thePrefix)
1104 {
1105   myError.Clear();
1106   mySource.Clear();
1107   myPrefix = thePrefix;
1108
1109   for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1110   {
1111     TCollection_AsciiString aSource = theStrings[anIndex];
1112     if (!aSource.IsEmpty())
1113     {
1114       mySource += TCollection_AsciiString ("\n") + aSource;
1115     }
1116   }
1117   return Standard_True;
1118 }
1119
1120 // =======================================================================
1121 // function : generateShaderPrefix
1122 // purpose  : Generates shader prefix based on current ray-tracing options
1123 // =======================================================================
1124 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1125 {
1126   TCollection_AsciiString aPrefixString =
1127     TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1128     TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1129
1130   if (myRaytraceParameters.TransparentShadows)
1131   {
1132     aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1133   }
1134
1135   // If OpenGL driver supports bindless textures and texturing
1136   // is actually used, activate texturing in ray-tracing mode
1137   if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1138   {
1139     aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1140       TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1141   }
1142
1143   if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1144   {
1145     aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1146
1147     if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1148     {
1149       // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
1150       if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1151       {
1152         aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") +
1153           TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize());
1154       }
1155     }
1156
1157     if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1158     {
1159       aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1160     }
1161
1162     switch (myRaytraceParameters.ToneMappingMethod)
1163     {
1164       case Graphic3d_ToneMappingMethod_Disabled:
1165         break;
1166       case Graphic3d_ToneMappingMethod_Filmic:
1167         aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1168         break;
1169     }
1170   }
1171
1172   if (myRaytraceParameters.DepthOfField)
1173   {
1174     aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1175   }
1176
1177   return aPrefixString;
1178 }
1179
1180 // =======================================================================
1181 // function : safeFailBack
1182 // purpose  : Performs safe exit when shaders initialization fails
1183 // =======================================================================
1184 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1185                                             const Handle(OpenGl_Context)&     theGlContext)
1186 {
1187   theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1188     GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1189
1190   myRaytraceInitStatus = OpenGl_RT_FAIL;
1191
1192   releaseRaytraceResources (theGlContext);
1193
1194   return Standard_False;
1195 }
1196
1197 // =======================================================================
1198 // function : initShader
1199 // purpose  : Creates new shader object with specified source
1200 // =======================================================================
1201 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum                  theType,
1202                                                      const ShaderSource&           theSource,
1203                                                      const Handle(OpenGl_Context)& theGlContext)
1204 {
1205   Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1206
1207   if (!aShader->Create (theGlContext))
1208   {
1209     const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1210       (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1211
1212     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1213       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1214
1215     aShader->Release (theGlContext.operator->());
1216
1217     return Handle(OpenGl_ShaderObject)();
1218   }
1219
1220   if (!aShader->LoadSource (theGlContext, theSource.Source()))
1221   {
1222     const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1223       (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1224
1225     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1226       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1227
1228     aShader->Release (theGlContext.operator->());
1229
1230     return Handle(OpenGl_ShaderObject)();
1231   }
1232
1233   TCollection_AsciiString aBuildLog;
1234
1235   if (!aShader->Compile (theGlContext))
1236   {
1237     aShader->FetchInfoLog (theGlContext, aBuildLog);
1238
1239     const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1240       (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1241
1242     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1243       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1244
1245     aShader->Release (theGlContext.operator->());
1246
1247 #ifdef RAY_TRACE_PRINT_INFO
1248     std::cout << "Shader build log:\n" << aBuildLog << "\n";
1249 #endif
1250
1251     return Handle(OpenGl_ShaderObject)();
1252   }
1253   else if (theGlContext->caps->glslWarnings)
1254   {
1255     aShader->FetchInfoLog (theGlContext, aBuildLog);
1256
1257     if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1258     {
1259       const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1260         "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1261
1262       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1263         GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1264     }
1265
1266 #ifdef RAY_TRACE_PRINT_INFO
1267     std::cout << "Shader build log:\n" << aBuildLog << "\n";
1268 #endif
1269   }
1270
1271   return aShader;
1272 }
1273
1274 // =======================================================================
1275 // function : initProgram
1276 // purpose  : Creates GLSL program from the given shader objects
1277 // =======================================================================
1278 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)&      theGlContext,
1279                                                        const Handle(OpenGl_ShaderObject)& theVertShader,
1280                                                        const Handle(OpenGl_ShaderObject)& theFragShader)
1281 {
1282   Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
1283
1284   if (!aProgram->Create (theGlContext))
1285   {
1286     theVertShader->Release (theGlContext.operator->());
1287
1288     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1289       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1290
1291     return Handle(OpenGl_ShaderProgram)();
1292   }
1293
1294   if (!aProgram->AttachShader (theGlContext, theVertShader)
1295    || !aProgram->AttachShader (theGlContext, theFragShader))
1296   {
1297     theVertShader->Release (theGlContext.operator->());
1298
1299     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1300       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1301
1302     return Handle(OpenGl_ShaderProgram)();
1303   }
1304
1305   aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1306
1307   TCollection_AsciiString aLinkLog;
1308
1309   if (!aProgram->Link (theGlContext))
1310   {
1311     aProgram->FetchInfoLog (theGlContext, aLinkLog);
1312
1313     const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1314       "Failed to link shader program:\n") + aLinkLog;
1315
1316     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1317       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1318
1319     return Handle(OpenGl_ShaderProgram)();
1320   }
1321   else if (theGlContext->caps->glslWarnings)
1322   {
1323     aProgram->FetchInfoLog (theGlContext, aLinkLog);
1324     if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1325     {
1326       const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1327         "Shader program was linked with following warnings:\n") + aLinkLog;
1328
1329       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1330         GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1331     }
1332   }
1333
1334   return aProgram;
1335 }
1336
1337 // =======================================================================
1338 // function : initRaytraceResources
1339 // purpose  : Initializes OpenGL/GLSL shader programs
1340 // =======================================================================
1341 Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1342 {
1343   if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1344   {
1345     return Standard_False;
1346   }
1347
1348   Standard_Boolean aToRebuildShaders = Standard_False;
1349
1350   if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1351   {
1352     myRaytraceInitStatus = OpenGl_RT_NONE;
1353     releaseRaytraceResources (theGlContext, Standard_True);
1354     myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1355   }
1356
1357   if (myRaytraceInitStatus == OpenGl_RT_INIT)
1358   {
1359     if (!myIsRaytraceDataValid)
1360     {
1361       return Standard_True;
1362     }
1363
1364     const Standard_Integer aRequiredStackSize =
1365       myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1366
1367     if (myRaytraceParameters.StackSize < aRequiredStackSize)
1368     {
1369       myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1370
1371       aToRebuildShaders = Standard_True;
1372     }
1373     else
1374     {
1375       if (aRequiredStackSize < myRaytraceParameters.StackSize)
1376       {
1377         if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1378         {
1379           myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1380           aToRebuildShaders = Standard_True;
1381         }
1382       }
1383     }
1384
1385     Standard_Integer aNbTilesX = 8;
1386     Standard_Integer aNbTilesY = 8;
1387
1388     for (Standard_Integer anIdx = 0; aNbTilesX * aNbTilesY < myRenderParams.NbRayTracingTiles; ++anIdx)
1389     {
1390       (anIdx % 2 == 0 ? aNbTilesX : aNbTilesY) <<= 1;
1391     }
1392
1393     if (myRenderParams.RaytracingDepth             != myRaytraceParameters.NbBounces
1394      || myRenderParams.IsTransparentShadowEnabled  != myRaytraceParameters.TransparentShadows
1395      || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1396      || myRenderParams.TwoSidedBsdfModels          != myRaytraceParameters.TwoSidedBsdfModels
1397      || myRaytraceGeometry.HasTextures()           != myRaytraceParameters.UseBindlessTextures
1398      || aNbTilesX                                  != myRaytraceParameters.NbTilesX
1399      || aNbTilesY                                  != myRaytraceParameters.NbTilesY)
1400     {
1401       myRaytraceParameters.NbBounces           = myRenderParams.RaytracingDepth;
1402       myRaytraceParameters.TransparentShadows  = myRenderParams.IsTransparentShadowEnabled;
1403       myRaytraceParameters.GlobalIllumination  = myRenderParams.IsGlobalIlluminationEnabled;
1404       myRaytraceParameters.TwoSidedBsdfModels  = myRenderParams.TwoSidedBsdfModels;
1405       myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1406
1407 #ifdef RAY_TRACE_PRINT_INFO
1408       if (aNbTilesX != myRaytraceParameters.NbTilesX
1409        || aNbTilesY != myRaytraceParameters.NbTilesY)
1410       {
1411         std::cout << "Number of tiles X: " << aNbTilesX << "\n";
1412         std::cout << "Number of tiles Y: " << aNbTilesY << "\n";
1413       }
1414 #endif
1415
1416       myRaytraceParameters.NbTilesX = aNbTilesX;
1417       myRaytraceParameters.NbTilesY = aNbTilesY;
1418
1419       aToRebuildShaders = Standard_True;
1420     }
1421
1422     if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
1423     {
1424       myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1425       if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1426       {
1427         if (!theGlContext->HasRayTracingAdaptiveSampling())
1428         {
1429           // disable the feature if it is not supported
1430           myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1431           theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1432                                      "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
1433         }
1434       }
1435
1436       aToRebuildShaders = Standard_True;
1437     }
1438
1439     const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1440     if (myRaytraceParameters.DepthOfField != toEnableDof)
1441     {
1442       myRaytraceParameters.DepthOfField = toEnableDof;
1443       aToRebuildShaders = Standard_True;
1444     }
1445
1446     if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1447     {
1448       myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1449       aToRebuildShaders = true;
1450     }
1451
1452     if (aToRebuildShaders)
1453     {
1454       // Reject accumulated frames
1455       myAccumFrames = 0;
1456
1457       // Environment map should be updated
1458       myToUpdateEnvironmentMap = Standard_True;
1459
1460       const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1461
1462 #ifdef RAY_TRACE_PRINT_INFO
1463       std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1464 #endif
1465
1466       myRaytraceShaderSource.SetPrefix (aPrefixString);
1467       myPostFSAAShaderSource.SetPrefix (aPrefixString);
1468       myOutImageShaderSource.SetPrefix (aPrefixString);
1469
1470       if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
1471        || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source())
1472        || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source()))
1473       {
1474         return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
1475       }
1476
1477       TCollection_AsciiString aLog;
1478
1479       if (!myRaytraceShader->Compile (theGlContext)
1480        || !myPostFSAAShader->Compile (theGlContext)
1481        || !myOutImageShader->Compile (theGlContext))
1482       {
1483 #ifdef RAY_TRACE_PRINT_INFO
1484         myRaytraceShader->FetchInfoLog (theGlContext, aLog);
1485
1486         if (!aLog.IsEmpty())
1487         {
1488           std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1489         }
1490 #endif
1491         return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1492       }
1493
1494       myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1495       myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1496       myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1497
1498       if (!myRaytraceProgram->Link (theGlContext)
1499        || !myPostFSAAProgram->Link (theGlContext)
1500        || !myOutImageProgram->Link (theGlContext))
1501       {
1502 #ifdef RAY_TRACE_PRINT_INFO
1503         myRaytraceProgram->FetchInfoLog (theGlContext, aLog);
1504
1505         if (!aLog.IsEmpty())
1506         {
1507           std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1508         }
1509 #endif
1510         return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1511       }
1512     }
1513   }
1514
1515   if (myRaytraceInitStatus == OpenGl_RT_NONE)
1516   {
1517     myAccumFrames = 0; // accumulation should be restarted
1518
1519     if (!theGlContext->IsGlGreaterEqual (3, 1))
1520     {
1521       return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1522     }
1523     else if (!theGlContext->arbTboRGB32)
1524     {
1525       return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1526     }
1527     else if (!theGlContext->arbFBOBlit)
1528     {
1529       return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1530     }
1531
1532     myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1533
1534     const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1535     if (myIsRaytraceDataValid)
1536     {
1537       myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1538         myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1539     }
1540
1541     const TCollection_AsciiString aPrefixString  = generateShaderPrefix (theGlContext);
1542
1543 #ifdef RAY_TRACE_PRINT_INFO
1544     std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1545 #endif
1546
1547     ShaderSource aBasicVertShaderSrc;
1548     {
1549       if (!aShaderFolder.IsEmpty())
1550       {
1551         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1552         if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1553         {
1554           return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1555         }
1556       }
1557       else
1558       {
1559         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1560         aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1561       }
1562     }
1563
1564     {
1565       if (!aShaderFolder.IsEmpty())
1566       {
1567         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1568                                                    aShaderFolder + "/PathtraceBase.fs",
1569                                                    aShaderFolder + "/RaytraceRender.fs",
1570                                                    "" };
1571         if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1572         {
1573           return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1574         }
1575       }
1576       else
1577       {
1578         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1579                                                         Shaders_PathtraceBase_fs,
1580                                                         Shaders_RaytraceRender_fs,
1581                                                         "" };
1582         myRaytraceShaderSource.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 ray-trace vertex shader", theGlContext);
1589       }
1590
1591       myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1592       if (myRaytraceShader.IsNull())
1593       {
1594         aBasicVertShader->Release (theGlContext.operator->());
1595         return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1596       }
1597
1598       myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
1599       if (myRaytraceProgram.IsNull())
1600       {
1601         return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1602       }
1603     }
1604
1605     {
1606       if (!aShaderFolder.IsEmpty())
1607       {
1608         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1609         if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1610         {
1611           return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1612         }
1613       }
1614       else
1615       {
1616         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1617         myPostFSAAShaderSource.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 initialize FSAA vertex shader", theGlContext);
1624       }
1625
1626       myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1627       if (myPostFSAAShader.IsNull())
1628       {
1629         aBasicVertShader->Release (theGlContext.operator->());
1630         return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1631       }
1632
1633       myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
1634       if (myPostFSAAProgram.IsNull())
1635       {
1636         return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1637       }
1638     }
1639
1640     {
1641       if (!aShaderFolder.IsEmpty())
1642       {
1643         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1644         if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1645         {
1646           return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1647         }
1648       }
1649       else
1650       {
1651         const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1652         myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1653       }
1654
1655       Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1656       if (aBasicVertShader.IsNull())
1657       {
1658         return safeFailBack ("Failed to set vertex shader source", theGlContext);
1659       }
1660
1661       myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1662       if (myOutImageShader.IsNull())
1663       {
1664         aBasicVertShader->Release (theGlContext.operator->());
1665         return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1666       }
1667
1668       myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
1669       if (myOutImageProgram.IsNull())
1670       {
1671         return safeFailBack ("Failed to initialize display shader program", theGlContext);
1672       }
1673     }
1674   }
1675
1676   if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1677   {
1678     for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1679     {
1680       Handle(OpenGl_ShaderProgram)& aShaderProgram =
1681         (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1682
1683       theGlContext->BindProgram (aShaderProgram);
1684
1685       aShaderProgram->SetSampler (theGlContext,
1686         "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1687       aShaderProgram->SetSampler (theGlContext,
1688         "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1689       aShaderProgram->SetSampler (theGlContext,
1690         "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1691       aShaderProgram->SetSampler (theGlContext,
1692         "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1693       aShaderProgram->SetSampler (theGlContext,
1694         "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1695       aShaderProgram->SetSampler (theGlContext,
1696         "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1697       aShaderProgram->SetSampler (theGlContext,
1698         "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1699       aShaderProgram->SetSampler (theGlContext, 
1700         "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1701       aShaderProgram->SetSampler (theGlContext,
1702         "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1703       aShaderProgram->SetSampler (theGlContext,
1704         "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1705       aShaderProgram->SetSampler (theGlContext,
1706         "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1707
1708       if (anIndex == 1)
1709       {
1710         aShaderProgram->SetSampler (theGlContext,
1711           "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1712       }
1713       else
1714       {
1715         aShaderProgram->SetSampler (theGlContext,
1716           "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1717       }
1718
1719       myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1720         aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1721
1722       myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1723         aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1724       myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1725         aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1726       myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1727         aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1728       myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1729         aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1730       myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1731         aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1732       myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1733         aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1734       myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1735         aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1736       myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1737         aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1738       myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1739         aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1740       myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1741         aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1742
1743       myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1744         aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1745       myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1746         aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1747       myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1748         aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1749       myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1750         aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1751
1752       myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1753         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1754       myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1755         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1756       myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1757         aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1758
1759       myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1760         aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1761
1762       myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1763         aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1764       myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1765         aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1766       myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1767         aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1768       myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1769         aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1770       myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1771         aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1772
1773       myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1774         aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1775       myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1776         aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1777
1778       myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1779         aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1780       myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1781         aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1782
1783       myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1784         aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1785       myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1786         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1787
1788       myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1789         aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1790       myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1791         aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1792
1793       myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1794         aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1795     }
1796
1797     theGlContext->BindProgram (myOutImageProgram);
1798
1799     myOutImageProgram->SetSampler (theGlContext,
1800       "uInputTexture", OpenGl_RT_PrevAccumTexture);
1801
1802     myOutImageProgram->SetSampler (theGlContext,
1803       "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1804
1805     theGlContext->BindProgram (NULL);
1806   }
1807
1808   if (myRaytraceInitStatus != OpenGl_RT_NONE)
1809   {
1810     return myRaytraceInitStatus == OpenGl_RT_INIT;
1811   }
1812
1813   const GLfloat aVertices[] = { -1.f, -1.f,  0.f,
1814                                 -1.f,  1.f,  0.f,
1815                                  1.f,  1.f,  0.f,
1816                                  1.f,  1.f,  0.f,
1817                                  1.f, -1.f,  0.f,
1818                                 -1.f, -1.f,  0.f };
1819
1820   myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1821
1822   myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1823
1824   return Standard_True;
1825 }
1826
1827 // =======================================================================
1828 // function : nullifyResource
1829 // purpose  : Releases OpenGL resource
1830 // =======================================================================
1831 template <class T>
1832 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1833 {
1834   if (!theResource.IsNull())
1835   {
1836     theResource->Release (theGlContext.operator->());
1837     theResource.Nullify();
1838   }
1839 }
1840
1841 // =======================================================================
1842 // function : releaseRaytraceResources
1843 // purpose  : Releases OpenGL/GLSL shader programs
1844 // =======================================================================
1845 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1846 {
1847   // release shader resources
1848   nullifyResource (theGlContext, myRaytraceShader);
1849   nullifyResource (theGlContext, myPostFSAAShader);
1850
1851   nullifyResource (theGlContext, myRaytraceProgram);
1852   nullifyResource (theGlContext, myPostFSAAProgram);
1853   nullifyResource (theGlContext, myOutImageProgram);
1854
1855   if (!theToRebuild) // complete release
1856   {
1857     myRaytraceFBO1[0]->Release (theGlContext.operator->());
1858     myRaytraceFBO1[1]->Release (theGlContext.operator->());
1859     myRaytraceFBO2[0]->Release (theGlContext.operator->());
1860     myRaytraceFBO2[1]->Release (theGlContext.operator->());
1861
1862     nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1863     nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1864
1865     nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1866     nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1867     nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1868     nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1869
1870     nullifyResource (theGlContext, mySceneNodeInfoTexture);
1871     nullifyResource (theGlContext, mySceneMinPointTexture);
1872     nullifyResource (theGlContext, mySceneMaxPointTexture);
1873
1874     nullifyResource (theGlContext, myGeometryVertexTexture);
1875     nullifyResource (theGlContext, myGeometryNormalTexture);
1876     nullifyResource (theGlContext, myGeometryTexCrdTexture);
1877     nullifyResource (theGlContext, myGeometryTriangTexture);
1878     nullifyResource (theGlContext, mySceneTransformTexture);
1879
1880     nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1881     nullifyResource (theGlContext, myRaytraceMaterialTexture);
1882
1883     myRaytraceGeometry.ReleaseResources (theGlContext);
1884
1885     if (myRaytraceScreenQuad.IsValid ())
1886     {
1887       myRaytraceScreenQuad.Release (theGlContext.operator->());
1888     }
1889   }
1890 }
1891
1892 // =======================================================================
1893 // function : updateRaytraceBuffers
1894 // purpose  : Updates auxiliary OpenGL frame buffers.
1895 // =======================================================================
1896 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer        theSizeX,
1897                                                      const Standard_Integer        theSizeY,
1898                                                      const Handle(OpenGl_Context)& theGlContext)
1899 {
1900   // Auxiliary buffers are not used
1901   if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1902   {
1903     myRaytraceFBO1[0]->Release (theGlContext.operator->());
1904     myRaytraceFBO2[0]->Release (theGlContext.operator->());
1905     myRaytraceFBO1[1]->Release (theGlContext.operator->());
1906     myRaytraceFBO2[1]->Release (theGlContext.operator->());
1907
1908     return Standard_True;
1909   }
1910
1911   if (myRaytraceParameters.AdaptiveScreenSampling)
1912   {
1913     const Standard_Integer aSizeX = std::max (myRaytraceParameters.NbTilesX * 64, theSizeX);
1914     const Standard_Integer aSizeY = std::max (myRaytraceParameters.NbTilesY * 64, theSizeY);
1915
1916     myRaytraceFBO1[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1917     myRaytraceFBO2[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1918
1919     if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1920     {
1921       myRaytraceFBO1[1]->Release (theGlContext.operator->());
1922       myRaytraceFBO2[1]->Release (theGlContext.operator->());
1923     }
1924   }
1925   else // non-adaptive mode
1926   {
1927     if (myRaytraceFBO1[0]->GetSizeX() != theSizeX
1928      || myRaytraceFBO1[0]->GetSizeY() != theSizeY)
1929     {
1930       myAccumFrames = 0; // accumulation should be restarted
1931     }
1932
1933     myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1934     myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1935
1936     // Init second set of buffers for stereographic rendering
1937     if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1938     {
1939       myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1940       myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1941     }
1942     else if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1943     {
1944       myRaytraceFBO1[1]->Release (theGlContext.operator->());
1945       myRaytraceFBO2[1]->Release (theGlContext.operator->());
1946     }
1947   }
1948
1949   myTileSampler.SetSize (theSizeX, theSizeY);
1950
1951   if (myRaytraceTileOffsetsTexture[0].IsNull()
1952    || myRaytraceTileOffsetsTexture[1].IsNull())
1953   {
1954     myRaytraceOutputTexture[0] = new OpenGl_Texture();
1955     myRaytraceOutputTexture[1] = new OpenGl_Texture();
1956
1957     myRaytraceTileOffsetsTexture[0] = new OpenGl_Texture();
1958     myRaytraceTileOffsetsTexture[1] = new OpenGl_Texture();
1959     myRaytraceVisualErrorTexture[0] = new OpenGl_Texture();
1960     myRaytraceVisualErrorTexture[1] = new OpenGl_Texture();
1961   }
1962
1963   if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
1964    || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
1965   {
1966     myAccumFrames = 0;
1967
1968     // Due to limitations of OpenGL image load-store extension
1969     // atomic operations are supported only for single-channel
1970     // images, so we define GL_R32F image. It is used as array
1971     // of 6D floating point vectors:
1972     // 0 - R color channel
1973     // 1 - G color channel
1974     // 2 - B color channel
1975     // 3 - hit time transformed into OpenGL NDC space
1976     // 4 - luminance accumulated for odd samples only
1977     myRaytraceOutputTexture[0]->InitRectangle (theGlContext,
1978       theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1979
1980     // workaround for some NVIDIA drivers
1981     myRaytraceVisualErrorTexture[0]->Release (theGlContext.operator->());
1982     myRaytraceTileOffsetsTexture[0]->Release (theGlContext.operator->());
1983
1984     myRaytraceVisualErrorTexture[0]->Init (theGlContext,
1985       GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1986
1987     myRaytraceTileOffsetsTexture[0]->Init (theGlContext,
1988       GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1989   }
1990
1991   if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1992   {
1993     if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
1994      || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
1995     {
1996       myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
1997         theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1998
1999       myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
2000       myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
2001
2002       myRaytraceVisualErrorTexture[1]->Init (theGlContext,
2003         GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
2004
2005       myRaytraceTileOffsetsTexture[1]->Init (theGlContext,
2006         GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
2007     }
2008   }
2009   else
2010   {
2011     myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
2012   }
2013
2014   return Standard_True;
2015 }
2016
2017 // =======================================================================
2018 // function : updateCamera
2019 // purpose  : Generates viewing rays for corners of screen quad
2020 // =======================================================================
2021 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
2022                                 const OpenGl_Mat4& theViewMapping,
2023                                 OpenGl_Vec3*       theOrigins,
2024                                 OpenGl_Vec3*       theDirects,
2025                                 OpenGl_Mat4&       theViewPr,
2026                                 OpenGl_Mat4&       theUnview)
2027 {
2028   // compute view-projection matrix
2029   theViewPr = theViewMapping * theOrientation;
2030
2031   // compute inverse view-projection matrix
2032   theViewPr.Inverted (theUnview);
2033
2034   Standard_Integer aOriginIndex = 0;
2035   Standard_Integer aDirectIndex = 0;
2036
2037   for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2038   {
2039     for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2040     {
2041       OpenGl_Vec4 aOrigin (GLfloat(aX),
2042                            GLfloat(aY),
2043                            -1.0f,
2044                            1.0f);
2045
2046       aOrigin = theUnview * aOrigin;
2047
2048       aOrigin.x() = aOrigin.x() / aOrigin.w();
2049       aOrigin.y() = aOrigin.y() / aOrigin.w();
2050       aOrigin.z() = aOrigin.z() / aOrigin.w();
2051
2052       OpenGl_Vec4 aDirect (GLfloat(aX),
2053                            GLfloat(aY),
2054                            1.0f,
2055                            1.0f);
2056
2057       aDirect = theUnview * aDirect;
2058
2059       aDirect.x() = aDirect.x() / aDirect.w();
2060       aDirect.y() = aDirect.y() / aDirect.w();
2061       aDirect.z() = aDirect.z() / aDirect.w();
2062
2063       aDirect = aDirect - aOrigin;
2064
2065       theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2066                                                 static_cast<GLfloat> (aOrigin.y()),
2067                                                 static_cast<GLfloat> (aOrigin.z()));
2068
2069       theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
2070                                                 static_cast<GLfloat> (aDirect.y()),
2071                                                 static_cast<GLfloat> (aDirect.z()));
2072     }
2073   }
2074 }
2075
2076 // =======================================================================
2077 // function : updatePerspCameraPT
2078 // purpose  : Generates viewing rays (path tracing, perspective camera)
2079 // =======================================================================
2080 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4&           theOrientation,
2081                                        const OpenGl_Mat4&           theViewMapping,
2082                                        Graphic3d_Camera::Projection theProjection,
2083                                        OpenGl_Mat4&                 theViewPr,
2084                                        OpenGl_Mat4&                 theUnview,
2085                                        const int                    theWinSizeX,
2086                                        const int                    theWinSizeY)
2087 {
2088   // compute view-projection matrix
2089   theViewPr = theViewMapping * theOrientation;
2090
2091   // compute inverse view-projection matrix
2092   theViewPr.Inverted(theUnview);
2093   
2094   // get camera stereo params
2095   float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
2096     ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
2097     : static_cast<float> (myCamera->IOD());
2098
2099   float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
2100     ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
2101     : static_cast<float> (myCamera->ZFocus());
2102
2103   // get camera view vectors
2104   const gp_Pnt anOrig = myCamera->Eye();
2105
2106   myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
2107                            static_cast<float> (anOrig.Y()),
2108                            static_cast<float> (anOrig.Z()));
2109
2110   const gp_Dir aView = myCamera->Direction();
2111
2112   OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2113                                            static_cast<float> (aView.Y()),
2114                                            static_cast<float> (aView.Z()));
2115
2116   const gp_Dir anUp = myCamera->Up();
2117
2118   myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2119                            static_cast<float> (anUp.Y()),
2120                            static_cast<float> (anUp.Z()));
2121
2122   myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2123
2124   const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2125   const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2126  
2127   myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2128                            static_cast<float> (aScaleY));
2129
2130   if (theProjection == Graphic3d_Camera::Projection_Perspective)
2131   {
2132     myEyeView = anEyeViewMono;
2133   }
2134   else // stereo camera
2135   {
2136     // compute z-focus point
2137     OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2138
2139     // compute stereo camera shift
2140     float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2141     myEyeOrig += myEyeSide.Normalized() * aDx;
2142
2143     // estimate new camera direction vector and correct its length
2144     myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2145     myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2146   }
2147 }
2148
2149 // =======================================================================
2150 // function : uploadRaytraceData
2151 // purpose  : Uploads ray-trace data to the GPU
2152 // =======================================================================
2153 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2154 {
2155   if (!theGlContext->IsGlGreaterEqual (3, 1))
2156   {
2157 #ifdef RAY_TRACE_PRINT_INFO
2158     std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2159 #endif
2160     return Standard_False;
2161   }
2162
2163   myAccumFrames = 0; // accumulation should be restarted
2164
2165   /////////////////////////////////////////////////////////////////////////////
2166   // Prepare OpenGL textures
2167
2168   if (theGlContext->arbTexBindless != NULL)
2169   {
2170     // If OpenGL driver supports bindless textures we need
2171     // to get unique 64- bit handles for using on the GPU
2172     if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2173     {
2174 #ifdef RAY_TRACE_PRINT_INFO
2175       std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2176 #endif
2177       return Standard_False;
2178     }
2179   }
2180
2181   /////////////////////////////////////////////////////////////////////////////
2182   // Create OpenGL BVH buffers
2183
2184   if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2185   {
2186     mySceneNodeInfoTexture  = new OpenGl_TextureBufferArb;
2187     mySceneMinPointTexture  = new OpenGl_TextureBufferArb;
2188     mySceneMaxPointTexture  = new OpenGl_TextureBufferArb;
2189     mySceneTransformTexture = new OpenGl_TextureBufferArb;
2190
2191     if (!mySceneNodeInfoTexture->Create  (theGlContext)
2192      || !mySceneMinPointTexture->Create  (theGlContext)
2193      || !mySceneMaxPointTexture->Create  (theGlContext)
2194      || !mySceneTransformTexture->Create (theGlContext))
2195     {
2196 #ifdef RAY_TRACE_PRINT_INFO
2197       std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2198 #endif
2199       return Standard_False;
2200     }
2201   }
2202
2203   if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2204   {
2205     myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2206     myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2207     myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2208     myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2209
2210     if (!myGeometryVertexTexture->Create (theGlContext)
2211      || !myGeometryNormalTexture->Create (theGlContext)
2212      || !myGeometryTexCrdTexture->Create (theGlContext)
2213      || !myGeometryTriangTexture->Create (theGlContext))
2214     {
2215 #ifdef RAY_TRACE_PRINT_INFO
2216       std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2217 #endif
2218       return Standard_False;
2219     }
2220   }
2221
2222   if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2223   {
2224     myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2225
2226     if (!myRaytraceMaterialTexture->Create (theGlContext))
2227     {
2228 #ifdef RAY_TRACE_PRINT_INFO
2229       std::cout << "Error: Failed to create buffers for material data" << std::endl;
2230 #endif
2231       return Standard_False;
2232     }
2233   }
2234   
2235   /////////////////////////////////////////////////////////////////////////////
2236   // Write transform buffer
2237
2238   BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2239
2240   bool aResult = true;
2241
2242   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2243   {
2244     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2245       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2246
2247     const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2248     Standard_ASSERT_RETURN (aTransform != NULL,
2249       "OpenGl_TriangleSet does not contain transform", Standard_False);
2250
2251     aNodeTransforms[anElemIndex] = aTransform->Inversed();
2252   }
2253
2254   aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2255     myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2256
2257   delete [] aNodeTransforms;
2258
2259   /////////////////////////////////////////////////////////////////////////////
2260   // Write geometry and bottom-level BVH buffers
2261
2262   Standard_Size aTotalVerticesNb = 0;
2263   Standard_Size aTotalElementsNb = 0;
2264   Standard_Size aTotalBVHNodesNb = 0;
2265
2266   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2267   {
2268     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2269       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2270
2271     Standard_ASSERT_RETURN (aTriangleSet != NULL,
2272       "Error: Failed to get triangulation of OpenGL element", Standard_False);
2273
2274     aTotalVerticesNb += aTriangleSet->Vertices.size();
2275     aTotalElementsNb += aTriangleSet->Elements.size();
2276
2277     Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2278       "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2279
2280     aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2281   }
2282
2283   aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2284
2285   if (aTotalBVHNodesNb != 0)
2286   {
2287     aResult &= mySceneNodeInfoTexture->Init (
2288       theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*>  (NULL));
2289     aResult &= mySceneMinPointTexture->Init (
2290       theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2291     aResult &= mySceneMaxPointTexture->Init (
2292       theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2293   }
2294
2295   if (!aResult)
2296   {
2297 #ifdef RAY_TRACE_PRINT_INFO
2298     std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2299 #endif
2300     return Standard_False;
2301   }
2302
2303   if (aTotalElementsNb != 0)
2304   {
2305     aResult &= myGeometryTriangTexture->Init (
2306       theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2307   }
2308
2309   if (aTotalVerticesNb != 0)
2310   {
2311     aResult &= myGeometryVertexTexture->Init (
2312       theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2313     aResult &= myGeometryNormalTexture->Init (
2314       theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2315     aResult &= myGeometryTexCrdTexture->Init (
2316       theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2317   }
2318
2319   if (!aResult)
2320   {
2321 #ifdef RAY_TRACE_PRINT_INFO
2322     std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2323 #endif
2324     return Standard_False;
2325   }
2326
2327   const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2328
2329   if (aBVH->Length() > 0)
2330   {
2331     aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2332       reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2333     aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2334       reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2335     aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2336       reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2337   }
2338
2339   for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2340   {
2341     if (!aBVH->IsOuter (aNodeIdx))
2342       continue;
2343
2344     OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2345
2346     Standard_ASSERT_RETURN (aTriangleSet != NULL,
2347       "Error: Failed to get triangulation of OpenGL element", Standard_False);
2348
2349     Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2350
2351     Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2352       "Error: Failed to get offset for bottom-level BVH", Standard_False);
2353
2354     const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2355
2356     if (aBvhBuffersSize != 0)
2357     {
2358       aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2359         reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2360       aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2361         reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2362       aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2363         reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2364
2365       if (!aResult)
2366       {
2367 #ifdef RAY_TRACE_PRINT_INFO
2368         std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2369 #endif
2370         return Standard_False;
2371       }
2372     }
2373
2374     const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2375
2376     Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2377       "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2378
2379     if (!aTriangleSet->Vertices.empty())
2380     {
2381       aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2382         GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2383       aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2384         GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2385       aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2386         GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2387     }
2388
2389     const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2390
2391     Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2392       "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2393
2394     if (!aTriangleSet->Elements.empty())
2395     {
2396       aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2397                                                    reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2398     }
2399
2400     if (!aResult)
2401     {
2402 #ifdef RAY_TRACE_PRINT_INFO
2403       std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2404 #endif
2405       return Standard_False;
2406     }
2407   }
2408
2409   /////////////////////////////////////////////////////////////////////////////
2410   // Write material buffer
2411
2412   if (myRaytraceGeometry.Materials.size() != 0)
2413   {
2414     aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2415       GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2416
2417     if (!aResult)
2418     {
2419 #ifdef RAY_TRACE_PRINT_INFO
2420       std::cout << "Error: Failed to upload material buffer" << std::endl;
2421 #endif
2422       return Standard_False;
2423     }
2424   }
2425
2426   myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2427
2428 #ifdef RAY_TRACE_PRINT_INFO
2429
2430   Standard_ShortReal aMemTrgUsed = 0.f;
2431   Standard_ShortReal aMemBvhUsed = 0.f;
2432
2433   for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2434   {
2435     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2436
2437     aMemTrgUsed += static_cast<Standard_ShortReal> (
2438       aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2439     aMemTrgUsed += static_cast<Standard_ShortReal> (
2440       aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2441     aMemTrgUsed += static_cast<Standard_ShortReal> (
2442       aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2443     aMemTrgUsed += static_cast<Standard_ShortReal> (
2444       aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2445
2446     aMemBvhUsed += static_cast<Standard_ShortReal> (
2447       aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2448     aMemBvhUsed += static_cast<Standard_ShortReal> (
2449       aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2450     aMemBvhUsed += static_cast<Standard_ShortReal> (
2451       aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2452   }
2453
2454   aMemBvhUsed += static_cast<Standard_ShortReal> (
2455     myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2456   aMemBvhUsed += static_cast<Standard_ShortReal> (
2457     myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2458   aMemBvhUsed += static_cast<Standard_ShortReal> (
2459     myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2460
2461   std::cout << "GPU Memory Used (Mb):\n"
2462     << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2463     << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2464
2465 #endif
2466
2467   return aResult;
2468 }
2469
2470 // =======================================================================
2471 // function : updateRaytraceLightSources
2472 // purpose  : Updates 3D scene light sources for ray-tracing
2473 // =======================================================================
2474 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2475 {
2476   std::vector<Handle(Graphic3d_CLight)> aLightSources;
2477   myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2478   if (myShadingModel != Graphic3d_TOSM_UNLIT
2479   && !myLights.IsNull())
2480   {
2481     const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
2482     myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
2483
2484     // move positional light sources at the front of the list
2485     aLightSources.reserve (myLights->Extent());
2486     for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2487          aLightIter.More(); aLightIter.Next())
2488     {
2489       const Graphic3d_CLight& aLight = *aLightIter.Value();
2490       if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2491       {
2492         aLightSources.push_back (aLightIter.Value());
2493       }
2494     }
2495
2496     for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2497          aLightIter.More(); aLightIter.Next())
2498     {
2499       if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2500       {
2501         aLightSources.push_back (aLightIter.Value());
2502       }
2503     }
2504   }
2505
2506   // get number of 'real' (not ambient) light sources
2507   const size_t aNbLights = aLightSources.size();
2508   Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2509   if (wasUpdated)
2510   {
2511     myRaytraceGeometry.Sources.resize (aNbLights);
2512   }
2513
2514   for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2515   {
2516     const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2517     const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2518     BVH_Vec4f aEmission  (aLightColor.r() * aLight.Intensity(),
2519                           aLightColor.g() * aLight.Intensity(),
2520                           aLightColor.b() * aLight.Intensity(),
2521                           1.0f);
2522
2523     BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
2524                          -aLight.PackedDirection().y(),
2525                          -aLight.PackedDirection().z(),
2526                          0.0f);
2527
2528     if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2529     {
2530       aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2531                              static_cast<float>(aLight.Position().Y()),
2532                              static_cast<float>(aLight.Position().Z()),
2533                              1.0f);
2534
2535       // store smoothing radius in W-component
2536       aEmission.w() = Max (aLight.Smoothness(), 0.f);
2537     }
2538     else
2539     {
2540       // store cosine of smoothing angle in W-component
2541       aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2542     }
2543
2544     if (aLight.IsHeadlight())
2545     {
2546       aPosition = theInvModelView * aPosition;
2547     }
2548
2549     for (int aK = 0; aK < 4; ++aK)
2550     {
2551       wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2552                  || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2553     }
2554
2555     if (wasUpdated)
2556     {
2557       myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2558     }
2559
2560     ++aRealIdx;
2561   }
2562
2563   if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2564   {
2565     myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2566   }
2567
2568   if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2569   {
2570     const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2571     if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2572     {
2573 #ifdef RAY_TRACE_PRINT_INFO
2574       std::cout << "Error: Failed to upload light source buffer" << std::endl;
2575 #endif
2576       return Standard_False;
2577     }
2578
2579     myAccumFrames = 0; // accumulation should be restarted
2580   }
2581
2582   return Standard_True;
2583 }
2584
2585 // =======================================================================
2586 // function : setUniformState
2587 // purpose  : Sets uniform state for the given ray-tracing shader program
2588 // =======================================================================
2589 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        theProgramId,
2590                                                const Standard_Integer        theWinSizeX,
2591                                                const Standard_Integer        theWinSizeY,
2592                                                Graphic3d_Camera::Projection  theProjection,
2593                                                const Handle(OpenGl_Context)& theGlContext)
2594 {
2595   // Get projection state
2596   OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2597
2598   OpenGl_Mat4 aViewPrjMat;
2599   OpenGl_Mat4 anUnviewMat;
2600   OpenGl_Vec3 aOrigins[4];
2601   OpenGl_Vec3 aDirects[4];
2602
2603   if (myCamera->IsOrthographic()
2604    || !myRenderParams.IsGlobalIlluminationEnabled)
2605   {
2606     updateCamera (myCamera->OrientationMatrixF(),
2607                   aCntxProjectionState.Current(),
2608                   aOrigins,
2609                   aDirects,
2610                   aViewPrjMat,
2611                   anUnviewMat);
2612   }
2613   else
2614   {
2615     updatePerspCameraPT (myCamera->OrientationMatrixF(),
2616                          aCntxProjectionState.Current(),
2617                          theProjection,
2618                          aViewPrjMat,
2619                          anUnviewMat,
2620                          theWinSizeX,
2621                          theWinSizeY);
2622   }
2623
2624   Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2625                                            ? myRaytraceProgram
2626                                            : myPostFSAAProgram;
2627
2628   if (theProgram.IsNull())
2629   {
2630     return Standard_False;
2631   }
2632   
2633   theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2634   theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2635   theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2636   theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2637   theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2638
2639   theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2640   theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2641   
2642   // Set camera state
2643   theProgram->SetUniform (theGlContext,
2644     myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2645   theProgram->SetUniform (theGlContext,
2646     myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2647   theProgram->SetUniform (theGlContext,
2648     myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2649   theProgram->SetUniform (theGlContext,
2650     myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2651   theProgram->SetUniform (theGlContext,
2652     myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2653   theProgram->SetUniform (theGlContext,
2654     myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2655   theProgram->SetUniform (theGlContext,
2656     myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2657   theProgram->SetUniform (theGlContext,
2658     myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2659   theProgram->SetUniform (theGlContext,
2660     myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2661   theProgram->SetUniform (theGlContext,
2662     myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2663
2664   // Set screen dimensions
2665   myRaytraceProgram->SetUniform (theGlContext,
2666     myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2667   myRaytraceProgram->SetUniform (theGlContext,
2668     myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2669
2670   // Set 3D scene parameters
2671   theProgram->SetUniform (theGlContext,
2672     myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2673   theProgram->SetUniform (theGlContext,
2674     myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2675
2676   // Set light source parameters
2677   const Standard_Integer aLightSourceBufferSize =
2678     static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2679   
2680   theProgram->SetUniform (theGlContext,
2681     myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2682
2683   // Set array of 64-bit texture handles
2684   if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2685   {
2686     const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2687
2688     theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2689       static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2690   }
2691
2692   // Set background colors (only gradient background supported)
2693   if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
2694   {
2695     theProgram->SetUniform (theGlContext,
2696       myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
2697     theProgram->SetUniform (theGlContext,
2698       myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
2699   }
2700   else
2701   {
2702     const OpenGl_Vec4& aBackColor = myBgColor;
2703
2704     theProgram->SetUniform (theGlContext,
2705       myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2706     theProgram->SetUniform (theGlContext,
2707       myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2708   }
2709
2710   // Set environment map parameters
2711   const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
2712                                                ||  myTextureEnv->IsEmpty()
2713                                                || !myTextureEnv->First()->IsValid();
2714
2715   theProgram->SetUniform (theGlContext,
2716     myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2717
2718   theProgram->SetUniform (theGlContext,
2719     myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ?  1 : 0);
2720
2721   if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2722   {
2723     theProgram->SetUniform (theGlContext,
2724       myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2725
2726     theProgram->SetUniform (theGlContext,
2727       myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2728
2729     // Check whether we should restart accumulation for run-time parameters
2730     if (myRenderParams.RadianceClampingValue       != myRaytraceParameters.RadianceClampingValue
2731      || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2732     {
2733       myAccumFrames = 0; // accumulation should be restarted
2734
2735       myRaytraceParameters.RadianceClampingValue  = myRenderParams.RadianceClampingValue;
2736       myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2737     }
2738   }
2739   else // RT parameters
2740   {
2741     // Set ambient light source
2742     theProgram->SetUniform (theGlContext,
2743       myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2744
2745     // Enable/disable run-time ray-tracing effects
2746     theProgram->SetUniform (theGlContext,
2747       myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ?  1 : 0);
2748     theProgram->SetUniform (theGlContext,
2749       myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ?  1 : 0);
2750   }
2751
2752   return Standard_True;
2753 }
2754
2755 // =======================================================================
2756 // function : bindRaytraceTextures
2757 // purpose  : Binds ray-trace textures to corresponding texture units
2758 // =======================================================================
2759 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2760 {
2761   if (myRaytraceParameters.AdaptiveScreenSampling)
2762   {
2763   #if !defined(GL_ES_VERSION_2_0)
2764     theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft,
2765       myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2766     theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh,
2767       myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2768
2769     theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImageLft,
2770       myRaytraceVisualErrorTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2771     theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImageRgh,
2772       myRaytraceVisualErrorTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2773     theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImageLft,
2774       myRaytraceTileOffsetsTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2775     theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImageRgh,
2776       myRaytraceTileOffsetsTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2777 #endif
2778   }
2779
2780   if (!myTextureEnv.IsNull()
2781    && !myTextureEnv->IsEmpty()
2782    &&  myTextureEnv->First()->IsValid())
2783   {
2784     myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
2785   }
2786
2787   mySceneMinPointTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2788   mySceneMaxPointTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2789   mySceneNodeInfoTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2790   myGeometryVertexTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2791   myGeometryNormalTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2792   myGeometryTexCrdTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2793   myGeometryTriangTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2794   mySceneTransformTexture  ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2795   myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2796   myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2797 }
2798
2799 // =======================================================================
2800 // function : unbindRaytraceTextures
2801 // purpose  : Unbinds ray-trace textures from corresponding texture units
2802 // =======================================================================
2803 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2804 {
2805   mySceneMinPointTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2806   mySceneMaxPointTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2807   mySceneNodeInfoTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2808   myGeometryVertexTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2809   myGeometryNormalTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2810   myGeometryTexCrdTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2811   myGeometryTriangTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2812   mySceneTransformTexture  ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2813   myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2814   myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2815
2816   theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2817 }
2818
2819 // =======================================================================
2820 // function : runRaytraceShaders
2821 // purpose  : Runs ray-tracing shader programs
2822 // =======================================================================
2823 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer        theSizeX,
2824                                                   const Standard_Integer        theSizeY,
2825                                                   Graphic3d_Camera::Projection  theProjection,
2826                                                   OpenGl_FrameBuffer*           theReadDrawFbo,
2827                                                   const Handle(OpenGl_Context)& theGlContext)
2828 {
2829   Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2830
2831   aResult &= setUniformState (0,
2832                               theSizeX,
2833                               theSizeY,
2834                               theProjection,
2835                               theGlContext);
2836
2837   if (myRaytraceParameters.GlobalIllumination) // path tracing
2838   {
2839     aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2840   }
2841   else // Whitted-style ray-tracing
2842   {
2843     aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2844   }
2845
2846   return aResult;
2847 }
2848
2849 // =======================================================================
2850 // function : runRaytrace
2851 // purpose  : Runs Whitted-style ray-tracing
2852 // =======================================================================
2853 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSizeX,
2854                                            const Standard_Integer        theSizeY,
2855                                            Graphic3d_Camera::Projection  theProjection,
2856                                            OpenGl_FrameBuffer*           theReadDrawFbo,
2857                                            const Handle(OpenGl_Context)& theGlContext)
2858 {
2859   Standard_Boolean aResult = Standard_True;
2860
2861   bindRaytraceTextures (theGlContext);
2862
2863   Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2864   Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2865
2866   // Choose proper set of frame buffers for stereo rendering
2867   const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2868
2869   if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2870   {
2871     myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2872
2873     glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2874   }
2875
2876   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2877
2878   if (myRenderParams.IsAntialiasingEnabled)
2879   {
2880     glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2881
2882     // bind ray-tracing output image as input
2883     myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2884
2885     aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2886
2887     aResult &= setUniformState (1 /* FSAA ID */,
2888                                 theSizeX,
2889                                 theSizeY,
2890                                 theProjection,
2891                                 theGlContext);
2892
2893     // Perform multi-pass adaptive FSAA using ping-pong technique.
2894     // We use 'FLIPTRI' sampling pattern changing for every pixel
2895     // (3 additional samples per pixel, the 1st sample is already
2896     // available from initial ray-traced image).
2897     for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2898     {
2899       GLfloat aOffsetX = 1.f / theSizeX;
2900       GLfloat aOffsetY = 1.f / theSizeY;
2901
2902       if (anIt == 1)
2903       {
2904         aOffsetX *= -0.55f;
2905         aOffsetY *=  0.55f;
2906       }
2907       else if (anIt == 2)
2908       {
2909         aOffsetX *=  0.00f;
2910         aOffsetY *= -0.55f;
2911       }
2912       else if (anIt == 3)
2913       {
2914         aOffsetX *= 0.55f;
2915         aOffsetY *= 0.00f;
2916       }
2917
2918       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2919         myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2920       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2921         myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2922       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2923         myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2924
2925       Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2926                                                ? myRaytraceFBO2[aFBOIdx]
2927                                                : myRaytraceFBO1[aFBOIdx];
2928
2929       aFramebuffer->BindBuffer (theGlContext);
2930
2931       // perform adaptive FSAA pass
2932       theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2933
2934       aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2935     }
2936
2937     aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2938     aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2939
2940     glEnable (GL_DEPTH_TEST);
2941
2942     // Display filtered image
2943     theGlContext->BindProgram (myOutImageProgram);
2944
2945     if (theReadDrawFbo != NULL)
2946     {
2947       theReadDrawFbo->BindBuffer (theGlContext);
2948     }
2949     else
2950     {
2951       aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2952     }
2953
2954     aRenderImageFramebuffer->ColorTexture()       ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2955     aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2956
2957     // copy the output image with depth values
2958     theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2959
2960     aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2961     aRenderImageFramebuffer->ColorTexture()       ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2962   }
2963
2964   unbindRaytraceTextures (theGlContext);
2965
2966   theGlContext->BindProgram (NULL);
2967
2968   return aResult;
2969 }
2970
2971 // =======================================================================
2972 // function : runPathtrace
2973 // purpose  : Runs path tracing shader
2974 // =======================================================================
2975 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer              theSizeX,
2976                                             const Standard_Integer              theSizeY,
2977                                             const Graphic3d_Camera::Projection  theProjection,
2978                                             OpenGl_FrameBuffer*                 theReadDrawFbo,
2979                                             const Handle(OpenGl_Context)&       theGlContext)
2980 {
2981   Standard_Boolean aResult = Standard_True;
2982
2983   if (myToUpdateEnvironmentMap) // check whether the map was changed
2984   {
2985     myAccumFrames = myToUpdateEnvironmentMap = 0;
2986   }
2987   
2988   if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2989    || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2990   {
2991
2992     myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2993     myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2994
2995     myAccumFrames = 0;
2996   }
2997
2998   // Choose proper set of frame buffers for stereo rendering
2999   const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
3000
3001   if (myRaytraceParameters.AdaptiveScreenSampling)
3002   {
3003     if (myAccumFrames == 0)
3004     {
3005       myTileSampler.Reset(); // reset tile sampler to its initial state
3006
3007       // Adaptive sampling is starting at the second frame
3008       myTileSampler.Upload (theGlContext,
3009                             myRaytraceTileOffsetsTexture[aFBOIdx],
3010                             myRaytraceParameters.NbTilesX,
3011                             myRaytraceParameters.NbTilesY,
3012                             false);
3013     }
3014   }
3015
3016   bindRaytraceTextures (theGlContext);
3017
3018   Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
3019   Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
3020   Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
3021
3022   const Standard_Integer anImageId = (aFBOIdx != 0)
3023                                    ? OpenGl_RT_OutputImageRgh
3024                                    : OpenGl_RT_OutputImageLft;
3025
3026   const Standard_Integer anErrorId = (aFBOIdx != 0)
3027                                    ? OpenGl_RT_VisualErrorImageRgh
3028                                    : OpenGl_RT_VisualErrorImageLft;
3029
3030   const Standard_Integer anOffsetId = (aFBOIdx != 0)
3031                                     ? OpenGl_RT_TileOffsetsImageRgh
3032                                     : OpenGl_RT_TileOffsetsImageLft;
3033
3034   aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3035   anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
3036
3037   aDepthSourceFramebuffer = aRenderImageFramebuffer;
3038
3039   anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3040
3041   aRenderImageFramebuffer->BindBuffer (theGlContext);
3042
3043   if (myAccumFrames == 0)
3044   {
3045     myRNG.SetSeed(); // start RNG from beginning
3046   }
3047
3048   // Clear adaptive screen sampling images
3049   if (myRaytraceParameters.AdaptiveScreenSampling)
3050   {
3051   #if !defined(GL_ES_VERSION_2_0)
3052     if (myAccumFrames == 0 || (myAccumFrames == 1 && myCamera->IsStereo()))
3053     {
3054       theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
3055     }
3056
3057     theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
3058   #endif
3059   }
3060
3061   // Set frame accumulation weight
3062   myRaytraceProgram->SetUniform (theGlContext,
3063     myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
3064
3065   // Set random number generator seed
3066   myRaytraceProgram->SetUniform (theGlContext,
3067     myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
3068
3069   // Set image uniforms for render program
3070   myRaytraceProgram->SetUniform (theGlContext,
3071     myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId);
3072   myRaytraceProgram->SetUniform (theGlContext,
3073     myUniformLocations[0][OpenGl_RT_uOffsetImage], anOffsetId);
3074
3075   glDisable (GL_DEPTH_TEST);
3076
3077   if (myRaytraceParameters.AdaptiveScreenSampling
3078    && ((myAccumFrames > 0 && !myCamera->IsStereo()) || myAccumFrames > 1))
3079   {
3080     glViewport (0,
3081                 0,
3082                 myTileSampler.TileSize() * myRaytraceParameters.NbTilesX,
3083                 myTileSampler.TileSize() * myRaytraceParameters.NbTilesY);
3084   }
3085
3086   // Generate for the given RNG seed
3087   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3088
3089   if (myRaytraceParameters.AdaptiveScreenSampling
3090    && ((myAccumFrames > 0 && !myCamera->IsStereo()) || myAccumFrames > 1))
3091   {
3092     glViewport (0,
3093                 0,
3094                 theSizeX,
3095                 theSizeY);
3096   }
3097
3098   // Output accumulated path traced image
3099   theGlContext->BindProgram (myOutImageProgram);
3100
3101   if (myRaytraceParameters.AdaptiveScreenSampling)
3102   {
3103     // Set uniforms for display program
3104     myOutImageProgram->SetUniform (theGlContext, "uRenderImage",   anImageId);
3105     myOutImageProgram->SetUniform (theGlContext, "uAccumFrames",   myAccumFrames);
3106     myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", anErrorId);
3107     myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ?  1 : 0);
3108   }
3109
3110   if (myRaytraceParameters.GlobalIllumination)
3111   {
3112     myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3113     switch (myRaytraceParameters.ToneMappingMethod)
3114     {
3115       case Graphic3d_ToneMappingMethod_Disabled:
3116         break;
3117       case Graphic3d_ToneMappingMethod_Filmic:
3118         myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3119         break;
3120     }
3121   }
3122
3123   if (theReadDrawFbo != NULL)
3124   {
3125     theReadDrawFbo->BindBuffer (theGlContext);
3126   }
3127   else
3128   {
3129     aRenderImageFramebuffer->UnbindBuffer (theGlContext);
3130   }
3131
3132   aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3133
3134   glEnable (GL_DEPTH_TEST);
3135
3136   // Copy accumulated image with correct depth values
3137   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3138
3139   aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3140
3141   if (myRaytraceParameters.AdaptiveScreenSampling)
3142   {
3143     myRaytraceVisualErrorTexture[aFBOIdx]->Bind (theGlContext);
3144
3145     // Download visual error map from the GPU and build
3146     // adjusted tile offsets for optimal image sampling
3147     myTileSampler.GrabVarianceMap (theGlContext);
3148
3149     myTileSampler.Upload (theGlContext,
3150                           myRaytraceTileOffsetsTexture[aFBOIdx],
3151                           myRaytraceParameters.NbTilesX,
3152                           myRaytraceParameters.NbTilesY,
3153                           myAccumFrames > 0);
3154   }
3155
3156   unbindRaytraceTextures (theGlContext);
3157
3158   theGlContext->BindProgram (NULL);
3159
3160   return aResult;
3161 }
3162
3163 // =======================================================================
3164 // function : raytrace
3165 // purpose  : Redraws the window using OpenGL/GLSL ray-tracing
3166 // =======================================================================
3167 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer        theSizeX,
3168                                         const Standard_Integer        theSizeY,
3169                                         Graphic3d_Camera::Projection  theProjection,
3170                                         OpenGl_FrameBuffer*           theReadDrawFbo,
3171                                         const Handle(OpenGl_Context)& theGlContext)
3172 {
3173   if (!initRaytraceResources (theGlContext))
3174   {
3175     return Standard_False;
3176   }
3177
3178   if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3179   {
3180     return Standard_False;
3181   }
3182
3183   OpenGl_Mat4 aLightSourceMatrix;
3184
3185   // Get inversed model-view matrix for transforming lights
3186   myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3187
3188   if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3189   {
3190     return Standard_False;
3191   }
3192
3193   // Generate image using Whitted-style ray-tracing or path tracing
3194   if (myIsRaytraceDataValid)
3195   {
3196     myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3197
3198     if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3199     {
3200       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3201         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3202     }
3203
3204     glDisable (GL_BLEND);
3205
3206     const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3207                                                          theSizeY,
3208                                                          theProjection,
3209                                                          theReadDrawFbo,
3210                                                          theGlContext);
3211
3212     if (!aResult)
3213     {
3214       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3215         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3216     }
3217
3218     if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3219     {
3220       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3221         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3222     }
3223
3224     myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3225   }
3226
3227   return Standard_True;
3228 }