0025897: Visualization, TKOpenGl - disable FBO blitting after first failure on broken...
[occt.git] / src / OpenGl / OpenGl_Workspace_Raytrace.cxx
1 // Created on: 2013-08-27
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2013 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_Workspace.hxx>
17
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_FrameBuffer.hxx>
20 #include <OpenGl_PrimitiveArray.hxx>
21 #include <OpenGl_VertexBuffer.hxx>
22 #include <OpenGl_View.hxx>
23 #include <OSD_File.hxx>
24 #include <OSD_Protection.hxx>
25
26 using namespace OpenGl_Raytrace;
27
28 //! Use this macro to output ray-tracing debug info
29 // #define RAY_TRACE_PRINT_INFO
30
31 #ifdef RAY_TRACE_PRINT_INFO
32   #include <OSD_Timer.hxx>
33 #endif
34
35 // =======================================================================
36 // function : UpdateRaytraceGeometry
37 // purpose  : Updates 3D scene geometry for ray tracing
38 // =======================================================================
39 Standard_Boolean OpenGl_Workspace::UpdateRaytraceGeometry (GeomUpdateMode theMode)
40 {
41   if (myView.IsNull())
42     return Standard_False;
43
44   // Note: In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for modifications
45   // This is light-weight procedure performed for each frame
46
47   if (theMode == OpenGl_GUM_CHECK)
48   {
49      if (myLayersModificationStatus != myView->LayerList().ModificationState())
50      {
51         return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
52      }
53   } 
54   else if (theMode == OpenGl_GUM_PREPARE)
55   {
56     myRaytraceGeometry.ClearMaterials();
57     myArrayToTrianglesMap.clear();
58
59     myIsRaytraceDataValid = Standard_False;
60   }
61
62   // The set of processed structures (reflected to ray-tracing)
63   // This set is used to remove out-of-date records from the
64   // hash map of structures
65   std::set<const OpenGl_Structure*> anElements;
66
67   // Set of all currently visible and "raytracable" primitive arrays.
68   std::set<Standard_Size> anArrayIDs;
69
70   const OpenGl_LayerList& aList = myView->LayerList();
71
72   for (OpenGl_SequenceOfLayers::Iterator anLayerIt (aList.Layers()); anLayerIt.More(); anLayerIt.Next())
73   {
74     const OpenGl_Layer& aLayer = anLayerIt.Value();
75     if (aLayer.NbStructures() == 0)
76       continue;
77
78     const OpenGl_ArrayOfStructure& aStructArray = aLayer.ArrayOfStructures();
79     for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
80     {
81       for (OpenGl_SequenceOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
82       {
83         const OpenGl_Structure* aStructure = aStructIt.Value();
84
85         if (theMode == OpenGl_GUM_CHECK)
86         {
87           if (CheckRaytraceStructure (aStructure))
88           {
89             return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
90           }
91         }
92         else if (theMode == OpenGl_GUM_PREPARE)
93         {
94           if (!aStructure->IsRaytracable()
95            || !aStructure->IsVisible())
96           {
97             continue;
98           }
99           else if (!aStructure->ViewAffinity.IsNull()
100                 && !aStructure->ViewAffinity->IsVisible (myViewId))
101           {
102             continue;
103           }
104
105           for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
106           {
107             // OpenGL elements from group (extract primitives arrays)
108             for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
109             {
110               OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
111
112               if (aPrimArray != NULL)
113               {
114                 // Collect all primitive arrays in scene.
115                 anArrayIDs.insert (aPrimArray->GetUID());
116               }
117             }
118           }
119         }
120         else if (theMode == OpenGl_GUM_UPDATE)
121         {
122           if (!aStructure->IsRaytracable())
123             continue;
124
125           AddRaytraceStructure (aStructure, anElements);
126         }
127       }
128     }
129   }
130
131   if (theMode == OpenGl_GUM_PREPARE)
132   {
133     BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
134
135     // Leave only unchanged objects in myRaytraceGeometry so only their transforms and materials will be updated
136     // Objects which not in myArrayToTrianglesMap will be built from scratch.
137     for (Standard_Integer anObjectIdx = 0; anObjectIdx < myRaytraceGeometry.Objects().Size(); ++anObjectIdx)
138     {
139       OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
140         myRaytraceGeometry.Objects().ChangeValue (anObjectIdx).operator->());
141
142       // If primitive array of object not in "anArrays" set then it was hided or deleted.
143       // If primitive array present in "anArrays" set but we don't have associated object yet, then
144       // the object is new and still has to be built.
145       if ((aTriangleSet != NULL) && ((anArrayIDs.find (aTriangleSet->AssociatedPArrayID())) != anArrayIDs.end()))
146       {
147         anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjectIdx));
148
149         myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
150       }
151     }
152
153     myRaytraceGeometry.Objects() = anUnchangedObjects;
154
155     return UpdateRaytraceGeometry (OpenGl_GUM_UPDATE);
156   }
157
158   if (theMode == OpenGl_GUM_UPDATE)
159   {
160     // Actualize the hash map of structures -- remove out-of-date records
161     std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
162
163     while (anIter != myStructureStates.end())
164     {
165       if (anElements.find (anIter->first) == anElements.end())
166       {
167         myStructureStates.erase (anIter++);
168       }
169       else
170       {
171         ++anIter;
172       }
173     }
174
175     // Actualize OpenGL layer list state
176     myLayersModificationStatus = myView->LayerList().ModificationState();
177
178     // Rebuild bottom-level and high-level BVHs
179     myRaytraceGeometry.ProcessAcceleration();
180
181     const Standard_ShortReal aMinRadius = Max (fabs (myRaytraceGeometry.Box().CornerMin().x()), Max (
182       fabs (myRaytraceGeometry.Box().CornerMin().y()), fabs (myRaytraceGeometry.Box().CornerMin().z())));
183     const Standard_ShortReal aMaxRadius = Max (fabs (myRaytraceGeometry.Box().CornerMax().x()), Max (
184       fabs (myRaytraceGeometry.Box().CornerMax().y()), fabs (myRaytraceGeometry.Box().CornerMax().z())));
185
186     myRaytraceSceneRadius = 2.f /* scale factor */ * Max (aMinRadius, aMaxRadius);
187
188     const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
189
190     myRaytraceSceneEpsilon = Max (1e-6f, 1e-4f * sqrtf (
191       aSize.x() * aSize.x() + aSize.y() * aSize.y() + aSize.z() * aSize.z()));
192
193     return UploadRaytraceData();
194   }
195
196   return Standard_True;
197 }
198
199 // =======================================================================
200 // function : CheckRaytraceStructure
201 // purpose  : Checks to see if the structure is modified
202 // =======================================================================
203 Standard_Boolean OpenGl_Workspace::CheckRaytraceStructure (const OpenGl_Structure* theStructure)
204 {
205   if (!theStructure->IsRaytracable())
206   {
207     // Checks to see if all ray-tracable elements were
208     // removed from the structure
209     if (theStructure->ModificationState() > 0)
210     {
211       theStructure->ResetModificationState();
212       return Standard_True;
213     }
214
215     return Standard_False;
216   }
217
218   std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
219
220   if (aStructState != myStructureStates.end())
221     return aStructState->second != theStructure->ModificationState();
222
223   return Standard_True;
224 }
225
226 // =======================================================================
227 // function : BuildTexTransform
228 // purpose  : Constructs texture transformation matrix
229 // =======================================================================
230 void BuildTexTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
231 {
232   theMatrix.InitIdentity();
233
234   // Apply scaling
235   const Graphic3d_Vec2& aScale = theParams->Scale();
236
237   theMatrix.ChangeValue (0, 0) *= aScale.x();
238   theMatrix.ChangeValue (1, 0) *= aScale.x();
239   theMatrix.ChangeValue (2, 0) *= aScale.x();
240   theMatrix.ChangeValue (3, 0) *= aScale.x();
241
242   theMatrix.ChangeValue (0, 1) *= aScale.y();
243   theMatrix.ChangeValue (1, 1) *= aScale.y();
244   theMatrix.ChangeValue (2, 1) *= aScale.y();
245   theMatrix.ChangeValue (3, 1) *= aScale.y();
246
247   // Apply translation
248   const Graphic3d_Vec2 aTrans = -theParams->Translation();
249
250   theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
251                                  theMatrix.GetValue (0, 1) * aTrans.y();
252
253   theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
254                                  theMatrix.GetValue (1, 1) * aTrans.y();
255
256   theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
257                                  theMatrix.GetValue (2, 1) * aTrans.y();
258
259   // Apply rotation
260   const Standard_ShortReal aSin = std::sin (
261     -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
262   const Standard_ShortReal aCos = std::cos (
263     -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
264
265   BVH_Mat4f aRotationMat;
266   aRotationMat.SetValue (0, 0,  aCos);
267   aRotationMat.SetValue (1, 1,  aCos);
268   aRotationMat.SetValue (0, 1, -aSin);
269   aRotationMat.SetValue (1, 0,  aSin);
270
271   theMatrix = theMatrix * aRotationMat;
272 }
273
274 // =======================================================================
275 // function : CreateMaterial
276 // purpose  : Creates ray-tracing material properties
277 // =======================================================================
278 Standard_Boolean OpenGl_Workspace::CreateMaterial (const OpenGl_AspectFace* theAspect, OpenGl_RaytraceMaterial& theMaterial)
279 {
280   const OPENGL_SURF_PROP& aProperties = theAspect->IntFront();
281
282   const Standard_ShortReal* aSrcAmbient =
283     aProperties.isphysic ? aProperties.ambcol.rgb : aProperties.matcol.rgb;
284
285   theMaterial.Ambient = BVH_Vec4f (aSrcAmbient[0] * aProperties.amb,
286                                    aSrcAmbient[1] * aProperties.amb,
287                                    aSrcAmbient[2] * aProperties.amb,
288                                    1.f);
289
290   const Standard_ShortReal* aSrcDiffuse =
291     aProperties.isphysic ? aProperties.difcol.rgb : aProperties.matcol.rgb;
292
293   theMaterial.Diffuse = BVH_Vec4f (aSrcDiffuse[0] * aProperties.diff,
294                                    aSrcDiffuse[1] * aProperties.diff,
295                                    aSrcDiffuse[2] * aProperties.diff,
296                                    -1.f /* no texture */);
297
298   theMaterial.Specular = BVH_Vec4f (
299     (aProperties.isphysic ? aProperties.speccol.rgb[0] : 1.f) * aProperties.spec,
300     (aProperties.isphysic ? aProperties.speccol.rgb[1] : 1.f) * aProperties.spec,
301     (aProperties.isphysic ? aProperties.speccol.rgb[2] : 1.f) * aProperties.spec,
302     aProperties.shine);
303
304   const Standard_ShortReal* aSrcEmission =
305     aProperties.isphysic ? aProperties.emscol.rgb : aProperties.matcol.rgb;
306
307   theMaterial.Emission = BVH_Vec4f (aSrcEmission[0] * aProperties.emsv,
308                                     aSrcEmission[1] * aProperties.emsv,
309                                     aSrcEmission[2] * aProperties.emsv,
310                                     1.f);
311
312   // Note: Here we use sub-linear transparency function
313   // to produce realistic-looking transparency effect
314   theMaterial.Transparency = BVH_Vec4f (powf (aProperties.trans, 0.75f),
315                                         1.f - aProperties.trans,
316                                         aProperties.index == 0 ? 1.f : aProperties.index,
317                                         aProperties.index == 0 ? 1.f : 1.f / aProperties.index);
318
319   const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
320                                       Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
321                                            theMaterial.Diffuse.z() + theMaterial.Specular.z()));
322
323   const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
324
325   theMaterial.Reflection = BVH_Vec4f (
326     aProperties.speccol.rgb[0] * aProperties.spec * aReflectionScale,
327     aProperties.speccol.rgb[1] * aProperties.spec * aReflectionScale,
328     aProperties.speccol.rgb[2] * aProperties.spec * aReflectionScale,
329     0.f);
330
331   if (theAspect->DoTextureMap())
332   {
333     if (myGlContext->arbTexBindless != NULL)
334     {
335       BuildTexTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
336       theMaterial.Diffuse.w() = static_cast<Standard_ShortReal> (
337         myRaytraceGeometry.AddTexture (theAspect->TextureRes (myGlContext)));
338     }
339     else if (!myIsRaytraceWarnTextures)
340     {
341       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
342                                 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
343                                 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
344                                 "Textures will be ignored.");
345       myIsRaytraceWarnTextures = Standard_True;
346     }
347   }
348
349   return Standard_True;
350 }
351
352 // =======================================================================
353 // function : AddRaytraceStructure
354 // purpose  : Adds OpenGL structure to ray-traced scene geometry
355 // =======================================================================
356 Standard_Boolean OpenGl_Workspace::AddRaytraceStructure (const OpenGl_Structure* theStructure, std::set<const OpenGl_Structure*>& theElements)
357 {
358   theElements.insert (theStructure);
359
360   if (!theStructure->IsVisible())
361   {
362     myStructureStates[theStructure] = theStructure->ModificationState();
363     return Standard_True;
364   }
365
366   // Get structure material
367   Standard_Integer aStructMatID = -1;
368
369   if (theStructure->AspectFace() != NULL)
370   {
371     aStructMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
372
373     OpenGl_RaytraceMaterial aStructMaterial;
374     CreateMaterial (theStructure->AspectFace(), aStructMaterial);
375
376     myRaytraceGeometry.Materials.push_back (aStructMaterial);
377   }
378
379   Standard_ShortReal  aStructTransformArr[16];
380   Standard_ShortReal* aStructTransform = NULL;
381   if (theStructure->Transformation()->mat != NULL)
382   {
383     aStructTransform = aStructTransformArr;
384     for (Standard_Integer i = 0; i < 4; ++i)
385     {
386       for (Standard_Integer j = 0; j < 4; ++j)
387       {
388         aStructTransform[j * 4 + i] = theStructure->Transformation()->mat[i][j];
389       }
390     }
391   }
392
393   AddRaytraceGroups (theStructure, aStructMatID, aStructTransform);
394
395   // Process all connected OpenGL structures
396   for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures()); anIts.More(); anIts.Next())
397   {
398     if (anIts.Value()->IsRaytracable())
399       AddRaytraceGroups (anIts.Value(), aStructMatID, aStructTransform);
400   }
401
402   myStructureStates[theStructure] = theStructure->ModificationState();
403   return Standard_True;
404 }
405
406 // =======================================================================
407 // function : AddRaytraceGroups
408 // purpose  : Adds OpenGL groups to ray-traced scene geometry
409 // =======================================================================
410 Standard_Boolean OpenGl_Workspace::AddRaytraceGroups (const OpenGl_Structure*   theStructure,
411                                                       const Standard_Integer    theStructMatId,
412                                                       const Standard_ShortReal* theTransform)
413 {
414   for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
415   {
416     // Get group material
417     Standard_Integer aGroupMatID = -1;
418     if (aGroupIter.Value()->AspectFace() != NULL)
419     {
420       aGroupMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
421
422       OpenGl_RaytraceMaterial aGroupMaterial;
423       CreateMaterial (aGroupIter.Value()->AspectFace(), aGroupMaterial);
424
425       myRaytraceGeometry.Materials.push_back (aGroupMaterial);
426     }
427
428     Standard_Integer aMatID = aGroupMatID < 0 ? theStructMatId : aGroupMatID;
429
430     if (aMatID < 0)
431     {
432       aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
433
434       myRaytraceGeometry.Materials.push_back (OpenGl_RaytraceMaterial());
435     }
436
437     // Add OpenGL elements from group (extract primitives arrays and aspects)
438     for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
439     {
440       OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
441       if (anAspect != NULL)
442       {
443         aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
444
445         OpenGl_RaytraceMaterial aMaterial;
446         CreateMaterial (anAspect, aMaterial);
447
448         myRaytraceGeometry.Materials.push_back (aMaterial);
449       }
450       else
451       {
452         OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
453
454         if (aPrimArray != NULL)
455         {
456           std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
457
458           if (aSetIter != myArrayToTrianglesMap.end())
459           {
460             OpenGl_TriangleSet* aSet = aSetIter->second;
461
462             BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
463
464             if (theTransform != NULL)
465             {
466               aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
467             }
468           
469             aSet->SetProperties (aTransform);
470
471             if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
472             {
473               aSet->SetMaterialIndex (aMatID);
474             }
475           }
476           else
477           {
478             NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
479               AddRaytracePrimitiveArray (aPrimArray, aMatID, 0);
480
481             if (!aSet.IsNull())
482             {
483               BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
484
485               if (theTransform != NULL)
486               {
487                 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
488               }
489
490               aSet->SetProperties (aTransform);
491
492               myRaytraceGeometry.Objects().Append (aSet);
493             }
494           }
495         }
496       }
497     }
498   }
499
500   return Standard_True;
501 }
502
503 // =======================================================================
504 // function : AddRaytracePrimitiveArray
505 // purpose  : Adds OpenGL primitive array to ray-traced scene geometry
506 // =======================================================================
507 OpenGl_TriangleSet* OpenGl_Workspace::AddRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
508                                                                  Standard_Integer             theMatID,
509                                                                  const OpenGl_Mat4*           theTransform)
510 {
511   const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
512   const Handle(Graphic3d_Buffer)&      anAttribs = theArray->Attributes();
513   const Handle(Graphic3d_BoundBuffer)& aBounds   = theArray->Bounds();
514   if (theArray->DrawMode() < GL_TRIANGLES
515   #if !defined(GL_ES_VERSION_2_0)
516    || theArray->DrawMode() > GL_POLYGON
517   #else
518    || theArray->DrawMode() > GL_TRIANGLE_FAN
519   #endif
520    || anAttribs.IsNull())
521   {
522     return NULL;
523   }
524
525 #ifdef RAY_TRACE_PRINT_INFO
526   switch (theArray->DrawMode())
527   {
528     case GL_TRIANGLES:      std::cout << "\tAdding GL_TRIANGLES\n";      break;
529     case GL_TRIANGLE_FAN:   std::cout << "\tAdding GL_TRIANGLE_FAN\n";   break;
530     case GL_TRIANGLE_STRIP: std::cout << "\tAdding GL_TRIANGLE_STRIP\n"; break;
531   #if !defined(GL_ES_VERSION_2_0)
532     case GL_QUADS:          std::cout << "\tAdding GL_QUADS\n";          break;
533     case GL_QUAD_STRIP:     std::cout << "\tAdding GL_QUAD_STRIP\n";     break;
534     case GL_POLYGON:        std::cout << "\tAdding GL_POLYGON\n";        break;
535   #endif
536   }
537 #endif
538
539   OpenGl_Mat4 aNormalMatrix;
540
541   if (theTransform != NULL)
542   {
543     Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
544       "Error: Failed to compute normal transformation matrix", NULL);
545
546     aNormalMatrix.Transpose();
547   }
548
549   OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
550   {
551     aSet->Vertices.reserve (anAttribs->NbElements);
552     aSet->Normals .reserve (anAttribs->NbElements);
553     aSet->TexCrds .reserve (anAttribs->NbElements);
554
555     const size_t aVertFrom = aSet->Vertices.size();
556     for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
557     {
558       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute       (anAttribIter);
559       const size_t               anOffset = anAttribs->AttributeOffset (anAttribIter);
560       if (anAttrib.Id == Graphic3d_TOA_POS)
561       {
562         if (anAttrib.DataType == Graphic3d_TOD_VEC3
563          || anAttrib.DataType == Graphic3d_TOD_VEC4)
564         {
565           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
566           {
567             aSet->Vertices.push_back (
568               *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset));
569           }
570         }
571         else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
572         {
573           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
574           {
575             const Graphic3d_Vec2& aVert = *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset);
576             aSet->Vertices.push_back (BVH_Vec3f (aVert.x(), aVert.y(), 0.0f));
577           }
578         }
579       }
580       else if (anAttrib.Id == Graphic3d_TOA_NORM)
581       {
582         if (anAttrib.DataType == Graphic3d_TOD_VEC3
583          || anAttrib.DataType == Graphic3d_TOD_VEC4)
584         {
585           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
586           {
587             aSet->Normals.push_back (
588               *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset));
589           }
590         }
591       }
592       else if (anAttrib.Id == Graphic3d_TOA_UV)
593       {
594         if (anAttrib.DataType == Graphic3d_TOD_VEC2)
595         {
596           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
597           {
598             aSet->TexCrds.push_back (
599               *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset));
600           }
601         }
602       }
603     }
604
605     if (aSet->Normals.size() != aSet->Vertices.size())
606     {
607       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
608       {
609         aSet->Normals.push_back (BVH_Vec3f());
610       }
611     }
612
613     if (aSet->TexCrds.size() != aSet->Vertices.size())
614     {
615       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
616       {
617         aSet->TexCrds.push_back (BVH_Vec2f());
618       }
619     }
620
621     if (theTransform != NULL)
622     {
623       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
624       {
625         BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
626
627         BVH_Vec4f aTransVertex =
628           *theTransform * BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
629
630         aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
631       }
632       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
633       {
634         BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
635
636         BVH_Vec4f aTransNormal =
637           aNormalMatrix * BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
638
639         aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
640       }
641     }
642
643     if (!aBounds.IsNull())
644     {
645 #ifdef RAY_TRACE_PRINT_INFO
646       std::cout << "\tNumber of bounds = " << aBounds->NbBounds << std::endl;
647 #endif
648
649       Standard_Integer aBoundStart = 0;
650       for (Standard_Integer aBound = 0; aBound < aBounds->NbBounds; ++aBound)
651       {
652         const Standard_Integer aVertNum = aBounds->Bounds[aBound];
653
654 #ifdef RAY_TRACE_PRINT_INFO
655         std::cout << "\tAdding indices from bound " << aBound << ": " <<
656                                       aBoundStart << " .. " << aVertNum << std::endl;
657 #endif
658
659         if (!AddRaytraceVertexIndices (*aSet, *theArray, aBoundStart, aVertNum, theMatID))
660         {
661           delete aSet;
662           return NULL;
663         }
664
665         aBoundStart += aVertNum;
666       }
667     }
668     else
669     {
670       const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
671
672   #ifdef RAY_TRACE_PRINT_INFO
673         std::cout << "\tAdding indices from array: " << aVertNum << std::endl;
674   #endif
675
676       if (!AddRaytraceVertexIndices (*aSet, *theArray, 0, aVertNum, theMatID))
677       {
678         delete aSet;
679         return NULL;
680       }
681     }
682   }
683
684   if (aSet->Size() != 0)
685     aSet->MarkDirty();
686
687   return aSet;
688 }
689
690 // =======================================================================
691 // function : AddRaytraceVertexIndices
692 // purpose  : Adds vertex indices to ray-traced scene geometry
693 // =======================================================================
694 Standard_Boolean OpenGl_Workspace::AddRaytraceVertexIndices (OpenGl_TriangleSet&          theSet,
695                                                              const OpenGl_PrimitiveArray& theArray,
696                                                              Standard_Integer             theOffset,
697                                                              Standard_Integer             theCount,
698                                                              Standard_Integer             theMatID)
699 {
700   switch (theArray.DrawMode())
701   {
702     case GL_TRIANGLES:      return AddRaytraceTriangleArray        (theSet, theArray.Indices(), theOffset, theCount, theMatID);
703     case GL_TRIANGLE_FAN:   return AddRaytraceTriangleFanArray     (theSet, theArray.Indices(), theOffset, theCount, theMatID);
704     case GL_TRIANGLE_STRIP: return AddRaytraceTriangleStripArray   (theSet, theArray.Indices(), theOffset, theCount, theMatID);
705   #if !defined(GL_ES_VERSION_2_0)
706     case GL_QUADS:          return AddRaytraceQuadrangleArray      (theSet, theArray.Indices(), theOffset, theCount, theMatID);
707     case GL_QUAD_STRIP:     return AddRaytraceQuadrangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
708     case GL_POLYGON:        return AddRaytracePolygonArray         (theSet, theArray.Indices(), theOffset, theCount, theMatID);
709   #endif
710   }
711   return Standard_False;
712 }
713
714 // =======================================================================
715 // function : AddRaytraceTriangleArray
716 // purpose  : Adds OpenGL triangle array to ray-traced scene geometry
717 // =======================================================================
718 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
719                                                              const Handle(Graphic3d_IndexBuffer)& theIndices,
720                                                              Standard_Integer                     theOffset,
721                                                              Standard_Integer                     theCount,
722                                                              Standard_Integer                     theMatID)
723 {
724   if (theCount < 3)
725     return Standard_True;
726
727   theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
728
729   if (!theIndices.IsNull())
730   {
731     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
732     {
733       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
734                                             theIndices->Index (aVert + 1),
735                                             theIndices->Index (aVert + 2),
736                                             theMatID));
737     }
738   }
739   else
740   {
741     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
742     {
743       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
744                                             theMatID));
745     }
746   }
747
748   return Standard_True;
749 }
750
751 // =======================================================================
752 // function : AddRaytraceTriangleFanArray
753 // purpose  : Adds OpenGL triangle fan array to ray-traced scene geometry
754 // =======================================================================
755 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
756                                                                 const Handle(Graphic3d_IndexBuffer)& theIndices,
757                                                                 Standard_Integer                     theOffset,
758                                                                 Standard_Integer                     theCount,
759                                                                 Standard_Integer                     theMatID)
760 {
761   if (theCount < 3)
762     return Standard_True;
763
764   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
765
766   if (!theIndices.IsNull())
767   {
768     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
769     {
770       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
771                                             theIndices->Index (aVert + 1),
772                                             theIndices->Index (aVert + 2),
773                                             theMatID));
774     }
775   }
776   else
777   {
778     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
779     {
780       theSet.Elements.push_back (BVH_Vec4i (theOffset,
781                                             aVert + 1,
782                                             aVert + 2,
783                                             theMatID));
784     }
785   }
786
787   return Standard_True;
788 }
789
790 // =======================================================================
791 // function : AddRaytraceTriangleStripArray
792 // purpose  : Adds OpenGL triangle strip array to ray-traced scene geometry
793 // =======================================================================
794 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
795                                                                   const Handle(Graphic3d_IndexBuffer)& theIndices,
796                                                                   Standard_Integer                     theOffset,
797                                                                   Standard_Integer                     theCount,
798                                                                   Standard_Integer                     theMatID)
799 {
800   if (theCount < 3)
801     return Standard_True;
802
803   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
804
805   if (!theIndices.IsNull())
806   {
807     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
808     {
809       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
810                                             theIndices->Index (aVert + aCW ? 0 : 1),
811                                             theIndices->Index (aVert + 2),
812                                             theMatID));
813     }
814   }
815   else
816   {
817     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
818     {
819       theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
820                                             aVert + aCW ? 0 : 1,
821                                             aVert + 2,
822                                             theMatID));
823     }
824   }
825
826   return Standard_True;
827 }
828
829 // =======================================================================
830 // function : AddRaytraceQuadrangleArray
831 // purpose  : Adds OpenGL quad array to ray-traced scene geometry
832 // =======================================================================
833 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
834                                                                const Handle(Graphic3d_IndexBuffer)& theIndices,
835                                                                Standard_Integer                     theOffset,
836                                                                Standard_Integer                     theCount,
837                                                                Standard_Integer                     theMatID)
838 {
839   if (theCount < 4)
840     return Standard_True;
841
842   theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
843
844   if (!theIndices.IsNull())
845   {
846     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
847     {
848       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
849                                             theIndices->Index (aVert + 1),
850                                             theIndices->Index (aVert + 2),
851                                             theMatID));
852       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
853                                             theIndices->Index (aVert + 2),
854                                             theIndices->Index (aVert + 3),
855                                             theMatID));
856     }
857   }
858   else
859   {
860     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
861     {
862       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
863                                             theMatID));
864       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
865                                             theMatID));
866     }
867   }
868
869   return Standard_True;
870 }
871
872 // =======================================================================
873 // function : AddRaytraceQuadrangleStripArray
874 // purpose  : Adds OpenGL quad strip array to ray-traced scene geometry
875 // =======================================================================
876 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
877                                                                     const Handle(Graphic3d_IndexBuffer)& theIndices,
878                                                                     Standard_Integer                     theOffset,
879                                                                     Standard_Integer                     theCount,
880                                                                     Standard_Integer                     theMatID)
881 {
882   if (theCount < 4)
883     return Standard_True;
884
885   theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
886
887   if (!theIndices.IsNull())
888   {
889     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
890     {
891       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
892                                             theIndices->Index (aVert + 1),
893                                             theIndices->Index (aVert + 2),
894                                             theMatID));
895
896       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
897                                             theIndices->Index (aVert + 3),
898                                             theIndices->Index (aVert + 2),
899                                             theMatID));
900     }
901   }
902   else
903   {
904     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
905     {
906       theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
907                                             aVert + 1,
908                                             aVert + 2,
909                                             theMatID));
910
911       theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
912                                             aVert + 3,
913                                             aVert + 2,
914                                             theMatID));
915     }
916   }
917
918   return Standard_True;
919 }
920
921 // =======================================================================
922 // function : AddRaytracePolygonArray
923 // purpose  : Adds OpenGL polygon array to ray-traced scene geometry
924 // =======================================================================
925 Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
926                                                             const Handle(Graphic3d_IndexBuffer)& theIndices,
927                                                             Standard_Integer                     theOffset,
928                                                             Standard_Integer                     theCount,
929                                                             Standard_Integer                     theMatID)
930 {
931   if (theCount < 3)
932     return Standard_True;
933
934   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
935
936   if (!theIndices.IsNull())
937   {
938     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
939     {
940       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
941                                             theIndices->Index (aVert + 1),
942                                             theIndices->Index (aVert + 2),
943                                             theMatID));
944     }
945   }
946   else
947   {
948     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
949     {
950       theSet.Elements.push_back (BVH_Vec4i (theOffset,
951                                             aVert + 1,
952                                             aVert + 2,
953                                             theMatID));
954     }
955   }
956
957   return Standard_True;
958 }
959
960 // =======================================================================
961 // function : UpdateRaytraceLightSources
962 // purpose  : Updates 3D scene light sources for ray-tracing
963 // =======================================================================
964 Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const OpenGl_Mat4& theInvModelView)
965 {
966   myRaytraceGeometry.Sources.clear();
967
968   myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
969
970   for (OpenGl_ListOfLight::Iterator anItl (myView->LightList()); anItl.More(); anItl.Next())
971   {
972     const OpenGl_Light& aLight = anItl.Value();
973
974     if (aLight.Type == Visual3d_TOLS_AMBIENT)
975     {
976       myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
977                                                aLight.Color.g(),
978                                                aLight.Color.b(),
979                                                0.0f);
980       continue;
981     }
982
983     BVH_Vec4f aDiffuse  (aLight.Color.r(),
984                          aLight.Color.g(),
985                          aLight.Color.b(),
986                          1.0f);
987
988     BVH_Vec4f aPosition (-aLight.Direction.x(),
989                          -aLight.Direction.y(),
990                          -aLight.Direction.z(),
991                          0.0f);
992
993     if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
994     {
995       aPosition = BVH_Vec4f (aLight.Position.x(),
996                              aLight.Position.y(),
997                              aLight.Position.z(),
998                              1.0f);
999     }
1000
1001     if (aLight.IsHeadlight)
1002     {
1003       aPosition = theInvModelView * aPosition;
1004     }
1005
1006     myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
1007   }
1008
1009   if (myRaytraceLightSrcTexture.IsNull())  // create light source buffer
1010   {
1011     myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
1012
1013     if (!myRaytraceLightSrcTexture->Create (myGlContext))
1014     {
1015 #ifdef RAY_TRACE_PRINT_INFO
1016       std::cout << "Error: Failed to create light source buffer" << std::endl;
1017 #endif
1018       return Standard_False;
1019     }
1020   }
1021   
1022   if (myRaytraceGeometry.Sources.size() != 0)
1023   {
1024     const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
1025     if (!myRaytraceLightSrcTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
1026     {
1027 #ifdef RAY_TRACE_PRINT_INFO
1028       std::cout << "Error: Failed to upload light source buffer" << std::endl;
1029 #endif
1030       return Standard_False;
1031     }
1032   }
1033
1034   return Standard_True;
1035 }
1036
1037 // =======================================================================
1038 // function : UpdateRaytraceEnvironmentMap
1039 // purpose  : Updates environment map for ray-tracing
1040 // =======================================================================
1041 Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
1042 {
1043   if (myView.IsNull())
1044     return Standard_False;
1045
1046   if (myViewModificationStatus == myView->ModificationState())
1047     return Standard_True;
1048
1049   for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
1050   {
1051     const Handle(OpenGl_ShaderProgram)& aProgram =
1052       anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
1053
1054     if (!aProgram.IsNull())
1055     {
1056       myGlContext->BindProgram (aProgram);
1057
1058       if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
1059       {
1060         myView->TextureEnv()->Bind (
1061           myGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
1062
1063         aProgram->SetUniform (myGlContext,
1064           myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 1);
1065       }
1066       else
1067       {
1068         aProgram->SetUniform (myGlContext,
1069           myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 0);
1070       }
1071     }
1072   }
1073
1074   myGlContext->BindProgram (NULL);
1075   myViewModificationStatus = myView->ModificationState();
1076   return Standard_True;
1077 }
1078
1079 // =======================================================================
1080 // function : Source
1081 // purpose  : Returns shader source combined with prefix
1082 // =======================================================================
1083 TCollection_AsciiString OpenGl_Workspace::ShaderSource::Source() const
1084 {
1085   static const TCollection_AsciiString aVersion = "#version 140";
1086
1087   if (myPrefix.IsEmpty())
1088   {
1089     return aVersion + "\n" + mySource;
1090   }
1091
1092   return aVersion + "\n" + myPrefix + "\n" + mySource;
1093 }
1094
1095 // =======================================================================
1096 // function : Load
1097 // purpose  : Loads shader source from specified files
1098 // =======================================================================
1099 void OpenGl_Workspace::ShaderSource::Load (
1100   const TCollection_AsciiString* theFileNames, const Standard_Integer theCount)
1101 {
1102   mySource.Clear();
1103
1104   for (Standard_Integer anIndex = 0; anIndex < theCount; ++anIndex)
1105   {
1106     OSD_File aFile (theFileNames[anIndex]);
1107
1108     Standard_ASSERT_RETURN (aFile.Exists(),
1109       "Error: Failed to find shader source file", /* none */);
1110
1111     aFile.Open (OSD_ReadOnly, OSD_Protection());
1112
1113     TCollection_AsciiString aSource;
1114
1115     Standard_ASSERT_RETURN (aFile.IsOpen(),
1116       "Error: Failed to open shader source file", /* none */);
1117
1118     aFile.Read (aSource, (Standard_Integer) aFile.Size());
1119
1120     if (!aSource.IsEmpty())
1121     {
1122       mySource += TCollection_AsciiString ("\n") + aSource;
1123     }
1124
1125     aFile.Close();
1126   }
1127 }
1128
1129 // =======================================================================
1130 // function : LoadShader
1131 // purpose  : Creates new shader object with specified source
1132 // =======================================================================
1133 Handle(OpenGl_ShaderObject) OpenGl_Workspace::LoadShader (const ShaderSource& theSource, GLenum theType)
1134 {
1135   Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1136
1137   if (!aShader->Create (myGlContext))
1138   {
1139     const TCollection_ExtendedString aMessage = "Error: Failed to create shader object";
1140       
1141     myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1142       GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1143
1144     aShader->Release (myGlContext.operator->());
1145
1146     return Handle(OpenGl_ShaderObject)();
1147   }
1148
1149   if (!aShader->LoadSource (myGlContext, theSource.Source()))
1150   {
1151     const TCollection_ExtendedString aMessage = "Error: Failed to set shader source";
1152       
1153     myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1154       GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1155
1156     aShader->Release (myGlContext.operator->());
1157
1158     return Handle(OpenGl_ShaderObject)();
1159   }
1160
1161   TCollection_AsciiString aBuildLog;
1162
1163   if (!aShader->Compile (myGlContext))
1164   {
1165     if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1166     {
1167       const TCollection_ExtendedString aMessage =
1168         TCollection_ExtendedString ("Error: Failed to compile shader object:\n") + aBuildLog;
1169
1170 #ifdef RAY_TRACE_PRINT_INFO
1171       std::cout << aBuildLog << std::endl;
1172 #endif
1173
1174       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1175         GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1176     }
1177     
1178     aShader->Release (myGlContext.operator->());
1179
1180     return Handle(OpenGl_ShaderObject)();
1181   }
1182
1183 #ifdef RAY_TRACE_PRINT_INFO
1184   if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1185   {
1186     if (!aBuildLog.IsEmpty())
1187     {
1188       std::cout << aBuildLog << std::endl;
1189     }
1190     else
1191     {
1192       std::cout << "Info: shader build log is empty" << std::endl;
1193     }
1194   }  
1195 #endif
1196
1197   return aShader;
1198 }
1199
1200 // =======================================================================
1201 // function : SafeFailBack
1202 // purpose  : Performs safe exit when shaders initialization fails
1203 // =======================================================================
1204 Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
1205 {
1206   myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1207     GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
1208
1209   myComputeInitStatus = OpenGl_RT_FAIL;
1210
1211   ReleaseRaytraceResources();
1212   
1213   return Standard_False;
1214 }
1215
1216 // =======================================================================
1217 // function : GenerateShaderPrefix
1218 // purpose  : Generates shader prefix based on current ray-tracing options
1219 // =======================================================================
1220 TCollection_AsciiString OpenGl_Workspace::GenerateShaderPrefix()
1221 {
1222   TCollection_AsciiString aPrefixString =
1223     TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1224     TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1225
1226   if (myRaytraceParameters.TransparentShadows)
1227   {
1228     aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1229   }
1230
1231   // If OpenGL driver supports bindless textures
1232   // activate texturing in ray-tracing mode
1233   if (myGlContext->arbTexBindless != NULL)
1234   {
1235     aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1236       TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1237   }
1238
1239   return aPrefixString;
1240 }
1241
1242 // =======================================================================
1243 // function : InitRaytraceResources
1244 // purpose  : Initializes OpenGL/GLSL shader programs
1245 // =======================================================================
1246 Standard_Boolean OpenGl_Workspace::InitRaytraceResources (const Graphic3d_CView& theCView)
1247 {
1248   Standard_Boolean aToRebuildShaders = Standard_False;
1249
1250   if (myComputeInitStatus == OpenGl_RT_INIT)
1251   {
1252     if (!myIsRaytraceDataValid)
1253       return Standard_True;
1254
1255     const Standard_Integer aRequiredStackSize =
1256       myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
1257
1258     if (myRaytraceParameters.StackSize < aRequiredStackSize)
1259     {
1260       myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1261
1262       aToRebuildShaders = Standard_True;
1263     }
1264     else
1265     {
1266       if (aRequiredStackSize < myRaytraceParameters.StackSize)
1267       {
1268         if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1269         {
1270           myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1271           aToRebuildShaders = Standard_True;
1272         }
1273       }
1274     }
1275
1276     if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
1277     {
1278       myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1279       aToRebuildShaders = Standard_True;
1280     }
1281
1282     if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1283     {
1284       myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
1285       aToRebuildShaders = Standard_True;
1286     }
1287
1288     if (aToRebuildShaders)
1289     {
1290 #ifdef RAY_TRACE_PRINT_INFO
1291       std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
1292 #endif
1293
1294       // Change state to force update all uniforms
1295       ++myViewModificationStatus;
1296
1297       TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
1298
1299 #ifdef RAY_TRACE_PRINT_INFO
1300       std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1301 #endif
1302
1303       myRaytraceShaderSource.SetPrefix (aPrefixString);
1304       myPostFSAAShaderSource.SetPrefix (aPrefixString);
1305
1306       if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1307        || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1308       {
1309         return Standard_False;
1310       }
1311
1312       if (!myRaytraceShader->Compile (myGlContext)
1313        || !myPostFSAAShader->Compile (myGlContext))
1314       {
1315         return Standard_False;
1316       }
1317
1318       myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1319       myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1320       if (!myRaytraceProgram->Link (myGlContext)
1321        || !myPostFSAAProgram->Link (myGlContext))
1322       {
1323         return Standard_False;
1324       }
1325     }
1326   }
1327
1328   if (myComputeInitStatus == OpenGl_RT_NONE)
1329   {
1330     if (!myGlContext->IsGlGreaterEqual (3, 1))
1331     {
1332       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1333                                 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1334                                 "Ray-tracing requires OpenGL 3.1 and higher");
1335       return Standard_False;
1336     }
1337     else if (!myGlContext->arbTboRGB32)
1338     {
1339       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1340                                 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1341                                 "Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension");
1342       return Standard_False;
1343     }
1344
1345     myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1346
1347     TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
1348
1349     if (aFolder.IsEmpty())
1350     {
1351       const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1352       
1353       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1354         GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1355       
1356       return Standard_False;
1357     }
1358
1359     if (myIsRaytraceDataValid)
1360     {
1361       myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1362         myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1363     }
1364
1365     TCollection_AsciiString aPrefixString  = GenerateShaderPrefix();
1366
1367 #ifdef RAY_TRACE_PRINT_INFO
1368     std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1369 #endif
1370
1371     {
1372       Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1373         ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1374
1375       if (aBasicVertShader.IsNull())
1376       {
1377         return SafeFailBack ("Failed to set vertex shader source");
1378       }
1379
1380       TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
1381
1382       myRaytraceShaderSource.Load (aFiles, 2);
1383
1384       myRaytraceShaderSource.SetPrefix (aPrefixString);
1385
1386       myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
1387
1388       if (myRaytraceShader.IsNull())
1389       {
1390         aBasicVertShader->Release (myGlContext.operator->());
1391
1392         return SafeFailBack ("Failed to set ray-trace fragment shader source");
1393       }
1394
1395       myRaytraceProgram = new OpenGl_ShaderProgram;
1396
1397       if (!myRaytraceProgram->Create (myGlContext))
1398       {
1399         aBasicVertShader->Release (myGlContext.operator->());
1400
1401         return SafeFailBack ("Failed to create ray-trace shader program");
1402       }
1403
1404       if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1405        || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1406       {
1407         aBasicVertShader->Release (myGlContext.operator->());
1408
1409         return SafeFailBack ("Failed to attach ray-trace shader objects");
1410       }
1411
1412       myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1413       if (!myRaytraceProgram->Link (myGlContext))
1414       {
1415         TCollection_AsciiString aLinkLog;
1416
1417         if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1418         {
1419   #ifdef RAY_TRACE_PRINT_INFO
1420           std::cout << aLinkLog << std::endl;
1421   #endif
1422         }
1423
1424         return SafeFailBack ("Failed to link ray-trace shader program");
1425       }
1426     }
1427
1428     {
1429       Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1430         ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1431
1432       if (aBasicVertShader.IsNull())
1433       {
1434         return SafeFailBack ("Failed to set vertex shader source");
1435       }
1436
1437       TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
1438
1439       myPostFSAAShaderSource.Load (aFiles, 2);
1440
1441       myPostFSAAShaderSource.SetPrefix (aPrefixString);
1442     
1443       myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
1444
1445       if (myPostFSAAShader.IsNull())
1446       {
1447         aBasicVertShader->Release (myGlContext.operator->());
1448
1449         return SafeFailBack ("Failed to set FSAA fragment shader source");
1450       }
1451
1452       myPostFSAAProgram = new OpenGl_ShaderProgram;
1453
1454       if (!myPostFSAAProgram->Create (myGlContext))
1455       {
1456         aBasicVertShader->Release (myGlContext.operator->());
1457
1458         return SafeFailBack ("Failed to create FSAA shader program");
1459       }
1460
1461       if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1462        || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1463       {
1464         aBasicVertShader->Release (myGlContext.operator->());
1465
1466         return SafeFailBack ("Failed to attach FSAA shader objects");
1467       }
1468
1469       myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1470       if (!myPostFSAAProgram->Link (myGlContext))
1471       {
1472         TCollection_AsciiString aLinkLog;
1473
1474         if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1475         {
1476   #ifdef RAY_TRACE_PRINT_INFO
1477           std::cout << aLinkLog << std::endl;
1478   #endif
1479         }
1480       
1481         return SafeFailBack ("Failed to link FSAA shader program");
1482       }
1483     }
1484   }
1485
1486   if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1487   {
1488     for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1489     {
1490       Handle(OpenGl_ShaderProgram)& aShaderProgram =
1491         (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1492
1493       myGlContext->BindProgram (aShaderProgram);
1494
1495       aShaderProgram->SetSampler (myGlContext,
1496         "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1497       aShaderProgram->SetSampler (myGlContext,
1498         "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1499       aShaderProgram->SetSampler (myGlContext,
1500         "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1501       aShaderProgram->SetSampler (myGlContext,
1502         "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1503       aShaderProgram->SetSampler (myGlContext,
1504         "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1505       aShaderProgram->SetSampler (myGlContext,
1506         "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1507       aShaderProgram->SetSampler (myGlContext,
1508         "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1509       aShaderProgram->SetSampler (myGlContext, 
1510         "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1511       aShaderProgram->SetSampler (myGlContext,
1512         "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1513       aShaderProgram->SetSampler (myGlContext,
1514         "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1515       aShaderProgram->SetSampler (myGlContext,
1516         "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1517
1518       aShaderProgram->SetSampler (myGlContext,
1519         "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1520       aShaderProgram->SetSampler (myGlContext,
1521         "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1522
1523       if (anIndex == 1)
1524       {
1525         aShaderProgram->SetSampler (myGlContext,
1526           "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1527       }
1528
1529       myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1530         aShaderProgram->GetAttributeLocation (myGlContext, "occVertex");
1531
1532       myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1533         aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1534       myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1535         aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1536       myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1537         aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1538       myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1539         aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1540       myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1541         aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1542       myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1543         aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1544       myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1545         aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1546       myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1547         aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
1548       myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1549         aShaderProgram->GetUniformLocation (myGlContext, "uUnviewMat");
1550
1551       myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1552         aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1553       myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1554         aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1555       myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1556         aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1557       myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1558         aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1559
1560       myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1561         aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1562       myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1563         aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1564       myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1565         aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
1566       myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1567         aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeX");
1568       myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1569         aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeY");
1570
1571       myUniformLocations[anIndex][OpenGl_RT_uTextures] =
1572         aShaderProgram->GetUniformLocation (myGlContext, "uTextureSamplers");
1573
1574       myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1575         aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1576       myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1577         aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1578       myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnable] =
1579         aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
1580     }
1581
1582     myGlContext->BindProgram (NULL);
1583   }
1584
1585   if (myComputeInitStatus != OpenGl_RT_NONE)
1586   {
1587     return myComputeInitStatus == OpenGl_RT_INIT;
1588   }
1589
1590   if (myRaytraceFBO1.IsNull())
1591   {
1592     myRaytraceFBO1 = new OpenGl_FrameBuffer;
1593   }
1594
1595   if (myRaytraceFBO2.IsNull())
1596   {
1597     myRaytraceFBO2 = new OpenGl_FrameBuffer;
1598   }
1599
1600   const GLfloat aVertices[] = { -1.f, -1.f,  0.f,
1601                                 -1.f,  1.f,  0.f,
1602                                  1.f,  1.f,  0.f,
1603                                  1.f,  1.f,  0.f,
1604                                  1.f, -1.f,  0.f,
1605                                 -1.f, -1.f,  0.f };
1606
1607   myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
1608
1609   myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
1610
1611   return Standard_True;
1612 }
1613
1614 // =======================================================================
1615 // function : NullifyResource
1616 // purpose  :
1617 // =======================================================================
1618 inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1619                              Handle(OpenGl_Resource)&      theResource)
1620 {
1621   if (!theResource.IsNull())
1622   {
1623     theResource->Release (theContext.operator->());
1624     theResource.Nullify();
1625   }
1626 }
1627
1628 // =======================================================================
1629 // function : ReleaseRaytraceResources
1630 // purpose  : Releases OpenGL/GLSL shader programs
1631 // =======================================================================
1632 void OpenGl_Workspace::ReleaseRaytraceResources()
1633 {
1634   NullifyResource (myGlContext, myOpenGlFBO);
1635   NullifyResource (myGlContext, myRaytraceFBO1);
1636   NullifyResource (myGlContext, myRaytraceFBO2);
1637
1638   NullifyResource (myGlContext, myRaytraceShader);
1639   NullifyResource (myGlContext, myPostFSAAShader);
1640
1641   NullifyResource (myGlContext, myRaytraceProgram);
1642   NullifyResource (myGlContext, myPostFSAAProgram);
1643
1644   NullifyResource (myGlContext, mySceneNodeInfoTexture);
1645   NullifyResource (myGlContext, mySceneMinPointTexture);
1646   NullifyResource (myGlContext, mySceneMaxPointTexture);
1647
1648   NullifyResource (myGlContext, myGeometryVertexTexture);
1649   NullifyResource (myGlContext, myGeometryNormalTexture);
1650   NullifyResource (myGlContext, myGeometryTexCrdTexture);
1651   NullifyResource (myGlContext, myGeometryTriangTexture);
1652   NullifyResource (myGlContext, mySceneTransformTexture);
1653
1654   NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1655   NullifyResource (myGlContext, myRaytraceMaterialTexture);
1656
1657   if (myRaytraceScreenQuad.IsValid())
1658     myRaytraceScreenQuad.Release (myGlContext.operator->());
1659 }
1660
1661 // =======================================================================
1662 // function : UploadRaytraceData
1663 // purpose  : Uploads ray-trace data to the GPU
1664 // =======================================================================
1665 Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1666 {
1667   if (!myGlContext->IsGlGreaterEqual (3, 1))
1668   {
1669 #ifdef RAY_TRACE_PRINT_INFO
1670     std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1671 #endif
1672     return Standard_False;
1673   }
1674
1675   /////////////////////////////////////////////////////////////////////////////
1676   // Prepare OpenGL textures
1677
1678   if (myGlContext->arbTexBindless != NULL)
1679   {
1680     // If OpenGL driver supports bindless textures we need
1681     // to get unique 64- bit handles for using on the GPU
1682     if (!myRaytraceGeometry.UpdateTextureHandles (myGlContext))
1683     {
1684 #ifdef RAY_TRACE_PRINT_INFO
1685       std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1686 #endif
1687       return Standard_False;
1688     }
1689   }
1690
1691   /////////////////////////////////////////////////////////////////////////////
1692   // Create OpenGL BVH buffers
1693
1694   if (mySceneNodeInfoTexture.IsNull())  // create scene BVH buffers
1695   {
1696     mySceneNodeInfoTexture  = new OpenGl_TextureBufferArb;
1697     mySceneMinPointTexture  = new OpenGl_TextureBufferArb;
1698     mySceneMaxPointTexture  = new OpenGl_TextureBufferArb;
1699     mySceneTransformTexture = new OpenGl_TextureBufferArb;
1700
1701     if (!mySceneNodeInfoTexture->Create  (myGlContext)
1702      || !mySceneMinPointTexture->Create  (myGlContext)
1703      || !mySceneMaxPointTexture->Create  (myGlContext)
1704      || !mySceneTransformTexture->Create (myGlContext))
1705     {
1706 #ifdef RAY_TRACE_PRINT_INFO
1707       std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
1708 #endif
1709       return Standard_False;
1710     }
1711   }
1712
1713   if  (myGeometryVertexTexture.IsNull())  // create geometry buffers
1714   {
1715     myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1716     myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1717     myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
1718     myGeometryTriangTexture = new OpenGl_TextureBufferArb;
1719
1720     if (!myGeometryVertexTexture->Create (myGlContext)
1721      || !myGeometryNormalTexture->Create (myGlContext)
1722      || !myGeometryTexCrdTexture->Create (myGlContext)
1723      || !myGeometryTriangTexture->Create (myGlContext))
1724     {
1725 #ifdef RAY_TRACE_PRINT_INFO
1726       std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1727 #endif
1728       return Standard_False;
1729     }
1730   }
1731
1732   if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1733   {
1734     myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
1735
1736     if (!myRaytraceMaterialTexture->Create (myGlContext))
1737     {
1738 #ifdef RAY_TRACE_PRINT_INFO
1739       std::cout << "Error: Failed to create buffers for material data" << std::endl;
1740 #endif
1741       return Standard_False;
1742     }
1743   }
1744   
1745   /////////////////////////////////////////////////////////////////////////////
1746   // Write transform buffer
1747
1748   BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1749
1750   bool aResult = true;
1751
1752   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1753   {
1754     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1755       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1756
1757     const BVH_Transform<Standard_ShortReal, 4>* aTransform = 
1758       dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1759
1760     Standard_ASSERT_RETURN (aTransform != NULL,
1761       "OpenGl_TriangleSet does not contain transform", Standard_False);
1762
1763     aNodeTransforms[anElemIndex] = aTransform->Inversed();
1764   }
1765
1766   aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1767     myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1768
1769   delete [] aNodeTransforms;
1770
1771   /////////////////////////////////////////////////////////////////////////////
1772   // Write geometry and bottom-level BVH buffers
1773
1774   Standard_Size aTotalVerticesNb = 0;
1775   Standard_Size aTotalElementsNb = 0;
1776   Standard_Size aTotalBVHNodesNb = 0;
1777
1778   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1779   {
1780     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1781       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1782
1783     Standard_ASSERT_RETURN (aTriangleSet != NULL,
1784       "Error: Failed to get triangulation of OpenGL element", Standard_False);
1785
1786     aTotalVerticesNb += aTriangleSet->Vertices.size();
1787     aTotalElementsNb += aTriangleSet->Elements.size();
1788
1789     Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1790       "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
1791
1792     aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1793   }
1794
1795   aTotalBVHNodesNb += myRaytraceGeometry.BVH()->NodeInfoBuffer().size();
1796
1797   if (aTotalBVHNodesNb != 0)
1798   {
1799     aResult &= mySceneNodeInfoTexture->Init (
1800       myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*>  (NULL));
1801     aResult &= mySceneMinPointTexture->Init (
1802       myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1803     aResult &= mySceneMaxPointTexture->Init (
1804       myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1805   }
1806
1807   if (!aResult)
1808   {
1809 #ifdef RAY_TRACE_PRINT_INFO
1810     std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1811 #endif
1812     return Standard_False;
1813   }
1814
1815   if (aTotalElementsNb != 0)
1816   {
1817     aResult &= myGeometryTriangTexture->Init (
1818       myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
1819   }
1820
1821   if (aTotalVerticesNb != 0)
1822   {
1823     aResult &= myGeometryVertexTexture->Init (
1824       myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1825     aResult &= myGeometryNormalTexture->Init (
1826       myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1827     aResult &= myGeometryTexCrdTexture->Init (
1828       myGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1829   }
1830
1831   if (!aResult)
1832   {
1833 #ifdef RAY_TRACE_PRINT_INFO
1834     std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1835 #endif
1836     return Standard_False;
1837   }
1838
1839   const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = myRaytraceGeometry.BVH();
1840   const Standard_Integer aBvhLength = aBVH->Length();
1841   if (aBvhLength > 0)
1842   {
1843     aResult &= mySceneNodeInfoTexture->SubData (myGlContext, 0, aBVH->Length(),
1844       reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1845     aResult &= mySceneMinPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1846       reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1847     aResult &= mySceneMaxPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1848       reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
1849   }
1850
1851   for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1852   {
1853     if (!aBVH->IsOuter (aNodeIdx))
1854       continue;
1855
1856     OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
1857
1858     Standard_ASSERT_RETURN (aTriangleSet != NULL,
1859       "Error: Failed to get triangulation of OpenGL element", Standard_False);
1860
1861     Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
1862
1863     Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1864       "Error: Failed to get offset for bottom-level BVH", Standard_False);
1865
1866     const Standard_Integer aBvhBuffersSize = aTriangleSet->BVH()->Length();
1867
1868     if (aBvhBuffersSize != 0)
1869     {
1870       aResult &= mySceneNodeInfoTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1871                                                    reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1872       aResult &= mySceneMinPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1873                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1874       aResult &= mySceneMaxPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1875                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
1876       if (!aResult)
1877       {
1878 #ifdef RAY_TRACE_PRINT_INFO
1879         std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1880 #endif
1881         return Standard_False;
1882       }
1883     }
1884
1885     const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
1886
1887     Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1888       "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
1889
1890     if (!aTriangleSet->Vertices.empty())
1891     {
1892       aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1893                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1894       aResult &= myGeometryTexCrdTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->TexCrds.size()),
1895                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
1896       aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1897                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
1898     }
1899
1900     const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
1901
1902     Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1903       "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
1904
1905     if (!aTriangleSet->Elements.empty())
1906     {
1907       aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1908                                                    reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
1909     }
1910
1911     if (!aResult)
1912     {
1913 #ifdef RAY_TRACE_PRINT_INFO
1914       std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
1915 #endif
1916       return Standard_False;
1917     }
1918   }
1919
1920   /////////////////////////////////////////////////////////////////////////////
1921   // Write material buffer
1922
1923   if (myRaytraceGeometry.Materials.size() != 0)
1924   {
1925     aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4,
1926       GLsizei (myRaytraceGeometry.Materials.size() * 11),  myRaytraceGeometry.Materials.front().Packed());
1927
1928     if (!aResult)
1929     {
1930 #ifdef RAY_TRACE_PRINT_INFO
1931       std::cout << "Error: Failed to upload material buffer" << std::endl;
1932 #endif
1933       return Standard_False;
1934     }
1935   }
1936
1937   myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
1938
1939 #ifdef RAY_TRACE_PRINT_INFO
1940
1941   Standard_ShortReal aMemUsed = 0.f;
1942
1943   for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1944   {
1945     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1946       myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
1947
1948     aMemUsed += static_cast<Standard_ShortReal> (
1949       aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
1950     aMemUsed += static_cast<Standard_ShortReal> (
1951       aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
1952     aMemUsed += static_cast<Standard_ShortReal> (
1953       aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
1954     aMemUsed += static_cast<Standard_ShortReal> (
1955       aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
1956
1957     aMemUsed += static_cast<Standard_ShortReal> (
1958       aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1959     aMemUsed += static_cast<Standard_ShortReal> (
1960       aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1961     aMemUsed += static_cast<Standard_ShortReal> (
1962       aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1963   }
1964
1965   aMemUsed += static_cast<Standard_ShortReal> (
1966     myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1967   aMemUsed += static_cast<Standard_ShortReal> (
1968     myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1969   aMemUsed += static_cast<Standard_ShortReal> (
1970     myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1971
1972   std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
1973
1974 #endif
1975
1976   return aResult;
1977 }
1978
1979 // =======================================================================
1980 // function : ResizeRaytraceBuffers
1981 // purpose  : Resizes OpenGL frame buffers
1982 // =======================================================================
1983 Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1984                                                           const Standard_Integer theSizeY)
1985 {
1986   if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1987    || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1988   {
1989     myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
1990     myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
1991   }
1992
1993   return Standard_True;
1994 }
1995
1996 // =======================================================================
1997 // function : UpdateCamera
1998 // purpose  : Generates viewing rays for corners of screen quad
1999 // =======================================================================
2000 void OpenGl_Workspace::UpdateCamera (const OpenGl_Mat4& theOrientation,
2001                                      const OpenGl_Mat4& theViewMapping,
2002                                      OpenGl_Vec3        theOrigins[4],
2003                                      OpenGl_Vec3        theDirects[4],
2004                                      OpenGl_Mat4&       theInvModelProj)
2005 {
2006   // compute inverse model-view-projection matrix
2007   (theViewMapping * theOrientation).Inverted (theInvModelProj);
2008
2009   Standard_Integer aOriginIndex = 0;
2010   Standard_Integer aDirectIndex = 0;
2011
2012   for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2013   {
2014     for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2015     {
2016       OpenGl_Vec4 aOrigin (GLfloat(aX),
2017                            GLfloat(aY),
2018                           -1.0f,
2019                            1.0f);
2020
2021       aOrigin = theInvModelProj * aOrigin;
2022
2023       aOrigin.x() = aOrigin.x() / aOrigin.w();
2024       aOrigin.y() = aOrigin.y() / aOrigin.w();
2025       aOrigin.z() = aOrigin.z() / aOrigin.w();
2026
2027       OpenGl_Vec4 aDirect (GLfloat(aX),
2028                            GLfloat(aY),
2029                            1.0f,
2030                            1.0f);
2031
2032       aDirect = theInvModelProj * aDirect;
2033
2034       aDirect.x() = aDirect.x() / aDirect.w();
2035       aDirect.y() = aDirect.y() / aDirect.w();
2036       aDirect.z() = aDirect.z() / aDirect.w();
2037
2038       aDirect = aDirect - aOrigin;
2039
2040       GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
2041                                      aDirect.y() * aDirect.y() +
2042                                      aDirect.z() * aDirect.z());
2043
2044       theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2045                                                 static_cast<GLfloat> (aOrigin.y()),
2046                                                 static_cast<GLfloat> (aOrigin.z()));
2047
2048       theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
2049                                                 static_cast<GLfloat> (aDirect.y() * aInvLen),
2050                                                 static_cast<GLfloat> (aDirect.z() * aInvLen));
2051     }
2052   }
2053 }
2054
2055 // =======================================================================
2056 // function : SetUniformState
2057 // purpose  : Sets uniform state for the given ray-tracing shader program
2058 // =======================================================================
2059 Standard_Boolean OpenGl_Workspace::SetUniformState (const Graphic3d_CView&        theCView,
2060                                                     const Standard_Integer        theSizeX,
2061                                                     const Standard_Integer        theSizeY,
2062                                                     const OpenGl_Vec3*            theOrigins,
2063                                                     const OpenGl_Vec3*            theDirects,
2064                                                     const OpenGl_Mat4&            theUnviewMat,
2065                                                     const Standard_Integer        theProgramIndex,
2066                                                     Handle(OpenGl_ShaderProgram)& theRaytraceProgram)
2067 {
2068   if (theRaytraceProgram.IsNull())
2069   {
2070     return Standard_False;
2071   }
2072
2073   Standard_Integer aLightSourceBufferSize =
2074     static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2075
2076   Standard_Boolean aResult = Standard_True;
2077
2078   // Set camera state
2079   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2080     myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLB], theOrigins[0]);
2081   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2082     myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRB], theOrigins[1]);
2083   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2084     myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLT], theOrigins[2]);
2085   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2086     myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRT], theOrigins[3]);
2087   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2088     myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLB], theDirects[0]);
2089   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2090     myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRB], theDirects[1]);
2091   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2092     myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLT], theDirects[2]);
2093   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2094     myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRT], theDirects[3]);
2095   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2096     myUniformLocations[theProgramIndex][OpenGl_RT_uUnviewMat], theUnviewMat);
2097
2098   // Set window size
2099   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2100     myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeX], theSizeX);
2101   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2102     myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeY], theSizeY);
2103
2104   // Set scene parameters
2105   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2106     myUniformLocations[theProgramIndex][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2107   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2108     myUniformLocations[theProgramIndex][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2109   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2110     myUniformLocations[theProgramIndex][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2111   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2112     myUniformLocations[theProgramIndex][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2113
2114   // Set rendering options
2115   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2116     myUniformLocations[theProgramIndex][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
2117   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2118     myUniformLocations[theProgramIndex][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
2119
2120   // Set array of 64-bit texture handles
2121   if (myGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2122   {
2123     aResult &= theRaytraceProgram->SetUniform (myGlContext, "uTextureSamplers",
2124       static_cast<GLsizei> (myRaytraceGeometry.TextureHandles().size()), &myRaytraceGeometry.TextureHandles()[0]);
2125   }
2126
2127   if (!aResult)
2128   {
2129 #ifdef RAY_TRACE_PRINT_INFO
2130     std::cout << "Info: Not all uniforms were detected (for program " << theProgramIndex << ")" << std::endl;
2131 #endif
2132   }
2133
2134   return aResult;
2135 }
2136
2137 // =======================================================================
2138 // function : RunRaytraceShaders
2139 // purpose  : Runs ray-tracing shader programs
2140 // =======================================================================
2141 Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
2142                                                        const Standard_Integer theSizeX,
2143                                                        const Standard_Integer theSizeY,
2144                                                        const OpenGl_Vec3      theOrigins[4],
2145                                                        const OpenGl_Vec3      theDirects[4],
2146                                                        const OpenGl_Mat4&     theUnviewMat,
2147                                                        OpenGl_FrameBuffer*    theFrameBuffer)
2148 {
2149   mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2150   mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2151   mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2152   myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2153   myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2154   myGeometryTexCrdTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2155   myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2156   mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2157   myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2158   myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2159   
2160   myOpenGlFBO->ColorTexture()->Bind        (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2161   myOpenGlFBO->DepthStencilTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2162
2163   if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
2164   {
2165     myRaytraceFBO1->BindBuffer (myGlContext);
2166     
2167     glDisable (GL_BLEND);
2168   }
2169
2170   myGlContext->BindProgram (myRaytraceProgram);
2171
2172   SetUniformState (theCView,
2173                    theSizeX,
2174                    theSizeY,
2175                    theOrigins,
2176                    theDirects,
2177                    theUnviewMat,
2178                    0, // ID of RT program
2179                    myRaytraceProgram);
2180
2181   myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2182   {
2183     myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2184     myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2185   }
2186   myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2187
2188   if (!theCView.RenderParams.IsAntialiasingEnabled)
2189   {
2190     myGlContext->BindProgram (NULL);
2191
2192     myOpenGlFBO->ColorTexture()->Unbind        (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2193     myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2194     mySceneMinPointTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2195     mySceneMaxPointTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2196     mySceneNodeInfoTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2197     myGeometryVertexTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2198     myGeometryNormalTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2199     myGeometryTexCrdTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2200     myGeometryTriangTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2201     mySceneTransformTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2202     myRaytraceMaterialTexture->UnbindTexture   (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2203     myRaytraceLightSrcTexture->UnbindTexture   (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2204
2205     myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2206
2207     return Standard_True;
2208   }
2209
2210   myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2211
2212   myGlContext->BindProgram (myPostFSAAProgram);
2213
2214   SetUniformState (theCView,
2215                    theSizeX,
2216                    theSizeY,
2217                    theOrigins,
2218                    theDirects,
2219                    theUnviewMat,
2220                    1, // ID of FSAA program
2221                    myPostFSAAProgram);
2222
2223   myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2224   myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2225
2226   // Perform multi-pass adaptive FSAA using ping-pong technique.
2227   // We use 'FLIPTRI' sampling pattern changing for every pixel
2228   // (3 additional samples per pixel, the 1st sample is already
2229   // available from initial ray-traced image).
2230   for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2231   {
2232     GLfloat aOffsetX = 1.f / theSizeX;
2233     GLfloat aOffsetY = 1.f / theSizeY;
2234
2235     if (anIt == 1)
2236     {
2237       aOffsetX *= -0.55f;
2238       aOffsetY *=  0.55f;
2239     }
2240     else if (anIt == 2)
2241     {
2242       aOffsetX *=  0.00f;
2243       aOffsetY *= -0.55f;
2244     }
2245     else if (anIt == 3)
2246     {
2247       aOffsetX *= 0.55f;
2248       aOffsetY *= 0.00f;
2249     }
2250
2251     myPostFSAAProgram->SetUniform (myGlContext,
2252       myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2253     myPostFSAAProgram->SetUniform (myGlContext,
2254       myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2255     myPostFSAAProgram->SetUniform (myGlContext,
2256       myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2257
2258     Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
2259
2260     if (anIt == 3) // disable FBO on last iteration
2261     {
2262       glEnable (GL_BLEND);
2263
2264       if (theFrameBuffer != NULL)
2265         theFrameBuffer->BindBuffer (myGlContext);
2266     }
2267     else
2268     {
2269       aFramebuffer->BindBuffer (myGlContext);
2270     }
2271
2272     myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2273
2274     if (anIt != 3) // set input for the next pass
2275     {
2276       aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2277       aFramebuffer->UnbindBuffer (myGlContext);
2278     }
2279   }
2280
2281   myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2282
2283   myGlContext->BindProgram (NULL);
2284   myRaytraceFBO1->ColorTexture()->Unbind     (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2285   myOpenGlFBO->ColorTexture()->Unbind        (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2286   myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2287   mySceneMinPointTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2288   mySceneMaxPointTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2289   mySceneNodeInfoTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2290   myGeometryVertexTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2291   myGeometryNormalTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2292   myGeometryTexCrdTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2293   myGeometryTriangTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2294   mySceneTransformTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2295   myRaytraceMaterialTexture->UnbindTexture   (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2296   myRaytraceLightSrcTexture->UnbindTexture   (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2297
2298   myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2299
2300   return Standard_True;
2301 }
2302
2303 // =======================================================================
2304 // function : Raytrace
2305 // purpose  : Redraws the window using OpenGL/GLSL ray-tracing
2306 // =======================================================================
2307 Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
2308                                              const Standard_Integer theSizeX,
2309                                              const Standard_Integer theSizeY,
2310                                              const Aspect_CLayer2d& theCOverLayer,
2311                                              const Aspect_CLayer2d& theCUnderLayer,
2312                                              OpenGl_FrameBuffer*    theFrameBuffer)
2313 {
2314   if (!InitRaytraceResources (theCView))
2315     return Standard_False;
2316
2317   if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
2318     return Standard_False;
2319
2320   if (!UpdateRaytraceEnvironmentMap())
2321     return Standard_False;
2322
2323   // Get model-view and projection matrices
2324   OpenGl_Mat4 aOrientationMatrix;
2325   OpenGl_Mat4 aViewMappingMatrix;
2326
2327   myView->GetMatrices (aOrientationMatrix,
2328                        aViewMappingMatrix);
2329
2330   OpenGl_Mat4 aInvOrientationMatrix;
2331   aOrientationMatrix.Inverted (aInvOrientationMatrix);
2332
2333   if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
2334     return Standard_False;
2335
2336   OpenGl_Vec3 aOrigins[4];
2337   OpenGl_Vec3 aDirects[4];
2338   OpenGl_Mat4 anUnviewMat;
2339
2340   UpdateCamera (aOrientationMatrix,
2341                 aViewMappingMatrix,
2342                 aOrigins,
2343                 aDirects,
2344                 anUnviewMat);
2345
2346   Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2347   Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
2348
2349   glDisable (GL_DEPTH_TEST);
2350
2351   if (theFrameBuffer != NULL)
2352   {
2353     theFrameBuffer->BindBuffer (myGlContext);
2354   }
2355
2356   if (NamedStatus & OPENGL_NS_WHITEBACK)
2357   {
2358     glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2359   }
2360   else
2361   {
2362     glClearColor (myBgColor.rgb[0],
2363                   myBgColor.rgb[1],
2364                   myBgColor.rgb[2],
2365                   1.0f);
2366   }
2367
2368   glClear (GL_COLOR_BUFFER_BIT);
2369
2370   myView->DrawBackground (this);
2371
2372   myView->RedrawLayer2d (myPrintContext, this, theCView, theCUnderLayer);
2373
2374   myGlContext->WorldViewState.Push();
2375   myGlContext->ProjectionState.Push();
2376
2377   myGlContext->WorldViewState.SetIdentity();
2378   myGlContext->ProjectionState.SetIdentity();
2379
2380   myGlContext->ApplyProjectionMatrix();
2381   myGlContext->ApplyWorldViewMatrix();
2382
2383   glEnable (GL_BLEND);
2384   glBlendFunc (GL_ONE, GL_SRC_ALPHA);
2385
2386   // Generate ray-traced image
2387   if (myIsRaytraceDataValid)
2388   {
2389     myRaytraceScreenQuad.Bind (myGlContext);
2390
2391     if (!myRaytraceGeometry.AcquireTextures (myGlContext))
2392     {
2393       const TCollection_ExtendedString aMessage = "Error: Failed to acquire OpenGL image textures";
2394
2395       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2396         GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2397     }
2398
2399     RunRaytraceShaders (theCView,
2400                         theSizeX,
2401                         theSizeY,
2402                         aOrigins,
2403                         aDirects,
2404                         anUnviewMat,
2405                         theFrameBuffer);
2406
2407     if (!myRaytraceGeometry.ReleaseTextures (myGlContext))
2408     {
2409       const TCollection_ExtendedString aMessage = "Error: Failed to release OpenGL image textures";
2410
2411       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2412         GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2413     }
2414
2415     myRaytraceScreenQuad.Unbind (myGlContext);
2416   }
2417
2418   if (!wasBlendingEnabled)
2419     glDisable (GL_BLEND);
2420
2421   if (wasDepthTestEnabled)
2422     glEnable (GL_DEPTH_TEST);
2423
2424   myGlContext->WorldViewState.Pop();
2425   myGlContext->ProjectionState.Pop();
2426
2427   myGlContext->ApplyProjectionMatrix();
2428
2429   // Redraw trihedron
2430   myView->RedrawTrihedron (this);
2431
2432   // Redraw overlay
2433   const int aMode = 0;
2434   DisplayCallback (theCView, (aMode | OCC_PRE_OVERLAY));
2435   myView->RedrawLayer2d (myPrintContext, this, theCView, theCOverLayer);
2436   DisplayCallback (theCView, aMode);
2437   return Standard_True;
2438 }
2439
2440 IMPLEMENT_STANDARD_HANDLE(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2441 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2442
2443 // =======================================================================
2444 // function : CanRender
2445 // purpose  :
2446 // =======================================================================
2447 Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
2448 {
2449   Standard_Boolean aPrevFilterResult = Standard_True;
2450   if (!myPrevRenderFilter.IsNull())
2451   {
2452     aPrevFilterResult = myPrevRenderFilter->CanRender(theElement);
2453   }
2454   return aPrevFilterResult &&
2455          !OpenGl_Raytrace::IsRaytracedElement (theElement);
2456 }