0031683: Visualization - V3d_View::SetBackgroundImage() should accept Image_PixMap
[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 <Standard_Transient.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
30 #include <Graphic3d_CView.hxx>
31 #include <Graphic3d_CullingTool.hxx>
32 #include <Graphic3d_GraduatedTrihedron.hxx>
33 #include <Graphic3d_SequenceOfHClipPlane.hxx>
34 #include <Graphic3d_ToneMappingMethod.hxx>
35 #include <Graphic3d_TypeOfShadingModel.hxx>
36 #include <Graphic3d_WorldViewProjState.hxx>
37 #include <Graphic3d_ZLayerSettings.hxx>
38
39 #include <OpenGl_Aspects.hxx>
40 #include <OpenGl_BackgroundArray.hxx>
41 #include <OpenGl_Context.hxx>
42 #include <OpenGl_FrameBuffer.hxx>
43 #include <OpenGl_FrameStatsPrs.hxx>
44 #include <OpenGl_GraduatedTrihedron.hxx>
45 #include <OpenGl_LayerList.hxx>
46 #include <OpenGl_LineAttributes.hxx>
47 #include <OpenGl_SceneGeometry.hxx>
48 #include <OpenGl_Structure.hxx>
49 #include <OpenGl_Window.hxx>
50 #include <OpenGl_Workspace.hxx>
51 #include <OpenGl_TileSampler.hxx>
52
53 #include <map>
54 #include <set>
55
56 struct OpenGl_Matrix;
57
58 class Graphic3d_StructureManager;
59 class OpenGl_GraphicDriver;
60 class OpenGl_PBREnvironment;
61 class OpenGl_StateCounter;
62 class OpenGl_TriangleSet;
63 class OpenGl_Workspace;
64 class OpenGl_View;
65 DEFINE_STANDARD_HANDLE(OpenGl_View,Graphic3d_CView)
66
67 //! Implementation of OpenGl view.
68 class OpenGl_View : public Graphic3d_CView
69 {
70
71 public:
72
73   //! Constructor.
74   Standard_EXPORT OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
75                                const Handle(OpenGl_GraphicDriver)& theDriver,
76                                const Handle(OpenGl_Caps)& theCaps,
77                                OpenGl_StateCounter* theCounter);
78
79   //! Default destructor.
80   Standard_EXPORT virtual ~OpenGl_View();
81
82   //! Release OpenGL resources.
83   Standard_EXPORT void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx);
84
85   //! Deletes and erases the view.
86   Standard_EXPORT virtual void Remove() Standard_OVERRIDE;
87
88   //! @param theDrawToFrontBuffer Advanced option to modify rendering mode:
89   //! 1. TRUE.  Drawing immediate mode structures directly to the front buffer over the scene image.
90   //! Fast, so preferred for interactive work (used by default).
91   //! However these extra drawings will be missed in image dump since it is performed from back buffer.
92   //! Notice that since no pre-buffering used the V-Sync will be ignored and rendering could be seen
93   //! in run-time (in case of slow hardware) and/or tearing may appear.
94   //! So this is strongly recommended to draw only simple (fast) structures.
95   //! 2. FALSE. Drawing immediate mode structures to the back buffer.
96   //! The complete scene is redrawn first, so this mode is slower if scene contains complex data and/or V-Sync
97   //! is turned on. But it works in any case and is especially useful for view dump because the dump image is read
98   //! from the back buffer.
99   //! @return previous mode.
100   Standard_EXPORT Standard_Boolean SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer) Standard_OVERRIDE;
101
102   //! Creates and maps rendering window to the view.
103   //! @param theWindow [in] the window.
104   //! @param theContext [in] the rendering context. If NULL the context will be created internally.
105   Standard_EXPORT virtual void SetWindow (const Handle(Aspect_Window)&  theWindow,
106                                           const Aspect_RenderingContext theContext) Standard_OVERRIDE;
107
108   //! Returns window associated with the view.
109   virtual Handle(Aspect_Window) Window() const Standard_OVERRIDE
110   { return myWindow->PlatformWindow(); }
111
112   //! Returns True if the window associated to the view is defined.
113   virtual Standard_Boolean IsDefined() const Standard_OVERRIDE
114   { return !myWindow.IsNull(); }
115
116   //! Handle changing size of the rendering window.
117   Standard_EXPORT virtual void Resized() Standard_OVERRIDE;
118
119   //! Redraw content of the view.
120   Standard_EXPORT virtual void Redraw() Standard_OVERRIDE;
121
122   //! Redraw immediate content of the view.
123   Standard_EXPORT virtual void RedrawImmediate() Standard_OVERRIDE;
124
125   //! Marks BVH tree for given priority list as dirty and marks primitive set for rebuild.
126   Standard_EXPORT virtual void Invalidate() Standard_OVERRIDE;
127
128   //! Return true if view content cache has been invalidated.
129   virtual Standard_Boolean IsInvalidated() Standard_OVERRIDE { return !myBackBufferRestored; }
130
131   //! Dump active rendering buffer into specified memory buffer.
132   //! In Ray-Tracing allow to get a raw HDR buffer using Graphic3d_BT_RGB_RayTraceHdrLeft buffer type,
133   //! only Left view will be dumped ignoring stereoscopic parameter.
134   Standard_EXPORT virtual Standard_Boolean BufferDump (Image_PixMap& theImage,
135                                                        const Graphic3d_BufferType& theBufferType) Standard_OVERRIDE;
136
137   //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated.
138   Standard_EXPORT virtual void InvalidateBVHData (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
139
140   //! Add a layer to the view.
141   //! @param theNewLayerId [in] id of new layer, should be > 0 (negative values are reserved for default layers).
142   //! @param theSettings   [in] new layer settings
143   //! @param theLayerAfter [in] id of layer to append new layer before
144   Standard_EXPORT virtual void InsertLayerBefore (const Graphic3d_ZLayerId theLayerId,
145                                                   const Graphic3d_ZLayerSettings& theSettings,
146                                                   const Graphic3d_ZLayerId theLayerAfter) Standard_OVERRIDE;
147
148   //! Add a layer to the view.
149   //! @param theNewLayerId  [in] id of new layer, should be > 0 (negative values are reserved for default layers).
150   //! @param theSettings    [in] new layer settings
151   //! @param theLayerBefore [in] id of layer to append new layer after
152   Standard_EXPORT virtual void InsertLayerAfter (const Graphic3d_ZLayerId theNewLayerId,
153                                                  const Graphic3d_ZLayerSettings& theSettings,
154                                                  const Graphic3d_ZLayerId theLayerBefore) Standard_OVERRIDE;
155
156   //! Remove a z layer with the given ID.
157   Standard_EXPORT virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
158
159   //! Sets the settings for a single Z layer of specified view.
160   Standard_EXPORT virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
161                                                   const Graphic3d_ZLayerSettings& theSettings) Standard_OVERRIDE;
162
163   //! Returns the maximum Z layer ID.
164   //! First layer ID is Graphic3d_ZLayerId_Default, last ID is ZLayerMax().
165   Standard_EXPORT virtual Standard_Integer ZLayerMax() const Standard_OVERRIDE;
166
167   //! Returns the list of layers.
168   Standard_EXPORT virtual const NCollection_List<Handle(Graphic3d_Layer)>& Layers() const Standard_OVERRIDE;
169
170   //! Returns layer with given ID or NULL if undefined.
171   Standard_EXPORT virtual Handle(Graphic3d_Layer) Layer (const Graphic3d_ZLayerId theLayerId) const Standard_OVERRIDE;
172
173   //! Returns the bounding box of all structures displayed in the view.
174   //! If theToIncludeAuxiliary is TRUE, then the boundary box also includes minimum and maximum limits
175   //! of graphical elements forming parts of infinite and other auxiliary structures.
176   //! @param theToIncludeAuxiliary consider also auxiliary presentations (with infinite flag or with trihedron transformation persistence)
177   //! @return computed bounding box
178   Standard_EXPORT virtual Bnd_Box MinMaxValues (const Standard_Boolean theToIncludeAuxiliary) const Standard_OVERRIDE;
179
180   //! Returns pointer to an assigned framebuffer object.
181   Standard_EXPORT virtual Handle(Standard_Transient) FBO() const Standard_OVERRIDE;
182
183   //! Sets framebuffer object for offscreen rendering.
184   Standard_EXPORT virtual void SetFBO (const Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
185
186   //! Generate offscreen FBO in the graphic library.
187   //! If not supported on hardware returns NULL.
188   Standard_EXPORT virtual Handle(Standard_Transient) FBOCreate (const Standard_Integer theWidth,
189                                                                 const Standard_Integer theHeight) Standard_OVERRIDE;
190
191   //! Remove offscreen FBO from the graphic library
192   Standard_EXPORT virtual void FBORelease (Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
193
194   //! Read offscreen FBO configuration.
195   Standard_EXPORT virtual void FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
196                                                  Standard_Integer& theWidth,
197                                                  Standard_Integer& theHeight,
198                                                  Standard_Integer& theWidthMax,
199                                                  Standard_Integer& theHeightMax) Standard_OVERRIDE;
200
201   //! Change offscreen FBO viewport.
202   Standard_EXPORT virtual void FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
203                                                   const Standard_Integer theWidth,
204                                                   const Standard_Integer theHeight) Standard_OVERRIDE;
205
206 public:
207
208   //! Returns gradient background fill colors.
209   Standard_EXPORT virtual Aspect_GradientBackground GradientBackground() const Standard_OVERRIDE;
210
211   //! Sets gradient background fill colors.
212   Standard_EXPORT virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) Standard_OVERRIDE;
213
214   //! Returns background image texture map.
215   virtual Handle(Graphic3d_TextureMap) BackgroundImage() Standard_OVERRIDE { return myBackgroundImage; }
216
217   //! Sets image texture or environment cubemap as backround.
218   //! @param theTextureMap [in] source to set a background;
219   //!                           should be either Graphic3d_Texture2D or Graphic3d_CubeMap
220   //! @param theToUpdatePBREnv [in] defines whether IBL maps will be generated or not
221   //!                               (see GeneratePBREnvironment())
222   Standard_EXPORT virtual void SetBackgroundImage (const Handle(Graphic3d_TextureMap)& theTextureMap,
223                                                    Standard_Boolean theToUpdatePBREnv = Standard_True) Standard_OVERRIDE;
224
225   //! Returns background image fill style.
226   Standard_EXPORT virtual Aspect_FillMethod BackgroundImageStyle() const Standard_OVERRIDE;
227
228   //! Sets background image fill style.
229   Standard_EXPORT virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) Standard_OVERRIDE;
230
231   //! Returns cubemap being set last time on background.
232   Standard_EXPORT Handle(Graphic3d_CubeMap) BackgroundCubeMap() const Standard_OVERRIDE;
233
234   //! Generates PBR specular probe and irradiance map
235   //! in order to provide environment indirect illumination in PBR shading model (Image Based Lighting).
236   //! The source of environment data is background cubemap.
237   //! If PBR is unavailable it does nothing.
238   //! If PBR is available but there is no cubemap being set to background it clears all IBL maps (see 'ClearPBREnvironment').
239   virtual void GeneratePBREnvironment() Standard_OVERRIDE { myPBREnvRequest = OpenGl_PBREnvRequest_BAKE; }
240
241   //! Fills PBR specular probe and irradiance map with white color.
242   //! So that environment indirect illumination will be constant
243   //! and will be fully controlled by ambient light sources.
244   //! If PBR is unavailable it does nothing.
245   virtual void ClearPBREnvironment() Standard_OVERRIDE { myPBREnvRequest = OpenGl_PBREnvRequest_CLEAR; }
246
247   //! Returns number of mipmap levels used in specular IBL map.
248   //! 0 if PBR environment is not created.
249   Standard_EXPORT unsigned int SpecIBLMapLevels() const;
250
251   //! Returns environment texture set for the view.
252   virtual Handle(Graphic3d_TextureEnv) TextureEnv() const Standard_OVERRIDE { return myTextureEnvData; }
253
254   //! Sets environment texture for the view.
255   Standard_EXPORT virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) Standard_OVERRIDE;
256
257   //! Return backfacing model used for the view.
258   virtual Graphic3d_TypeOfBackfacingModel BackfacingModel() const Standard_OVERRIDE { return myBackfacing; }
259
260   //! Sets backfacing model for the view.
261   virtual void SetBackfacingModel (const Graphic3d_TypeOfBackfacingModel theModel) Standard_OVERRIDE { myBackfacing = theModel; }
262
263   //! Returns local camera origin currently set for rendering, might be modified during rendering.
264   const gp_XYZ& LocalOrigin() const { return myLocalOrigin; }
265
266   //! Setup local camera origin currently set for rendering.
267   Standard_EXPORT void SetLocalOrigin (const gp_XYZ& theOrigin);
268
269   //! Returns list of lights of the view.
270   virtual const Handle(Graphic3d_LightSet)& Lights() const Standard_OVERRIDE { return myLights; }
271
272   //! Sets list of lights for the view.
273   virtual void SetLights (const Handle(Graphic3d_LightSet)& theLights) Standard_OVERRIDE
274   {
275     myLights = theLights;
276     myCurrLightSourceState = myStateCounter->Increment();
277   }
278
279   //! Returns list of clip planes set for the view.
280   virtual const Handle(Graphic3d_SequenceOfHClipPlane)& ClipPlanes() const Standard_OVERRIDE { return myClipPlanes; }
281
282   //! Sets list of clip planes for the view.
283   virtual void SetClipPlanes (const Handle(Graphic3d_SequenceOfHClipPlane)& thePlanes) Standard_OVERRIDE { myClipPlanes = thePlanes; }
284
285   //! Fill in the dictionary with diagnostic info.
286   //! Should be called within rendering thread.
287   //!
288   //! This API should be used only for user output or for creating automated reports.
289   //! The format of returned information (e.g. key-value layout)
290   //! is NOT part of this API and can be changed at any time.
291   //! Thus application should not parse returned information to weed out specific parameters.
292   Standard_EXPORT virtual void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
293                                                       Graphic3d_DiagnosticInfo theFlags) const Standard_OVERRIDE;
294
295   //! Returns string with statistic performance info.
296   Standard_EXPORT virtual TCollection_AsciiString StatisticInformation() const Standard_OVERRIDE;
297
298   //! Fills in the dictionary with statistic performance info.
299   Standard_EXPORT virtual void StatisticInformation (TColStd_IndexedDataMapOfStringString& theDict) const Standard_OVERRIDE;
300
301 public:
302
303   //! Returns background color.
304   const Quantity_ColorRGBA& BackgroundColor() const { return myBgColor; }
305
306   //! Change graduated trihedron.
307   OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
308
309   void SetTextureEnv (const Handle(OpenGl_Context)&       theCtx,
310                       const Handle(Graphic3d_TextureEnv)& theTexture);
311
312   void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
313
314   void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
315
316   void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
317
318   //! Returns list of OpenGL Z-layers.
319   const OpenGl_LayerList& LayerList() const { return myZLayers; }
320
321   //! Returns OpenGL window implementation.
322   const Handle(OpenGl_Window)& GlWindow() const { return myWindow; }
323
324   //! Returns OpenGL environment map.
325   const Handle(OpenGl_TextureSet)& GlTextureEnv() const { return myTextureEnv; }
326
327   //! Returns selector for BVH tree, providing a possibility to store information
328   //! about current view volume and to detect which objects are overlapping it.
329   const Graphic3d_CullingTool& BVHTreeSelector() const { return myBVHSelector; }
330
331   //! Returns true if there are immediate structures to display
332   bool HasImmediateStructures() const
333   {
334     return myZLayers.NbImmediateStructures() != 0;
335   }
336
337 public: //! @name obsolete Graduated Trihedron functionality
338
339   //! Displays Graduated Trihedron.
340   Standard_EXPORT virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) Standard_OVERRIDE;
341
342   //! Erases Graduated Trihedron.
343   Standard_EXPORT virtual void GraduatedTrihedronErase() Standard_OVERRIDE;
344
345   //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object.
346   //! @param theMin [in] the minimum point of scene.
347   //! @param theMax [in] the maximum point of scene.
348   Standard_EXPORT virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) Standard_OVERRIDE;
349
350 protected: //! @name Internal methods for managing GL resources
351
352   //! Initializes OpenGl resource for environment texture.
353   void initTextureEnv (const Handle(OpenGl_Context)& theContext);
354
355 protected: //! @name low-level redrawing sub-routines
356
357   //! Redraws view for the given monographic camera projection, or left/right eye.
358   Standard_EXPORT virtual void redraw (const Graphic3d_Camera::Projection theProjection,
359                                        OpenGl_FrameBuffer*                theReadDrawFbo,
360                                        OpenGl_FrameBuffer*                theOitAccumFbo);
361
362   //! Redraws view for the given monographic camera projection, or left/right eye.
363   //!
364   //! Method will blit snapshot containing main scene (myMainSceneFbos or BackBuffer)
365   //! into presentation buffer (myMainSceneFbos -> offscreen FBO or
366   //! myMainSceneFbos -> BackBuffer or BackBuffer -> FrontBuffer),
367   //! and redraw immediate structures on top.
368   //!
369   //! When scene caching is disabled (myTransientDrawToFront, no double buffer in window, etc.),
370   //! the first step (blitting) will be skipped.
371   //!
372   //! @return false if immediate structures has been rendered directly into FrontBuffer
373   //! and Buffer Swap should not be called.
374   Standard_EXPORT virtual bool redrawImmediate (const Graphic3d_Camera::Projection theProjection,
375                                                 OpenGl_FrameBuffer* theReadFbo,
376                                                 OpenGl_FrameBuffer* theDrawFbo,
377                                                 OpenGl_FrameBuffer* theOitAccumFbo,
378                                                 const Standard_Boolean theIsPartialUpdate = Standard_False);
379
380   //! Blit image from/to specified buffers.
381   Standard_EXPORT bool blitBuffers (OpenGl_FrameBuffer*    theReadFbo,
382                                     OpenGl_FrameBuffer*    theDrawFbo,
383                                     const Standard_Boolean theToFlip = Standard_False);
384
385   //! Setup default FBO.
386   Standard_EXPORT void bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo = NULL);
387
388 protected: //! @name Rendering of GL graphics (with prepared drawing buffer).
389
390   //! Renders the graphical contents of the view into the preprepared window or framebuffer.
391   //! @param theProjection [in] the projection that should be used for rendering.
392   //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
393   //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
394   //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
395   Standard_EXPORT virtual void render (Graphic3d_Camera::Projection theProjection,
396                                        OpenGl_FrameBuffer*          theReadDrawFbo,
397                                        OpenGl_FrameBuffer*          theOitAccumFbo,
398                                        const Standard_Boolean       theToDrawImmediate);
399
400   //! Renders the graphical scene.
401   //! @param theProjection [in] the projection that is used for rendering.
402   //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
403   //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
404   //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
405   Standard_EXPORT virtual void renderScene (Graphic3d_Camera::Projection theProjection,
406                                             OpenGl_FrameBuffer*    theReadDrawFbo,
407                                             OpenGl_FrameBuffer*    theOitAccumFbo,
408                                             const Standard_Boolean theToDrawImmediate);
409
410   //! Draw background (gradient / image)
411   Standard_EXPORT virtual void drawBackground (const Handle(OpenGl_Workspace)& theWorkspace,
412                                                Graphic3d_Camera::Projection theProjection);
413
414   //! Render set of structures presented in the view.
415   //! @param theProjection [in] the projection that is used for rendering.
416   //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
417   //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
418   //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
419   Standard_EXPORT virtual void renderStructs (Graphic3d_Camera::Projection theProjection,
420                                               OpenGl_FrameBuffer*    theReadDrawFbo,
421                                               OpenGl_FrameBuffer*    theOitAccumFbo,
422                                               const Standard_Boolean theToDrawImmediate);
423
424   //! Renders trihedron.
425   void renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
426
427   //! Renders frame statistics.
428   void renderFrameStats();
429
430 private:
431
432   //! Adds the structure to display lists of the view.
433   Standard_EXPORT virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
434                                                  const Standard_Integer thePriority) Standard_OVERRIDE;
435
436   //! Erases the structure from display lists of the view.
437   Standard_EXPORT virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) Standard_OVERRIDE;
438
439   //! Change Z layer of a structure already presented in view.
440   Standard_EXPORT virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure,
441                                              const Graphic3d_ZLayerId theNewLayerId) Standard_OVERRIDE;
442
443   //! Changes the priority of a structure within its Z layer in the specified view.
444   Standard_EXPORT virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure,
445                                                const Standard_Integer theNewPriority) Standard_OVERRIDE;
446
447 private:
448
449   //! Release sRGB resources (frame-buffers, textures, etc.).
450   void releaseSrgbResources (const Handle(OpenGl_Context)& theCtx);
451
452   //! Copy content of Back buffer to the Front buffer.
453   bool copyBackToFront();
454
455   //! Initialize blit quad.
456   OpenGl_VertexBuffer* initBlitQuad (const Standard_Boolean theToFlip);
457
458   //! Blend together views pair into stereo image.
459   void drawStereoPair (OpenGl_FrameBuffer* theDrawFbo);
460
461   //! Check and update OIT compatibility with current OpenGL context's state.
462   bool checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
463                               const Standard_Boolean theMSAA);
464
465   //! Chooses compatible internal color format for OIT frame buffer.
466   bool chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
467                                     const Standard_Integer theConfigIndex,
468                                     OpenGl_ColorFormats& theFormats);
469
470 protected:
471
472   OpenGl_GraphicDriver*    myDriver;
473   Handle(OpenGl_Window)    myWindow;
474   Handle(OpenGl_Workspace) myWorkspace;
475   Handle(OpenGl_Caps)      myCaps;
476   Standard_Boolean         myWasRedrawnGL;
477
478   Graphic3d_TypeOfBackfacingModel myBackfacing;
479   Handle(Graphic3d_SequenceOfHClipPlane) myClipPlanes;
480   gp_XYZ                          myLocalOrigin;
481   Handle(OpenGl_FrameBuffer)      myFBO;
482   Standard_Boolean                myToShowGradTrihedron;
483   Handle(Graphic3d_TextureMap)    myBackgroundImage;
484   Handle(Graphic3d_TextureEnv)    myTextureEnvData;
485   Graphic3d_GraduatedTrihedron    myGTrihedronData;
486
487   Handle(Graphic3d_LightSet)      myNoShadingLight;
488   Handle(Graphic3d_LightSet)      myLights;
489   OpenGl_LayerList                myZLayers; //!< main list of displayed structure, sorted by layers
490
491   Graphic3d_WorldViewProjState    myWorldViewProjState; //!< camera modification state
492   OpenGl_StateCounter*            myStateCounter;
493   Standard_Size                   myCurrLightSourceState;
494   Standard_Size                   myLightsRevision;
495
496   typedef std::pair<Standard_Size, Standard_Size> StateInfo;
497
498   StateInfo myLastOrientationState;
499   StateInfo myLastViewMappingState;
500   StateInfo myLastLightSourceState;
501
502   //! Is needed for selection of overlapping objects and storage of the current view volume
503   Graphic3d_CullingTool myBVHSelector;
504
505   OpenGl_GraduatedTrihedron myGraduatedTrihedron;
506   OpenGl_FrameStatsPrs      myFrameStatsPrs;
507
508   Handle(OpenGl_TextureSet) myTextureEnv;
509
510   //! Framebuffers for OpenGL output.
511   Handle(OpenGl_FrameBuffer) myOpenGlFBO;
512   Handle(OpenGl_FrameBuffer) myOpenGlFBO2;
513
514 protected: //! @name Rendering properties
515
516   //! Two framebuffers (left and right views) store cached main presentation
517   //! of the view (without presentation of immediate layers).
518   Standard_Integer           mySRgbState;             //!< track sRGB state
519   GLint                      myFboColorFormat;        //!< sized format for color attachments
520   GLint                      myFboDepthFormat;        //!< sized format for depth-stencil attachments
521   OpenGl_ColorFormats        myFboOitColorConfig;     //!< selected color format configuration for OIT color attachments
522   Handle(OpenGl_FrameBuffer) myMainSceneFbos[2];
523   Handle(OpenGl_FrameBuffer) myMainSceneFbosOit[2];      //!< Additional buffers for transparent draw of main layer.
524   Handle(OpenGl_FrameBuffer) myImmediateSceneFbos[2];    //!< Additional buffers for immediate layer in stereo mode.
525   Handle(OpenGl_FrameBuffer) myImmediateSceneFbosOit[2]; //!< Additional buffers for transparency draw of immediate layer.
526   Handle(OpenGl_FrameBuffer) myXrSceneFbo;            //!< additional FBO (without MSAA) for submitting to XR
527   OpenGl_VertexBuffer        myFullScreenQuad;        //!< Vertices for full-screen quad rendering.
528   OpenGl_VertexBuffer        myFullScreenQuadFlip;
529   Standard_Boolean           myToFlipOutput;          //!< Flag to draw result image upside-down
530   unsigned int               myFrameCounter;          //!< redraw counter, for debugging
531   Standard_Boolean           myHasFboBlit;            //!< disable FBOs on failure
532   Standard_Boolean           myToDisableOIT;          //!< disable OIT on failure
533   Standard_Boolean           myToDisableOITMSAA;      //!< disable OIT with MSAA on failure
534   Standard_Boolean           myToDisableMSAA;         //!< disable MSAA after failure
535   Standard_Boolean           myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer)
536   Standard_Boolean           myBackBufferRestored;
537   Standard_Boolean           myIsImmediateDrawn;     //!< flag indicates that immediate mode buffer contains some data
538
539 protected: //! @name Background parameters
540
541   OpenGl_Aspects*            myTextureParams;                     //!< Stores texture and its parameters for textured background
542   OpenGl_Aspects*            myCubeMapParams;                     //!< Stores cubemap and its parameters for cubemap background
543   Handle(Graphic3d_CubeMap)  myBackgroundCubeMap;                 //!< Cubemap has been set as background
544   Graphic3d_TypeOfBackground myBackgroundType;                    //!< Current type of background
545   OpenGl_BackgroundArray*    myBackgrounds[Graphic3d_TypeOfBackground_NB]; //!< Array of primitive arrays of different background types
546
547 protected: //! @name methods related to PBR
548
549   //! Checks whether PBR is available.
550   Standard_EXPORT Standard_Boolean checkPBRAvailability() const;
551
552   //! Generates IBL maps used in PBR pipeline.
553   //! If background cubemap is not set clears all IBL maps.
554   Standard_EXPORT void bakePBREnvironment (const Handle(OpenGl_Context)& theCtx);
555
556   //! Fills all IBL maps with white color.
557   //! So that environment lighting is considered to be constant and is completely controls by ambient light sources.
558   Standard_EXPORT void clearPBREnvironment (const Handle(OpenGl_Context)& theCtx);
559
560   //! Process requests to generate or to clear PBR environment.
561   Standard_EXPORT void processPBREnvRequest (const Handle(OpenGl_Context)& theCtx);
562
563 protected: //! @name fields and types related to PBR
564
565   //! State of PBR environment.
566   enum PBREnvironmentState
567   {
568     OpenGl_PBREnvState_NONEXISTENT,
569     OpenGl_PBREnvState_UNAVAILABLE, // indicates failed try to create PBR environment
570     OpenGl_PBREnvState_CREATED
571   };
572
573   //! Type of action which can be done with PBR environment.
574   enum PBREnvironmentRequest
575   {
576     OpenGl_PBREnvRequest_NONE,
577     OpenGl_PBREnvRequest_BAKE,
578     OpenGl_PBREnvRequest_CLEAR
579   };
580
581   Handle(OpenGl_PBREnvironment) myPBREnvironment; //!< manager of IBL maps used in PBR pipeline
582   PBREnvironmentState           myPBREnvState;    //!< state of PBR environment
583   PBREnvironmentRequest         myPBREnvRequest;  //!< type of action is requested to be done with PBR environment
584
585 protected: //! @name data types related to ray-tracing
586
587   //! Result of OpenGL shaders initialization.
588   enum RaytraceInitStatus
589   {
590     OpenGl_RT_NONE,
591     OpenGl_RT_INIT,
592     OpenGl_RT_FAIL
593   };
594
595   //! Describes update mode (state).
596   enum RaytraceUpdateMode
597   {
598     OpenGl_GUM_CHECK,   //!< check geometry state
599     OpenGl_GUM_PREPARE, //!< collect unchanged objects
600     OpenGl_GUM_REBUILD  //!< rebuild changed and new objects
601   };
602
603   //! Defines frequently used shader variables.
604   enum ShaderVariableIndex
605   {
606     OpenGl_RT_aPosition,
607
608     // camera position
609     OpenGl_RT_uOriginLT,
610     OpenGl_RT_uOriginLB,
611     OpenGl_RT_uOriginRT,
612     OpenGl_RT_uOriginRB,
613     OpenGl_RT_uDirectLT,
614     OpenGl_RT_uDirectLB,
615     OpenGl_RT_uDirectRT,
616     OpenGl_RT_uDirectRB,
617     OpenGl_RT_uViewPrMat,
618     OpenGl_RT_uUnviewMat,
619
620     // 3D scene params
621     OpenGl_RT_uSceneRad,
622     OpenGl_RT_uSceneEps,
623     OpenGl_RT_uLightAmbnt,
624     OpenGl_RT_uLightCount,
625
626     // background params
627     OpenGl_RT_uBackColorTop,
628     OpenGl_RT_uBackColorBot,
629
630     // ray-tracing params
631     OpenGl_RT_uShadowsEnabled,
632     OpenGl_RT_uReflectEnabled,
633     OpenGl_RT_uEnvMapEnabled,
634     OpenGl_RT_uEnvMapForBack,
635     OpenGl_RT_uTexSamplersArray,
636     OpenGl_RT_uBlockedRngEnabled,
637
638     // size of render window
639     OpenGl_RT_uWinSizeX,
640     OpenGl_RT_uWinSizeY,
641
642     // sampled frame params
643     OpenGl_RT_uAccumSamples,
644     OpenGl_RT_uFrameRndSeed,
645
646     // adaptive FSAA params
647     OpenGl_RT_uOffsetX,
648     OpenGl_RT_uOffsetY,
649     OpenGl_RT_uSamples,
650
651     // images used by ISS mode
652     OpenGl_RT_uRenderImage,
653     OpenGl_RT_uTilesImage,
654     OpenGl_RT_uOffsetImage,
655     OpenGl_RT_uTileSize,
656     OpenGl_RT_uVarianceScaleFactor,
657
658     // maximum radiance value
659     OpenGl_RT_uMaxRadiance,
660
661     OpenGl_RT_NbVariables // special field
662   };
663
664   //! Defines OpenGL image samplers.
665   enum ShaderImageNames
666   {
667     OpenGl_RT_OutputImage = 0,
668     OpenGl_RT_VisualErrorImage = 1,
669     OpenGl_RT_TileOffsetsImage = 2,
670     OpenGl_RT_TileSamplesImage = 3
671   };
672
673   //! Tool class for management of shader sources.
674   class ShaderSource
675   {
676   public:
677
678     //! Default shader prefix - empty string.
679     static const TCollection_AsciiString EMPTY_PREFIX;
680
681     //! Creates new uninitialized shader source.
682     ShaderSource()
683     {
684       //
685     }
686
687   public:
688
689     //! Returns error description in case of load fail.
690     const TCollection_AsciiString& ErrorDescription() const
691     {
692       return myError;
693     }
694
695     //! Returns prefix to insert before the source.
696     const TCollection_AsciiString& Prefix() const
697     {
698       return myPrefix;
699     }
700
701     //! Sets prefix to insert before the source.
702     void SetPrefix (const TCollection_AsciiString& thePrefix)
703     {
704       myPrefix = thePrefix;
705     }
706
707     //! Returns shader source combined with prefix.
708     TCollection_AsciiString Source() const;
709
710     //! Loads shader source from specified files.
711     Standard_Boolean LoadFromFiles (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
712
713     //! Loads shader source from specified strings.
714     Standard_Boolean LoadFromStrings (const TCollection_AsciiString* theStrings, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
715
716   private:
717
718     TCollection_AsciiString mySource; //!< Source string of the shader object
719     TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
720     TCollection_AsciiString myError;  //!< error state
721
722   };
723
724   //! Default ray-tracing depth.
725   static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
726
727   //! Default size of traversal stack.
728   static const Standard_Integer THE_DEFAULT_STACK_SIZE = 10;
729
730   //! Compile-time ray-tracing parameters.
731   struct RaytracingParams
732   {
733     //! Actual size of traversal stack in shader program.
734     Standard_Integer StackSize;
735
736     //! Actual ray-tracing depth (number of ray bounces).
737     Standard_Integer NbBounces;
738
739     //! Enables/disables light propagation through transparent media.
740     Standard_Boolean TransparentShadows;
741
742     //! Enables/disables global illumination (GI) effects.
743     Standard_Boolean GlobalIllumination;
744
745     //! Enables/disables the use of OpenGL bindless textures.
746     Standard_Boolean UseBindlessTextures;
747
748     //! Enables/disables two-sided BSDF models instead of one-sided.
749     Standard_Boolean TwoSidedBsdfModels;
750
751     //! Enables/disables adaptive screen sampling for path tracing.
752     Standard_Boolean AdaptiveScreenSampling;
753
754     //! Enables/disables 1-pass atomic mode for AdaptiveScreenSampling.
755     Standard_Boolean AdaptiveScreenSamplingAtomic;
756
757     //! Enables/disables environment map for background.
758     Standard_Boolean UseEnvMapForBackground;
759
760     //! Enables/disables normal map ignoring during path tracing.
761     Standard_Boolean ToIgnoreNormalMap;
762
763     //! Maximum radiance value used for clamping radiance estimation.
764     Standard_ShortReal RadianceClampingValue;
765     
766     //! Enables/disables depth-of-field effect (path tracing, perspective camera).
767     Standard_Boolean DepthOfField;
768
769     //! Enables/disables cubemap backgraund.
770     Standard_Boolean CubemapForBack;
771
772     //! Tone mapping method for path tracing.
773     Graphic3d_ToneMappingMethod ToneMappingMethod;
774
775     //! Creates default compile-time ray-tracing parameters.
776     RaytracingParams()
777     : StackSize              (THE_DEFAULT_STACK_SIZE),
778       NbBounces              (THE_DEFAULT_NB_BOUNCES),
779       TransparentShadows     (Standard_False),
780       GlobalIllumination     (Standard_False),
781       UseBindlessTextures    (Standard_False),
782       TwoSidedBsdfModels     (Standard_False),
783       AdaptiveScreenSampling (Standard_False),
784       AdaptiveScreenSamplingAtomic (Standard_False),
785       UseEnvMapForBackground (Standard_False),
786       ToIgnoreNormalMap      (Standard_False),
787       RadianceClampingValue  (30.0),
788       DepthOfField           (Standard_False),
789       CubemapForBack         (Standard_False),
790       ToneMappingMethod      (Graphic3d_ToneMappingMethod_Disabled) { }
791   };
792
793   //! Describes state of OpenGL structure.
794   struct StructState
795   {
796     Standard_Size StructureState;
797     Standard_Size InstancedState;
798
799     //! Creates new structure state.
800     StructState (const Standard_Size theStructureState = 0,
801                  const Standard_Size theInstancedState = 0)
802     : StructureState (theStructureState),
803       InstancedState (theInstancedState)
804     {
805       //
806     }
807
808     //! Creates new structure state.
809     StructState (const OpenGl_Structure* theStructure)
810     {
811       StructureState = theStructure->ModificationState();
812
813       InstancedState = theStructure->InstancedStructure() != NULL ?
814         theStructure->InstancedStructure()->ModificationState() : 0;
815     }
816   };
817
818 protected: //! @name methods related to ray-tracing
819
820   //! Updates 3D scene geometry for ray-tracing.
821   Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode      theMode,
822                                            const Standard_Integer        theViewId,
823                                            const Handle(OpenGl_Context)& theGlContext);
824
825   //! Updates 3D scene light sources for ray-tracing.
826   Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
827
828   //! Checks to see if the OpenGL structure is modified.
829   Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
830
831   //! Adds OpenGL structure to ray-traced scene geometry.
832   Standard_Boolean addRaytraceStructure (const OpenGl_Structure*       theStructure,
833                                          const Handle(OpenGl_Context)& theGlContext);
834
835   //! Adds OpenGL groups to ray-traced scene geometry.
836   Standard_Boolean addRaytraceGroups (const OpenGl_Structure*        theStructure,
837                                       const OpenGl_RaytraceMaterial& theStructMat,
838                                       const Handle(TopLoc_Datum3D)&  theTrsf,
839                                       const Handle(OpenGl_Context)&  theGlContext);
840
841   //! Creates ray-tracing material properties.
842   OpenGl_RaytraceMaterial convertMaterial (const OpenGl_Aspects* theAspect,
843                                            const Handle(OpenGl_Context)& theGlContext);
844
845   //! Adds OpenGL primitive array to ray-traced scene geometry.
846   Handle(OpenGl_TriangleSet) addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
847                                                         const Standard_Integer       theMatID,
848                                                         const OpenGl_Mat4*           theTrans);
849
850   //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
851   Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet&                  theSet,
852                                              const Standard_Integer               theMatID,
853                                              const Standard_Integer               theCount,
854                                              const Standard_Integer               theOffset,
855                                              const OpenGl_PrimitiveArray&         theArray);
856
857   //! Adds OpenGL triangle array to ray-traced scene geometry.
858   Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
859                                              const Standard_Integer               theMatID,
860                                              const Standard_Integer               theCount,
861                                              const Standard_Integer               theOffset,
862                                              const Handle(Graphic3d_IndexBuffer)& theIndices);
863
864   //! Adds OpenGL triangle fan array to ray-traced scene geometry.
865   Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
866                                                 const Standard_Integer               theMatID,
867                                                 const Standard_Integer               theCount,
868                                                 const Standard_Integer               theOffset,
869                                                 const Handle(Graphic3d_IndexBuffer)& theIndices);
870
871   //! Adds OpenGL triangle strip array to ray-traced scene geometry.
872   Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
873                                                   const Standard_Integer               theMatID,
874                                                   const Standard_Integer               theCount,
875                                                   const Standard_Integer               theOffset,
876                                                   const Handle(Graphic3d_IndexBuffer)& theIndices);
877
878   //! Adds OpenGL quadrangle array to ray-traced scene geometry.
879   Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
880                                                const Standard_Integer               theMatID,
881                                                const Standard_Integer               theCount,
882                                                const Standard_Integer               theOffset,
883                                                const Handle(Graphic3d_IndexBuffer)& theIndices);
884
885   //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
886   Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
887                                                     const Standard_Integer               theMatID,
888                                                     const Standard_Integer               theCount,
889                                                     const Standard_Integer               theOffset,
890                                                     const Handle(Graphic3d_IndexBuffer)& theIndices);
891
892   //! Adds OpenGL polygon array to ray-traced scene geometry.
893   Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
894                                             const Standard_Integer               theMatID,
895                                             const Standard_Integer               theCount,
896                                             const Standard_Integer               theOffset,
897                                             const Handle(Graphic3d_IndexBuffer)& theIndices);
898
899   //! Uploads ray-trace data to the GPU.
900   Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
901
902   //! Generates shader prefix based on current ray-tracing options.
903   TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
904
905   //! Performs safe exit when shaders initialization fails.
906   Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
907                                  const Handle(OpenGl_Context)&     theGlContext);
908
909   //! Loads and compiles shader object from specified source.
910   Handle(OpenGl_ShaderObject) initShader (const GLenum                  theType,
911                                           const ShaderSource&           theSource,
912                                           const Handle(OpenGl_Context)& theGlContext);
913
914   //! Creates shader program from the given vertex and fragment shaders.
915   Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)&      theGlContext,
916                                             const Handle(OpenGl_ShaderObject)& theVertShader,
917                                             const Handle(OpenGl_ShaderObject)& theFragShader,
918                                             const TCollection_AsciiString& theName);
919
920   //! Initializes OpenGL/GLSL shader programs.
921   Standard_Boolean initRaytraceResources (const Standard_Integer theSizeX,
922                                           const Standard_Integer theSizeY,
923                                           const Handle(OpenGl_Context)& theGlContext);
924
925   //! Releases OpenGL/GLSL shader programs.
926   void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext,
927                                  const Standard_Boolean        theToRebuild = Standard_False);
928
929   //! Updates auxiliary OpenGL frame buffers.
930   Standard_Boolean updateRaytraceBuffers (const Standard_Integer        theSizeX,
931                                           const Standard_Integer        theSizeY,
932                                           const Handle(OpenGl_Context)& theGlContext);
933
934   //! Generates viewing rays for corners of screen quad.
935   //! (ray tracing; path tracing for orthographic camera)
936   void updateCamera (const OpenGl_Mat4& theOrientation,
937                      const OpenGl_Mat4& theViewMapping,
938                      OpenGl_Vec3*       theOrigins,
939                      OpenGl_Vec3*       theDirects,
940                      OpenGl_Mat4&       theView,
941                      OpenGl_Mat4&       theUnView);
942
943   //! Generate viewing rays (path tracing, perspective camera).
944   void updatePerspCameraPT(const OpenGl_Mat4&           theOrientation,
945                            const OpenGl_Mat4&           theViewMapping,
946                            Graphic3d_Camera::Projection theProjection,
947                            OpenGl_Mat4&                 theViewPr,
948                            OpenGl_Mat4&                 theUnview,
949                            const int                    theWinSizeX,
950                            const int                    theWinSizeY);
951
952   //! Binds ray-trace textures to corresponding texture units.
953   void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
954                              int theStereoView);
955
956   //! Unbinds ray-trace textures from corresponding texture unit.
957   void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
958
959   //! Sets uniform state for the given ray-tracing shader program.
960   Standard_Boolean setUniformState (const Standard_Integer        theProgramId,
961                                     const Standard_Integer        theSizeX,
962                                     const Standard_Integer        theSizeY,
963                                     Graphic3d_Camera::Projection  theProjection,
964                                     const Handle(OpenGl_Context)& theGlContext);
965
966   //! Runs ray-tracing shader programs.
967   Standard_Boolean runRaytraceShaders (const Standard_Integer        theSizeX,
968                                        const Standard_Integer        theSizeY,
969                                        Graphic3d_Camera::Projection  theProjection,
970                                        OpenGl_FrameBuffer*           theReadDrawFbo,
971                                        const Handle(OpenGl_Context)& theGlContext);
972
973   //! Runs classical (Whitted-style) ray-tracing kernel.
974   Standard_Boolean runRaytrace (const Standard_Integer        theSizeX,
975                                 const Standard_Integer        theSizeY,
976                                 Graphic3d_Camera::Projection  theProjection,
977                                 OpenGl_FrameBuffer*           theReadDrawFbo,
978                                 const Handle(OpenGl_Context)& theGlContext);
979
980   //! Runs path tracing (global illumination) kernel.
981   Standard_Boolean runPathtrace (const Standard_Integer        theSizeX,
982                                  const Standard_Integer        theSizeY,
983                                  Graphic3d_Camera::Projection  theProjection,
984                                  const Handle(OpenGl_Context)& theGlContext);
985
986   //! Runs path tracing (global illumination) kernel.
987   Standard_Boolean runPathtraceOut (Graphic3d_Camera::Projection  theProjection,
988                                     OpenGl_FrameBuffer*           theReadDrawFbo,
989                                     const Handle(OpenGl_Context)& theGlContext);
990
991   //! Redraws the window using OpenGL/GLSL ray-tracing or path tracing.
992   Standard_Boolean raytrace (const Standard_Integer        theSizeX,
993                              const Standard_Integer        theSizeY,
994                              Graphic3d_Camera::Projection  theProjection,
995                              OpenGl_FrameBuffer*           theReadDrawFbo,
996                              const Handle(OpenGl_Context)& theGlContext);
997
998 protected: //! @name fields related to ray-tracing
999
1000   //! Result of RT/PT shaders initialization.
1001   RaytraceInitStatus myRaytraceInitStatus;
1002
1003   //! Is ray-tracing geometry data valid?
1004   Standard_Boolean myIsRaytraceDataValid;
1005
1006   //! True if warning about missing extension GL_ARB_bindless_texture has been displayed.
1007   Standard_Boolean myIsRaytraceWarnTextures;
1008
1009   //! 3D scene geometry data for ray-tracing.
1010   OpenGl_RaytraceGeometry myRaytraceGeometry;
1011
1012   //! Builder for triangle set.
1013   opencascade::handle<BVH_Builder<Standard_ShortReal, 3> > myRaytraceBVHBuilder;
1014
1015   //! Compile-time ray-tracing parameters.
1016   RaytracingParams myRaytraceParameters;
1017
1018   //! Radius of bounding sphere of the scene.
1019   Standard_ShortReal myRaytraceSceneRadius;
1020   //! Scene epsilon to prevent self-intersections.
1021   Standard_ShortReal myRaytraceSceneEpsilon;
1022
1023   //! OpenGL/GLSL source of ray-tracing fragment shader.
1024   ShaderSource myRaytraceShaderSource;
1025   //! OpenGL/GLSL source of adaptive-AA fragment shader.
1026   ShaderSource myPostFSAAShaderSource;
1027   //! OpenGL/GLSL source of RT/PT display fragment shader.
1028   ShaderSource myOutImageShaderSource;
1029
1030   //! OpenGL/GLSL ray-tracing fragment shader.
1031   Handle(OpenGl_ShaderObject) myRaytraceShader;
1032   //! OpenGL/GLSL adaptive-AA fragment shader.
1033   Handle(OpenGl_ShaderObject) myPostFSAAShader;
1034   //! OpenGL/GLSL ray-tracing display fragment shader.
1035   Handle(OpenGl_ShaderObject) myOutImageShader;
1036
1037   //! OpenGL/GLSL ray-tracing shader program.
1038   Handle(OpenGl_ShaderProgram) myRaytraceProgram;
1039   //! OpenGL/GLSL adaptive-AA shader program.
1040   Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
1041   //! OpenGL/GLSL program for displaying texture.
1042   Handle(OpenGl_ShaderProgram) myOutImageProgram;
1043
1044   //! Texture buffer of data records of bottom-level BVH nodes.
1045   Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
1046   //! Texture buffer of minimum points of bottom-level BVH nodes.
1047   Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
1048   //! Texture buffer of maximum points of bottom-level BVH nodes.
1049   Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
1050   //! Texture buffer of transformations of high-level BVH nodes.
1051   Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
1052
1053   //! Texture buffer of vertex coords.
1054   Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
1055   //! Texture buffer of vertex normals.
1056   Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
1057   //! Texture buffer of vertex UV coords.
1058   Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
1059   //! Texture buffer of triangle indices.
1060   Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
1061
1062   //! Texture buffer of material properties.
1063   Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
1064   //! Texture buffer of light source properties.
1065   Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
1066
1067   //! 1st framebuffer (FBO) to perform adaptive FSAA.
1068   //! Used in compatibility mode (no adaptive sampling).
1069   Handle(OpenGl_FrameBuffer) myRaytraceFBO1[2];
1070   //! 2nd framebuffer (FBO) to perform adaptive FSAA.
1071   //! Used in compatibility mode (no adaptive sampling).
1072   Handle(OpenGl_FrameBuffer) myRaytraceFBO2[2];
1073
1074   //! Output textures (2 textures are used in stereo mode).
1075   //! Used if adaptive screen sampling is activated.
1076   Handle(OpenGl_Texture) myRaytraceOutputTexture[2];
1077
1078   //! Texture containing per-tile visual error estimation (2 textures are used in stereo mode).
1079   //! Used if adaptive screen sampling is activated.
1080   Handle(OpenGl_Texture) myRaytraceVisualErrorTexture[2];
1081   //! Texture containing offsets of sampled screen tiles (2 textures are used in stereo mode).
1082   //! Used if adaptive screen sampling is activated.
1083   Handle(OpenGl_Texture) myRaytraceTileOffsetsTexture[2];
1084   //! Texture containing amount of extra per-tile samples (2 textures are used in stereo mode).
1085   //! Used if adaptive screen sampling is activated.
1086   Handle(OpenGl_Texture) myRaytraceTileSamplesTexture[2];
1087
1088   //! Vertex buffer (VBO) for drawing dummy quad.
1089   OpenGl_VertexBuffer myRaytraceScreenQuad;
1090
1091   //! Cached locations of frequently used uniform variables.
1092   Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
1093
1094   //! State of OpenGL structures reflected to ray-tracing.
1095   std::map<const OpenGl_Structure*, StructState> myStructureStates;
1096
1097   //! PrimitiveArray to TriangleSet map for scene partial update.
1098   std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
1099
1100   //! Set of IDs of non-raytracable elements (to detect updates).
1101   std::set<Standard_Integer> myNonRaytraceStructureIDs;
1102
1103   //! Marks if environment map should be updated.
1104   Standard_Boolean myToUpdateEnvironmentMap;
1105
1106   //! State of OpenGL layer list.
1107   Standard_Size myRaytraceLayerListState;
1108
1109   //! Number of accumulated frames (for progressive rendering).
1110   Standard_Integer myAccumFrames;
1111
1112   //! Stored ray origins used for detection of camera movements.
1113   OpenGl_Vec3 myPreviousOrigins[3];
1114
1115   //! Bullard RNG to produce random sequence.
1116   math_BullardGenerator myRNG;
1117
1118   //! Tool object for sampling screen tiles in PT mode.
1119   OpenGl_TileSampler myTileSampler;
1120
1121   //! Camera position used for projective mode
1122   OpenGl_Vec3 myEyeOrig;
1123
1124   //! Camera view direction used for projective mode
1125   OpenGl_Vec3 myEyeView;
1126
1127   //! Camera's screen vertical direction used for projective mode
1128   OpenGl_Vec3 myEyeVert;
1129
1130   //! Camera's screen horizontal direction used for projective mode
1131   OpenGl_Vec3 myEyeSide;
1132
1133   //! Camera's screen size used for projective mode
1134   OpenGl_Vec2 myEyeSize;
1135
1136   //! Aperture radius of camera on previous frame used for depth-of-field (path tracing)
1137   float myPrevCameraApertureRadius;
1138
1139   //! Focal distance of camera on previous frame used for depth-of-field (path tracing)
1140   float myPrevCameraFocalPlaneDist;
1141
1142 public:
1143
1144   DEFINE_STANDARD_ALLOC
1145   DEFINE_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView) // Type definition
1146
1147   friend class OpenGl_GraphicDriver;
1148   friend class OpenGl_Workspace;
1149   friend class OpenGl_LayerList;
1150   friend class OpenGl_FrameStats;
1151 };
1152
1153 #endif // _OpenGl_View_Header