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