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