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