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