0025201: Visualization - Implementing soft shadows and ambient occlusion in OCCT...
[occt.git] / src / OpenGl / OpenGl_View.hxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 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 #ifndef _OpenGl_View_Header
17 #define _OpenGl_View_Header
18
19 #include <MMgt_TShared.hxx>
20 #include <Standard_DefineHandle.hxx>
21
22 #include <TColStd_Array2OfReal.hxx>
23 #include <NCollection_List.hxx>
24 #include <math_BullardGenerator.hxx>
25
26 #include <Quantity_NameOfColor.hxx>
27 #include <Aspect_FillMethod.hxx>
28 #include <Aspect_GradientFillMethod.hxx>
29 #include <Aspect_TypeOfTriedronPosition.hxx>
30 #include <Aspect_CLayer2d.hxx>
31
32 #include <InterfaceGraphic_Graphic3d.hxx>
33 #include <InterfaceGraphic_Visual3d.hxx>
34
35 #include <Graphic3d_CView.hxx>
36 #include <Graphic3d_GraduatedTrihedron.hxx>
37 #include <Graphic3d_SequenceOfHClipPlane.hxx>
38 #include <Graphic3d_ZLayerSettings.hxx>
39 #include <Visual3d_TypeOfSurfaceDetail.hxx>
40 #include <Visual3d_TypeOfModel.hxx>
41
42 #include <OpenGl_AspectFace.hxx>
43 #include <OpenGl_BackgroundArray.hxx>
44 #include <OpenGl_BVHTreeSelector.hxx>
45 #include <OpenGl_LayerList.hxx>
46 #include <OpenGl_Light.hxx>
47 #include <OpenGl_LineAttributes.hxx>
48 #include <OpenGl_Trihedron.hxx>
49 #include <OpenGl_GraduatedTrihedron.hxx>
50
51 #include <Handle_OpenGl_Context.hxx>
52 #include <Handle_OpenGl_GraphicDriver.hxx>
53 #include <Handle_OpenGl_Workspace.hxx>
54 #include <Handle_OpenGl_View.hxx>
55 #include <Handle_OpenGl_Texture.hxx>
56
57 struct OPENGL_ZCLIP
58 {
59   struct {
60     Standard_Boolean   IsOn;
61     Standard_ShortReal Limit; /* in the range [0., 1.] */
62   } Back;
63   struct {
64     Standard_Boolean   IsOn;
65     Standard_ShortReal Limit; /* in the range [0., 1.] */
66   } Front;
67 };
68
69 struct OPENGL_FOG
70 {
71   Standard_Boolean   IsOn;
72   Standard_ShortReal Front; /* in the range [0., 1.] */
73   Standard_ShortReal Back; /* in the range [0., 1.] */
74   TEL_COLOUR         Color;
75 };
76
77 struct OpenGl_Matrix;
78 class OpenGl_Structure;
79 class Handle(OpenGl_PrinterContext);
80 class OpenGl_StateCounter;
81
82 class OpenGl_View : public MMgt_TShared
83 {
84  public:
85   OpenGl_View (const CALL_DEF_VIEWCONTEXT &AContext, OpenGl_StateCounter* theCounter);
86   virtual ~OpenGl_View ();
87
88   void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx);
89
90   void SetTextureEnv (const Handle(OpenGl_Context)&       theCtx,
91                       const Handle(Graphic3d_TextureEnv)& theTexture);
92   void SetSurfaceDetail (const Visual3d_TypeOfSurfaceDetail AMode);
93   void SetBackfacing (const Standard_Integer AMode);
94   void SetLights (const CALL_DEF_VIEWCONTEXT &AContext);
95   void SetAntiAliasing (const Standard_Boolean AMode) { myAntiAliasing = AMode; }
96   void SetClipPlanes (const Graphic3d_SequenceOfHClipPlane &thePlanes) { myClipPlanes = thePlanes; }
97   void SetVisualisation (const CALL_DEF_VIEWCONTEXT &AContext);
98
99   const Handle(Graphic3d_Camera)& Camera() { return myCamera; }
100   void SetCamera (const Handle(Graphic3d_Camera)& theCamera) { myCamera = theCamera; }
101
102   void SetClipLimit (const Graphic3d_CView& theCView);
103
104   void SetFog (const Graphic3d_CView& theCView, const Standard_Boolean theFlag);
105
106   OpenGl_Trihedron& ChangeTrihedron() { return myTrihedron; }
107   void TriedronDisplay (const Aspect_TypeOfTriedronPosition thePosition,
108                         const Quantity_NameOfColor          theColor,
109                         const Standard_Real                 theScale,
110                         const Standard_Boolean              theAsWireframe);
111   void TriedronErase (const Handle(OpenGl_Context)& theCtx);
112
113   OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
114   void GraduatedTrihedronDisplay (const Handle(OpenGl_Context)&        theCtx,
115                                   const Graphic3d_GraduatedTrihedron& theCubic);
116   void GraduatedTrihedronErase (const Handle(OpenGl_Context)& theCtx);
117
118   Standard_Real Height () const { return myCamera->ViewDimensions().X(); }
119   Standard_Real Width () const { return myCamera->ViewDimensions().Y(); }
120
121   Standard_Integer Backfacing () const { return myBackfacing; }
122
123   const TEL_TRANSFORM_PERSISTENCE * BeginTransformPersistence (const Handle(OpenGl_Context)& theCtx,
124                                                                const TEL_TRANSFORM_PERSISTENCE *theTransPers,
125                                                                Standard_Integer theWidth,
126                                                                Standard_Integer theHeight);
127   void EndTransformPersistence (const Handle(OpenGl_Context)& theCtx);
128
129   //! Add structure to display list with specified priority.
130   //! The structure will be added to associated with it z layer.
131   //! If the z layer is not presented in the view, the structure will
132   //! be displayed in default bottom-level z layer.
133   void DisplayStructure (const Handle(Graphic3d_Structure)& theStructure,
134                          const Standard_Integer             thePriority);
135
136   //! Erase structure from display list.
137   void EraseStructure (const Handle(Graphic3d_Structure)& theStructure);
138
139   //! Add structure to the list of immediate structures.
140   void DisplayImmediateStructure (const Handle(Graphic3d_Structure)& theStructure);
141
142   //! Erase structure from display list.
143   void EraseImmediateStructure (const OpenGl_Structure* theStructure);
144
145   //! Insert a new top-level z layer with ID <theLayerId>
146   void AddZLayer (const Graphic3d_ZLayerId theLayerId);
147
148   //! Remove a z layer with ID <theLayerId>
149   void RemoveZLayer (const Graphic3d_ZLayerId theLayerId);
150
151   //! Display structure in z layer with ID <theNewLayerId>
152   //! If the layer with ID <theNewLayerId> is not presented in the view,
153   //! the structure will be displayed in default bottom-level layer.
154   void ChangeZLayer (const OpenGl_Structure*  theStructure,
155                      const Graphic3d_ZLayerId theNewLayerId);
156
157   //! Sets the settings for a single Z layer of specified view.
158   void SetZLayerSettings (const Graphic3d_ZLayerId        theLayerId,
159                           const Graphic3d_ZLayerSettings& theSettings);
160
161   //! Changes the priority of a structure within its ZLayer
162   void ChangePriority (const OpenGl_Structure* theStructure,
163                        const Standard_Integer  theNewPriority);
164
165   void CreateBackgroundTexture (const Standard_CString AFileName,
166                                 const Aspect_FillMethod AFillStyle);
167
168   void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
169   void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
170   void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
171
172   void Render (const Handle(OpenGl_PrinterContext)& thePrintContext,
173                const Handle(OpenGl_Workspace)&      theWorkspace,
174                OpenGl_FrameBuffer*                  theReadDrawFbo,
175                Graphic3d_Camera::Projection         theProjection,
176                const Graphic3d_CView&               theCView,
177                const Aspect_CLayer2d&               theCUnderLayer,
178                const Aspect_CLayer2d&               theCOverLayer,
179                const Standard_Boolean               theToDrawImmediate);
180
181
182   void DrawBackground (const Handle(OpenGl_Workspace)& theWorkspace);
183
184   //! Returns list of OpenGL Z-layers.
185   const OpenGl_LayerList& LayerList() const { return myZLayers; }
186
187   //! Returns list of openGL light sources.
188   const OpenGl_ListOfLight& LightList() const { return myLights; }
189
190   //! Returns OpenGL environment map.
191   const Handle(OpenGl_Texture)& TextureEnv() const { return myTextureEnv; }
192
193   //! Returns visualization mode for objects in the view.
194   Visual3d_TypeOfSurfaceDetail SurfaceDetail() const { return mySurfaceDetail; }
195
196   //! Returns selector for BVH tree, providing a possibility to store information
197   //! about current view volume and to detect which objects are overlapping it.
198   OpenGl_BVHTreeSelector& BVHTreeSelector() { return myBVHSelector; }
199
200   //! Marks BVH tree for given priority list as dirty and
201   //! marks primitive set for rebuild.
202   void InvalidateBVHData (const Standard_Integer theLayerId);
203
204   //! Returns list of immediate structures rendered on top of main presentation
205   const OpenGl_IndexedMapOfStructure& ImmediateStructures() const
206   {
207     return myImmediateList;
208   }
209
210   //! Returns true if there are immediate structures to display
211   bool HasImmediateStructures() const
212   {
213     return !myImmediateList.IsEmpty()
214          || myZLayers.NbImmediateStructures() != 0;
215   }
216
217 protected:
218
219   void RenderStructs (const Handle(OpenGl_Workspace)& theWorkspace,
220                       OpenGl_FrameBuffer*             theReadDrawFbo,
221                       const Graphic3d_CView&          theCView,
222                       const Standard_Boolean          theToDrawImmediate);
223
224   void RedrawLayer2d (const Handle(OpenGl_PrinterContext)& thePrintContext,
225                       const Handle(OpenGl_Workspace)&      theWorkspace,
226                       const Graphic3d_CView&               theCView,
227                       const Aspect_CLayer2d&               theCLayer);
228
229   void RedrawTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
230
231   //! Redraw contents of model scene: clipping planes,
232   //! lights, structures. The peculiar properties of "scene" is that
233   //! it requires empty Z-Buffer and uses projection and orientation
234   //! matrices supplied by 3d view.
235   void RedrawScene (const Handle(OpenGl_PrinterContext)& thePrintContext,
236                     const Handle(OpenGl_Workspace)&      theWorkspace,
237                     OpenGl_FrameBuffer*                  theReadDrawFbo,
238                     const Graphic3d_CView&               theCView,
239                     const Standard_Boolean               theToDrawImmediate);
240
241   Handle(OpenGl_LineAttributes) myLineAttribs;
242   Handle(OpenGl_Texture)        myTextureEnv;
243   Visual3d_TypeOfSurfaceDetail  mySurfaceDetail;
244   Standard_Integer              myBackfacing;
245
246   OPENGL_ZCLIP   myZClip;
247
248   Graphic3d_SequenceOfHClipPlane myClipPlanes;
249   
250   Handle(Graphic3d_Camera) myCamera;
251
252   OPENGL_FOG myFog;
253   OpenGl_Trihedron           myTrihedron;
254   OpenGl_GraduatedTrihedron  myGraduatedTrihedron;
255   bool                       myToShowTrihedron;
256   bool                       myToShowGradTrihedron;
257
258   //View_LABViewContext
259   int myVisualization;
260   Visual3d_TypeOfModel       myShadingModel;  //!< lighting shading model
261
262   //View_LABLight
263   OpenGl_ListOfLight myLights;
264
265   //View_LABPlane
266   //View_LABAliasing
267   Standard_Boolean myAntiAliasing;
268
269   //View_LABDepthCueing - fixed index used
270
271   OpenGl_LayerList             myZLayers;       //!< main list of displayed structure, sorted by layers
272   OpenGl_IndexedMapOfStructure myImmediateList; //!< list of immediate structures rendered on top of main presentation
273
274   const TEL_TRANSFORM_PERSISTENCE *myTransPers;
275   Standard_Boolean myIsTransPers;
276
277   //! Modification state
278   Standard_Size myProjectionState;
279   Standard_Size myModelViewState;
280   OpenGl_StateCounter* myStateCounter;
281
282   Standard_Size myCurrLightSourceState;
283
284   typedef std::pair<Standard_Size, Standard_Size> StateInfo;
285
286   StateInfo myLastOrientationState;
287   StateInfo myLastViewMappingState;
288   StateInfo myLastLightSourceState;
289
290   //! Is needed for selection of overlapping objects and storage of the current view volume
291   OpenGl_BVHTreeSelector myBVHSelector;
292
293 protected: //! @name Background parameters
294
295   OpenGl_AspectFace*      myTextureParams;   //!< Stores texture and its parameters for textured background
296   OpenGl_BackgroundArray* myBgGradientArray; //!< Primitive array for gradient background
297   OpenGl_BackgroundArray* myBgTextureArray;  //!< Primitive array for texture  background
298
299 protected: //! @name data types related to ray-tracing
300
301   //! Result of OpenGL shaders initialization.
302   enum RaytraceInitStatus
303   {
304     OpenGl_RT_NONE,
305     OpenGl_RT_INIT,
306     OpenGl_RT_FAIL
307   };
308
309   //! Describes update mode (state).
310   enum RaytraceUpdateMode
311   {
312     OpenGl_GUM_CHECK,   //!< check geometry state
313     OpenGl_GUM_PREPARE, //!< collect unchanged objects
314     OpenGl_GUM_REBUILD  //!< rebuild changed and new objects
315   };
316
317   //! Defines frequently used shader variables.
318   enum ShaderVariableIndex
319   {
320     OpenGl_RT_aPosition,
321
322     // camera position
323     OpenGl_RT_uOriginLT,
324     OpenGl_RT_uOriginLB,
325     OpenGl_RT_uOriginRT,
326     OpenGl_RT_uOriginRB,
327     OpenGl_RT_uDirectLT,
328     OpenGl_RT_uDirectLB,
329     OpenGl_RT_uDirectRT,
330     OpenGl_RT_uDirectRB,
331     OpenGl_RT_uUnviewMat,
332
333     // 3D scene params
334     OpenGl_RT_uSceneRad,
335     OpenGl_RT_uSceneEps,
336     OpenGl_RT_uLightAmbnt,
337     OpenGl_RT_uLightCount,
338
339     // background params
340     OpenGl_RT_uBackColorTop,
341     OpenGl_RT_uBackColorBot,
342
343     // ray-tracing params
344     OpenGl_RT_uShadowsEnabled,
345     OpenGl_RT_uReflectEnabled,
346     OpenGl_RT_uSphereMapEnabled,
347     OpenGl_RT_uSphereMapForBack,
348     OpenGl_RT_uTexSamplersArray,
349
350     // sampled frame params
351     OpenGl_RT_uSampleWeight,
352     OpenGl_RT_uFrameRndSeed,
353
354     // adaptive FSAA params
355     OpenGl_RT_uOffsetX,
356     OpenGl_RT_uOffsetY,
357     OpenGl_RT_uSamples,
358
359     OpenGl_RT_NbVariables // special field
360   };
361
362   //! Defines texture samplers.
363   enum ShaderSamplerNames
364   {
365     OpenGl_RT_SceneNodeInfoTexture  = 0,
366     OpenGl_RT_SceneMinPointTexture  = 1,
367     OpenGl_RT_SceneMaxPointTexture  = 2,
368     OpenGl_RT_SceneTransformTexture = 3,
369
370     OpenGl_RT_GeometryVertexTexture = 4,
371     OpenGl_RT_GeometryNormalTexture = 5,
372     OpenGl_RT_GeometryTexCrdTexture = 6,
373     OpenGl_RT_GeometryTriangTexture = 7,
374
375     OpenGl_RT_EnvironmentMapTexture = 8,
376
377     OpenGl_RT_RaytraceMaterialTexture = 9,
378     OpenGl_RT_RaytraceLightSrcTexture = 10,
379
380     OpenGl_RT_FsaaInputTexture = 11,
381     OpenGl_RT_PrevAccumTexture = 12,
382
383     OpenGl_RT_OpenGlColorTexture = 13,
384     OpenGl_RT_OpenGlDepthTexture = 14
385   };
386
387   //! Tool class for management of shader sources.
388   class ShaderSource
389   {
390   public:
391
392     //! Default shader prefix - empty string.
393     static const TCollection_AsciiString EMPTY_PREFIX;
394
395     //! Creates new uninitialized shader source.
396     ShaderSource()
397     {
398       //
399     }
400
401     //! Creates new shader source from specified file.
402     ShaderSource (const TCollection_AsciiString& theFileName, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX)
403     {
404       TCollection_AsciiString aFileNames[] = { theFileName, "" };
405
406       Load (aFileNames, thePrefix);
407     }
408
409   public:
410
411     //! Returns prefix to insert before the source.
412     const TCollection_AsciiString& Prefix() const
413     {
414       return myPrefix;
415     }
416
417     //! Sets prefix to insert before the source.
418     void SetPrefix (const TCollection_AsciiString& thePrefix)
419     {
420       myPrefix = thePrefix;
421     }
422
423     //! Returns shader source combined with prefix.
424     TCollection_AsciiString Source() const;
425
426     //! Loads shader source from specified files.
427     void Load (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
428
429   private:
430
431     TCollection_AsciiString mySource; //!< Source string of the shader object
432     TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
433
434   };
435
436   //! Default ray-tracing depth.
437   static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
438
439   //! Default size of traversal stack.
440   static const Standard_Integer THE_DEFAULT_STACK_SIZE = 24;
441
442   //! Compile-time ray-tracing parameters.
443   struct RaytracingParams
444   {
445     //! Actual size of traversal stack in shader program.
446     Standard_Integer StackSize;
447
448     //! Actual ray-tracing depth (number of ray bounces).
449     Standard_Integer NbBounces;
450
451     //! Enables/disables light propagation through transparent media.
452     Standard_Boolean TransparentShadows;
453
454     //! Enables/disables global illumination (GI) effects.
455     Standard_Boolean GlobalIllumination;
456
457     //! Enables/disables the use of OpenGL bindless textures.
458     Standard_Boolean UseBindlessTextures;
459
460     //! Creates default compile-time ray-tracing parameters.
461     RaytracingParams()
462     : StackSize (THE_DEFAULT_STACK_SIZE),
463       NbBounces (THE_DEFAULT_NB_BOUNCES),
464       TransparentShadows (Standard_False),
465       GlobalIllumination  (Standard_False),
466       UseBindlessTextures (Standard_False)
467     {
468       //
469     }
470   };
471
472   //! Describes state of OpenGL structure.
473   struct StructState
474   {
475     Standard_Size StructureState;
476     Standard_Size InstancedState;
477
478     //! Creates new structure state.
479     StructState (const Standard_Size theStructureState = 0,
480                  const Standard_Size theInstancedState = 0)
481     : StructureState (theStructureState),
482       InstancedState (theInstancedState)
483     {
484       //
485     }
486
487     //! Creates new structure state.
488     StructState (const OpenGl_Structure* theStructure)
489     {
490       StructureState = theStructure->ModificationState();
491
492       InstancedState = theStructure->InstancedStructure() != NULL ?
493         theStructure->InstancedStructure()->ModificationState() : 0;
494     }
495   };
496
497 protected: //! @name methods related to ray-tracing
498
499   //! Updates 3D scene geometry for ray-tracing.
500   Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode      theMode,
501                                            const Standard_Integer        theViewId,
502                                            const Handle(OpenGl_Context)& theGlContext);
503
504   //! Updates 3D scene light sources for ray-tracing.
505   Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
506
507   //! Updates environment map for ray-tracing.
508   Standard_Boolean updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext);
509
510   //! Checks to see if the OpenGL structure is modified.
511   Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
512
513   //! Adds OpenGL structure to ray-traced scene geometry.
514   Standard_Boolean addRaytraceStructure (const OpenGl_Structure*       theStructure,
515                                          const Handle(OpenGl_Context)& theGlContext);
516
517   //! Adds OpenGL groups to ray-traced scene geometry.
518   Standard_Boolean addRaytraceGroups (const OpenGl_Structure*       theStructure,
519                                       const Standard_Integer        theStructMat,
520                                       const Standard_ShortReal*     theTransform,
521                                       const Handle(OpenGl_Context)& theGlContext);
522
523   //! Creates ray-tracing material properties.
524   OpenGl_RaytraceMaterial convertMaterial (const OpenGl_AspectFace*      theAspect,
525                                            const Handle(OpenGl_Context)& theGlContext);
526
527   //! Adds OpenGL primitive array to ray-traced scene geometry.
528   OpenGl_TriangleSet* addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
529                                                  const Standard_Integer       theMatID,
530                                                  const OpenGl_Mat4*           theTrans);
531
532   //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
533   Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet&                  theSet,
534                                              const Standard_Integer               theMatID,
535                                              const Standard_Integer               theCount,
536                                              const Standard_Integer               theOffset,
537                                              const OpenGl_PrimitiveArray&         theArray);
538
539   //! Adds OpenGL triangle array to ray-traced scene geometry.
540   Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
541                                              const Standard_Integer               theMatID,
542                                              const Standard_Integer               theCount,
543                                              const Standard_Integer               theOffset,
544                                              const Handle(Graphic3d_IndexBuffer)& theIndices);
545
546   //! Adds OpenGL triangle fan array to ray-traced scene geometry.
547   Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
548                                                 const Standard_Integer               theMatID,
549                                                 const Standard_Integer               theCount,
550                                                 const Standard_Integer               theOffset,
551                                                 const Handle(Graphic3d_IndexBuffer)& theIndices);
552
553   //! Adds OpenGL triangle strip array to ray-traced scene geometry.
554   Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
555                                                   const Standard_Integer               theMatID,
556                                                   const Standard_Integer               theCount,
557                                                   const Standard_Integer               theOffset,
558                                                   const Handle(Graphic3d_IndexBuffer)& theIndices);
559
560   //! Adds OpenGL quadrangle array to ray-traced scene geometry.
561   Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
562                                                const Standard_Integer               theMatID,
563                                                const Standard_Integer               theCount,
564                                                const Standard_Integer               theOffset,
565                                                const Handle(Graphic3d_IndexBuffer)& theIndices);
566
567   //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
568   Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
569                                                     const Standard_Integer               theMatID,
570                                                     const Standard_Integer               theCount,
571                                                     const Standard_Integer               theOffset,
572                                                     const Handle(Graphic3d_IndexBuffer)& theIndices);
573
574   //! Adds OpenGL polygon array to ray-traced scene geometry.
575   Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
576                                             const Standard_Integer               theMatID,
577                                             const Standard_Integer               theCount,
578                                             const Standard_Integer               theOffset,
579                                             const Handle(Graphic3d_IndexBuffer)& theIndices);
580
581   //! Uploads ray-trace data to the GPU.
582   Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
583
584   //! Generates shader prefix based on current ray-tracing options.
585   TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
586
587   //! Performs safe exit when shaders initialization fails.
588   Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
589                                  const Handle(OpenGl_Context)&     theGlContext);
590
591   //! Loads and compiles shader object from specified source.
592   Handle(OpenGl_ShaderObject) initShader (const GLenum                  theType,
593                                           const ShaderSource&           theSource,
594                                           const Handle(OpenGl_Context)& theGlContext);
595
596   //! Creates shader program from the given vertex and fragment shaders.
597   Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)&      theGlContext,
598                                             const Handle(OpenGl_ShaderObject)& theVertShader,
599                                             const Handle(OpenGl_ShaderObject)& theFragShader);
600
601   //! Initializes OpenGL/GLSL shader programs.
602   Standard_Boolean initRaytraceResources (const Graphic3d_CView&        theCView,
603                                           const Handle(OpenGl_Context)& theGlContext);
604
605   //! Releases OpenGL/GLSL shader programs.
606   void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
607
608   //! Resizes OpenGL frame buffers.
609   Standard_Boolean resizeRaytraceBuffers (const Standard_Integer        theSizeX,
610                                           const Standard_Integer        theSizeY,
611                                           const Handle(OpenGl_Context)& theGlContext);
612
613   //! Generates viewing rays for corners of screen quad.
614   void updateCamera (const OpenGl_Mat4& theOrientation,
615                      const OpenGl_Mat4& theViewMapping,
616                      OpenGl_Vec3*       theOrigins,
617                      OpenGl_Vec3*       theDirects,
618                      OpenGl_Mat4&       theUnView);
619
620   //! Binds ray-trace textures to corresponding texture units.
621   void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
622
623   //! Unbinds ray-trace textures from corresponding texture unit.
624   void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
625
626   //! Sets uniform state for the given ray-tracing shader program.
627   Standard_Boolean setUniformState (const Graphic3d_CView&        theCView,
628                                     const OpenGl_Vec3*            theOrigins,
629                                     const OpenGl_Vec3*            theDirects,
630                                     const OpenGl_Mat4&            theUnviewMat,
631                                     const Standard_Integer        theProgramId,
632                                     const Handle(OpenGl_Context)& theGlContext);
633
634   //! Runs ray-tracing shader programs.
635   Standard_Boolean runRaytraceShaders (const Graphic3d_CView&        theCView,
636                                        const Standard_Integer        theSizeX,
637                                        const Standard_Integer        theSizeY,
638                                        const OpenGl_Vec3*            theOrigins,
639                                        const OpenGl_Vec3*            theDirects,
640                                        const OpenGl_Mat4&            theUnviewMat,
641                                        OpenGl_FrameBuffer*           theReadDrawFbo,
642                                        const Handle(OpenGl_Context)& theGlContext);
643
644   //! Redraws the window using OpenGL/GLSL ray-tracing.
645   Standard_Boolean raytrace (const Graphic3d_CView&        theCView,
646                              const Standard_Integer        theSizeX,
647                              const Standard_Integer        theSizeY,
648                              OpenGl_FrameBuffer*           theReadDrawFbo,
649                              const Handle(OpenGl_Context)& theGlContext);
650
651 protected: //! @name fields related to ray-tracing
652
653   //! Result of shaders initialization.
654   RaytraceInitStatus myRaytraceInitStatus;
655
656   //! Is geometry data valid?
657   Standard_Boolean myIsRaytraceDataValid;
658
659   //! Warning about missing extension GL_ARB_bindless_texture has been displayed?
660   Standard_Boolean myIsRaytraceWarnTextures;
661
662   //! 3D scene geometry data for ray-tracing.
663   OpenGl_RaytraceGeometry myRaytraceGeometry;
664
665   //! Compile-time ray-tracing parameters.
666   RaytracingParams myRaytraceParameters;
667
668   //! Radius of bounding sphere of the scene.
669   Standard_ShortReal myRaytraceSceneRadius;
670   //! Scene epsilon to prevent self-intersections.
671   Standard_ShortReal myRaytraceSceneEpsilon;
672
673   //! OpenGL/GLSL source of ray-tracing fragment shader.
674   ShaderSource myRaytraceShaderSource;
675   //! OpenGL/GLSL source of adaptive-AA fragment shader.
676   ShaderSource myPostFSAAShaderSource;
677
678   //! OpenGL/GLSL ray-tracing fragment shader.
679   Handle(OpenGl_ShaderObject) myRaytraceShader;
680   //! OpenGL/GLSL adaptive-AA fragment shader.
681   Handle(OpenGl_ShaderObject) myPostFSAAShader;
682
683   //! OpenGL/GLSL ray-tracing shader program.
684   Handle(OpenGl_ShaderProgram) myRaytraceProgram;
685   //! OpenGL/GLSL adaptive-AA shader program.
686   Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
687   //! OpenGL/GLSL program for displaying texture.
688   Handle(OpenGl_ShaderProgram) myOutImageProgram;
689
690   //! Texture buffer of data records of bottom-level BVH nodes.
691   Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
692   //! Texture buffer of minimum points of bottom-level BVH nodes.
693   Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
694   //! Texture buffer of maximum points of bottom-level BVH nodes.
695   Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
696   //! Texture buffer of transformations of high-level BVH nodes.
697   Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
698
699   //! Texture buffer of vertex coords.
700   Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
701   //! Texture buffer of vertex normals.
702   Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
703   //! Texture buffer of vertex UV coords.
704   Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
705   //! Texture buffer of triangle indices.
706   Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
707
708   //! Texture buffer of material properties.
709   Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
710   //! Texture buffer of light source properties.
711   Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
712
713   //! 1st framebuffer (FBO) to perform adaptive FSAA.
714   Handle(OpenGl_FrameBuffer) myRaytraceFBO1;
715   //! 2nd framebuffer (FBO) to perform adaptive FSAA.
716   Handle(OpenGl_FrameBuffer) myRaytraceFBO2;
717   //! Framebuffer (FBO) for preliminary OpenGL output.
718   Handle(OpenGl_FrameBuffer) myOpenGlFBO;
719
720   //! Vertex buffer (VBO) for drawing dummy quad.
721   OpenGl_VertexBuffer myRaytraceScreenQuad;
722
723   //! Cached locations of frequently used uniform variables.
724   Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
725
726   //! State of OpenGL structures reflected to ray-tracing.
727   std::map<const OpenGl_Structure*, StructState> myStructureStates;
728
729   //! PrimitiveArray to TriangleSet map for scene partial update.
730   std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
731
732   //! Set of IDs of non-raytracable elements (to detect updates).
733   std::set<Standard_Integer> myNonRaytraceStructureIDs;
734
735   //! Render filter to filter out all raytracable structures.
736   Handle(OpenGl_RaytraceFilter) myRaytraceFilter;
737
738   //! Marks if environment map should be updated.
739   Standard_Boolean myToUpdateEnvironmentMap;
740
741   //! State of OpenGL layer list.
742   Standard_Size myLayerListState;
743
744   //! Number of accumulated frames (for progressive rendering).
745   Standard_Integer myAccumFrames;
746
747   //! Stored ray origins used for detection of camera movements.
748   OpenGl_Vec3 myPreviousOrigins[3];
749
750   //! Bullard RNG to produce random sequence.
751   math_BullardGenerator myRNG;
752
753 public:
754
755   DEFINE_STANDARD_ALLOC
756   DEFINE_STANDARD_RTTI(OpenGl_View) // Type definition
757
758   friend class OpenGl_Workspace;
759
760 };
761
762 #endif // _OpenGl_View_Header