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