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