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