1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
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.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #ifndef _OpenGl_View_Header
17 #define _OpenGl_View_Header
19 #include <MMgt_TShared.hxx>
20 #include <Standard_Type.hxx>
22 #include <TColStd_Array2OfReal.hxx>
23 #include <NCollection_List.hxx>
24 #include <math_BullardGenerator.hxx>
26 #include <Quantity_NameOfColor.hxx>
27 #include <Aspect_FillMethod.hxx>
28 #include <Aspect_GradientFillMethod.hxx>
29 #include <Aspect_TypeOfTriedronPosition.hxx>
31 #include <Graphic3d_CView.hxx>
32 #include <Graphic3d_GraduatedTrihedron.hxx>
33 #include <Graphic3d_SequenceOfHClipPlane.hxx>
34 #include <Graphic3d_TypeOfShadingModel.hxx>
35 #include <Graphic3d_WorldViewProjState.hxx>
36 #include <Graphic3d_ZLayerSettings.hxx>
38 #include <OpenGl_AspectFace.hxx>
39 #include <OpenGl_BackgroundArray.hxx>
40 #include <OpenGl_BVHTreeSelector.hxx>
41 #include <OpenGl_Context.hxx>
42 #include <OpenGl_FrameBuffer.hxx>
43 #include <OpenGl_GraduatedTrihedron.hxx>
44 #include <OpenGl_LayerList.hxx>
45 #include <OpenGl_Light.hxx>
46 #include <OpenGl_LineAttributes.hxx>
47 #include <OpenGl_SceneGeometry.hxx>
48 #include <OpenGl_Structure.hxx>
49 #include <OpenGl_Trihedron.hxx>
50 #include <OpenGl_Window.hxx>
51 #include <OpenGl_Workspace.hxx>
58 class Graphic3d_StructureManager;
59 class OpenGl_GraphicDriver;
60 class OpenGl_StateCounter;
61 class OpenGl_RaytraceMaterial;
62 class OpenGl_TriangleSet;
63 class OpenGl_Workspace;
65 DEFINE_STANDARD_HANDLE(OpenGl_View,Graphic3d_CView)
67 //! Implementation of OpenGl view.
68 class OpenGl_View : public Graphic3d_CView
74 Standard_EXPORT OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
75 const Handle(OpenGl_GraphicDriver)& theDriver,
76 const Handle(OpenGl_Caps)& theCaps,
77 Standard_Boolean& theDeviceLostFlag,
78 OpenGl_StateCounter* theCounter);
80 //! Default destructor.
81 Standard_EXPORT virtual ~OpenGl_View();
83 Standard_EXPORT void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx);
85 //! Deletes and erases the view.
86 Standard_EXPORT virtual void Remove() Standard_OVERRIDE;
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;
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;
108 //! Returns window associated with the view.
109 virtual Handle(Aspect_Window) Window() const Standard_OVERRIDE
110 { return myWindow->PlatformWindow(); }
112 //! Returns True if the window associated to the view is defined.
113 virtual Standard_Boolean IsDefined() const Standard_OVERRIDE
114 { return !myWindow.IsNull(); }
116 //! Handle changing size of the rendering window.
117 Standard_EXPORT virtual void Resized() Standard_OVERRIDE;
119 //! Redraw content of the view.
120 Standard_EXPORT virtual void Redraw() Standard_OVERRIDE;
122 //! Redraw immediate content of the view.
123 Standard_EXPORT virtual void RedrawImmediate() Standard_OVERRIDE;
125 //! Marks BVH tree for given priority list as dirty and marks primitive set for rebuild.
126 Standard_EXPORT virtual void Invalidate() Standard_OVERRIDE;
128 //! Return true if view content cache has been invalidated.
129 virtual Standard_Boolean IsInvalidated() Standard_OVERRIDE { return !myBackBufferRestored; }
131 //! Displays z-buffer trihedron.
132 Standard_EXPORT virtual void TriedronDisplay (const Aspect_TypeOfTriedronPosition thePosition = Aspect_TOTP_CENTER,
133 const Quantity_NameOfColor theColor = Quantity_NOC_WHITE,
134 const Standard_Real theScale = 0.02,
135 const Standard_Boolean theAsWireframe = Standard_True) Standard_OVERRIDE;
137 //! Erases z-buffer trihedron.
138 Standard_EXPORT virtual void TriedronErase() Standard_OVERRIDE;
140 //! Setup parameters of z-buffer trihedron.
141 Standard_EXPORT virtual void ZBufferTriedronSetup (const Quantity_NameOfColor theXColor = Quantity_NOC_RED,
142 const Quantity_NameOfColor theYColor = Quantity_NOC_GREEN,
143 const Quantity_NameOfColor theZColor = Quantity_NOC_BLUE1,
144 const Standard_Real theSizeRatio = 0.8,
145 const Standard_Real theAxisDiametr = 0.05,
146 const Standard_Integer theNbFacettes = 12) Standard_OVERRIDE;
148 //! Displays trihedron echo.
149 Standard_EXPORT virtual void TriedronEcho (const Aspect_TypeOfTriedronEcho theType = Aspect_TOTE_NONE) Standard_OVERRIDE;
151 //! Returns data of a graduated trihedron
152 const Graphic3d_GraduatedTrihedron& GetGraduatedTrihedron() Standard_OVERRIDE
153 { return myGTrihedronData; }
155 //! Displays Graduated Trihedron.
156 Standard_EXPORT virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) Standard_OVERRIDE;
158 //! Erases Graduated Trihedron.
159 Standard_EXPORT virtual void GraduatedTrihedronErase() Standard_OVERRIDE;
161 //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object.
162 //! @param theMin [in] the minimum point of scene.
163 //! @param theMax [in] the maximum point of scene.
164 Standard_EXPORT virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) Standard_OVERRIDE;
166 //! Dump active rendering buffer into specified memory buffer.
167 Standard_EXPORT virtual Standard_Boolean BufferDump (Image_PixMap& theImage,
168 const Graphic3d_BufferType& theBufferType) Standard_OVERRIDE;
170 //! Export scene into the one of the Vector graphics formats (SVG, PS, PDF...).
171 //! In contrast to Bitmaps, Vector graphics is scalable (so you may got quality benefits
172 //! on printing to laser printer). Notice however that results may differ a lot and
173 //! do not contain some elements.
174 Standard_EXPORT virtual Standard_Boolean Export (const Standard_CString theFileName,
175 const Graphic3d_ExportFormat theFormat,
176 const Graphic3d_SortType theSortType = Graphic3d_ST_BSP_Tree) Standard_OVERRIDE;
178 //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated.
179 Standard_EXPORT virtual void InvalidateBVHData (const Standard_Integer theLayerId) Standard_OVERRIDE;
181 //! Insert a new top-level z layer with the given ID.
182 Standard_EXPORT virtual void AddZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
184 //! Remove a z layer with the given ID.
185 Standard_EXPORT virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
187 //! Sets the settings for a single Z layer of specified view.
188 Standard_EXPORT virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
189 const Graphic3d_ZLayerSettings& theSettings) Standard_OVERRIDE;
191 //! Returns the maximum Z layer ID.
192 //! First layer ID is Graphic3d_ZLayerId_Default, last ID is ZLayerMax().
193 Standard_EXPORT virtual Standard_Integer ZLayerMax() const Standard_OVERRIDE;
195 //! Returns the bounding box of all structures displayed in the Z layer.
196 //! Never fails. If Z layer does not exist nothing happens.
197 Standard_EXPORT virtual void InvalidateZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId) const Standard_OVERRIDE;
199 //! Returns the bounding box of all structures displayed in the Z layer.
200 //! If Z layer does not exist the empty box is returned.
201 //! @param theLayerId layer identifier
202 //! @param theCamera camera definition
203 //! @param theWindowWidth viewport width (for applying transformation-persistence)
204 //! @param theWindowHeight viewport height (for applying transformation-persistence)
205 //! @param theToIncludeAuxiliary consider also auxiliary presentations (with infinite flag or with trihedron transformation persistence)
206 //! @return computed bounding box
207 Standard_EXPORT virtual Graphic3d_BndBox4f ZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId,
208 const Handle(Graphic3d_Camera)& theCamera,
209 const Standard_Integer theWindowWidth,
210 const Standard_Integer theWindowHeight,
211 const Standard_Boolean theToIncludeAuxiliary) const Standard_OVERRIDE;
213 //! Returns pointer to an assigned framebuffer object.
214 Standard_EXPORT virtual Handle(Standard_Transient) FBO() const Standard_OVERRIDE;
216 //! Sets framebuffer object for offscreen rendering.
217 Standard_EXPORT virtual void SetFBO (const Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
219 //! Generate offscreen FBO in the graphic library.
220 //! If not supported on hardware returns NULL.
221 Standard_EXPORT virtual Handle(Standard_Transient) FBOCreate (const Standard_Integer theWidth,
222 const Standard_Integer theHeight) Standard_OVERRIDE;
224 //! Remove offscreen FBO from the graphic library
225 Standard_EXPORT virtual void FBORelease (Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
227 //! Read offscreen FBO configuration.
228 Standard_EXPORT virtual void FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
229 Standard_Integer& theWidth,
230 Standard_Integer& theHeight,
231 Standard_Integer& theWidthMax,
232 Standard_Integer& theHeightMax) Standard_OVERRIDE;
234 //! Change offscreen FBO viewport.
235 Standard_EXPORT virtual void FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
236 const Standard_Integer theWidth,
237 const Standard_Integer theHeight) Standard_OVERRIDE;
241 //! Returns background fill color.
242 Standard_EXPORT virtual Aspect_Background Background() const Standard_OVERRIDE;
244 //! Sets background fill color.
245 Standard_EXPORT virtual void SetBackground (const Aspect_Background& theBackground) Standard_OVERRIDE;
247 //! Returns gradient background fill colors.
248 Standard_EXPORT virtual Aspect_GradientBackground GradientBackground() const Standard_OVERRIDE;
250 //! Sets gradient background fill colors.
251 Standard_EXPORT virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) Standard_OVERRIDE;
253 //! Returns background image texture file path.
254 Standard_EXPORT virtual TCollection_AsciiString BackgroundImage() Standard_OVERRIDE { return myBackgroundImagePath; }
256 //! Sets background image texture file path.
257 Standard_EXPORT virtual void SetBackgroundImage (const TCollection_AsciiString& theFilePath) Standard_OVERRIDE;
259 //! Returns background image fill style.
260 Standard_EXPORT virtual Aspect_FillMethod BackgroundImageStyle() const Standard_OVERRIDE;
262 //! Sets background image fill style.
263 Standard_EXPORT virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) Standard_OVERRIDE;
265 //! Returns environment texture set for the view.
266 Standard_EXPORT virtual Handle(Graphic3d_TextureEnv) TextureEnv() const Standard_OVERRIDE { return myTextureEnvData; }
268 //! Sets environment texture for the view.
269 Standard_EXPORT virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) Standard_OVERRIDE;
271 //! Returns the state of frustum culling optimization.
272 virtual Standard_Boolean IsCullingEnabled() const Standard_OVERRIDE { return myCulling; }
274 //! Enables or disables frustum culling optimization.
275 virtual void SetCullingEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myCulling = theIsEnabled; }
277 //! Returns shading model of the view.
278 virtual Graphic3d_TypeOfShadingModel ShadingModel() const Standard_OVERRIDE { return myShadingModel; }
280 //! Sets shading model of the view.
281 virtual void SetShadingModel (const Graphic3d_TypeOfShadingModel theModel) Standard_OVERRIDE { myShadingModel = theModel; }
283 //! Return backfacing model used for the view.
284 virtual Graphic3d_TypeOfBackfacingModel BackfacingModel() const Standard_OVERRIDE { return myBackfacing; }
286 //! Sets backfacing model for the view.
287 virtual void SetBackfacingModel (const Graphic3d_TypeOfBackfacingModel theModel) Standard_OVERRIDE { myBackfacing = theModel; }
289 //! Returns camera object of the view.
290 virtual const Handle(Graphic3d_Camera)& Camera() const Standard_OVERRIDE { return myCamera; }
292 //! Sets camera used by the view.
293 virtual void SetCamera (const Handle(Graphic3d_Camera)& theCamera) Standard_OVERRIDE { myCamera = theCamera; }
295 //! Returns true if GL lighting is enabled.
296 virtual Standard_Boolean IsGLLightEnabled() const Standard_OVERRIDE { return myUseGLLight; }
298 //! Sets GL lighting enabled or disable state.
299 virtual void SetGLLightEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myUseGLLight = theIsEnabled; }
301 //! Returns list of lights of the view.
302 virtual const Graphic3d_ListOfCLight& Lights() const Standard_OVERRIDE { return myLights; }
304 //! Sets list of lights for the view.
305 virtual void SetLights (const Graphic3d_ListOfCLight& theLights) Standard_OVERRIDE
307 myLights = theLights;
308 myCurrLightSourceState = myStateCounter->Increment();
311 //! Returns list of clip planes set for the view.
312 virtual const Graphic3d_SequenceOfHClipPlane& ClipPlanes() const Standard_OVERRIDE { return myClipPlanes; }
314 //! Sets list of clip planes for the view.
315 virtual void SetClipPlanes (const Graphic3d_SequenceOfHClipPlane& thePlanes) Standard_OVERRIDE { myClipPlanes = thePlanes; }
319 //! Returns background color.
320 const Quantity_ColorRGBA& BackgroundColor() const { return myBgColor; }
322 //! Change trihedron.
323 OpenGl_Trihedron& ChangeTrihedron() { return myTrihedron; }
325 //! Change graduated trihedron.
326 OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
328 void SetTextureEnv (const Handle(OpenGl_Context)& theCtx,
329 const Handle(Graphic3d_TextureEnv)& theTexture);
331 void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
333 void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
335 void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
337 //! Returns list of OpenGL Z-layers.
338 const OpenGl_LayerList& LayerList() const { return myZLayers; }
340 //! Returns list of openGL light sources.
341 const OpenGl_ListOfLight& LightList() const { return myLights; }
343 //! Returns OpenGL window implementation.
344 const Handle(OpenGl_Window) GlWindow() const { return myWindow; }
346 //! Returns OpenGL environment map.
347 const Handle(OpenGl_Texture)& GlTextureEnv() const { return myTextureEnv; }
349 //! Returns selector for BVH tree, providing a possibility to store information
350 //! about current view volume and to detect which objects are overlapping it.
351 OpenGl_BVHTreeSelector& BVHTreeSelector() { return myBVHSelector; }
353 //! Returns true if there are immediate structures to display
354 bool HasImmediateStructures() const
356 return myZLayers.NbImmediateStructures() != 0;
359 protected: //! @name Internal methods for managing GL resources
361 //! Initializes OpenGl resource for environment texture.
362 void initTextureEnv (const Handle(OpenGl_Context)& theContext);
364 protected: //! @name low-level redrawing sub-routines
366 //! Redraws view for the given monographic camera projection, or left/right eye.
367 Standard_EXPORT virtual void redraw (const Graphic3d_Camera::Projection theProjection,
368 OpenGl_FrameBuffer* theReadDrawFbo);
370 //! Redraws view for the given monographic camera projection, or left/right eye.
372 //! Method will blit snapshot containing main scene (myMainSceneFbos or BackBuffer)
373 //! into presentation buffer (myMainSceneFbos -> offscreen FBO or
374 //! myMainSceneFbos -> BackBuffer or BackBuffer -> FrontBuffer),
375 //! and redraw immediate structures on top.
377 //! When scene caching is disabled (myTransientDrawToFront, no double buffer in window, etc.),
378 //! the first step (blitting) will be skipped.
380 //! @return false if immediate structures has been rendered directly into FrontBuffer
381 //! and Buffer Swap should not be called.
382 Standard_EXPORT virtual bool redrawImmediate (const Graphic3d_Camera::Projection theProjection,
383 OpenGl_FrameBuffer* theReadFbo,
384 OpenGl_FrameBuffer* theDrawFbo,
385 const Standard_Boolean theIsPartialUpdate = Standard_False);
387 //! Blit image from/to specified buffers.
388 Standard_EXPORT bool blitBuffers (OpenGl_FrameBuffer* theReadFbo,
389 OpenGl_FrameBuffer* theDrawFbo,
390 const Standard_Boolean theToFlip = Standard_False);
392 //! Setup default FBO.
393 Standard_EXPORT void bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo = NULL);
395 protected: //! @name Rendering of GL graphics (with prepared drawing buffer).
397 //! Renders the graphical contents of the view into the preprepared window or framebuffer.
398 //! @param theProjection [in] the projection that should be used for rendering.
399 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
400 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
401 Standard_EXPORT virtual void render (Graphic3d_Camera::Projection theProjection,
402 OpenGl_FrameBuffer* theReadDrawFbo,
403 const Standard_Boolean theToDrawImmediate);
405 //! Renders the graphical scene.
406 //! @param theProjection [in] the projection that is used for rendering.
407 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
408 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
409 Standard_EXPORT virtual void renderScene (Graphic3d_Camera::Projection theProjection,
410 OpenGl_FrameBuffer* theReadDrawFbo,
411 const Standard_Boolean theToDrawImmediate);
413 //! Draw background (gradient / image)
414 Standard_EXPORT virtual void drawBackground (const Handle(OpenGl_Workspace)& theWorkspace);
416 //! Render set of structures presented in the view.
417 //! @param theProjection [in] the projection that is used for rendering.
418 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
419 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
420 Standard_EXPORT virtual void renderStructs (Graphic3d_Camera::Projection theProjection,
421 OpenGl_FrameBuffer* theReadDrawFbo,
422 const Standard_Boolean theToDrawImmediate);
424 //! Renders trihedron.
425 void renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
429 //! Adds the structure to display lists of the view.
430 Standard_EXPORT virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
431 const Standard_Integer thePriority) Standard_OVERRIDE;
433 //! Erases the structure from display lists of the view.
434 Standard_EXPORT virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) Standard_OVERRIDE;
436 //! Change Z layer of a structure already presented in view.
437 Standard_EXPORT virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure,
438 const Graphic3d_ZLayerId theNewLayerId) Standard_OVERRIDE;
440 //! Changes the priority of a structure within its Z layer in the specified view.
441 Standard_EXPORT virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure,
442 const Standard_Integer theNewPriority) Standard_OVERRIDE;
444 //! Returns zoom-scale factor.
445 Standard_EXPORT virtual Standard_Real considerZoomPersistenceObjects (const Graphic3d_ZLayerId theLayerId,
446 const Handle(Graphic3d_Camera)& theCamera,
447 const Standard_Integer theWindowWidth,
448 const Standard_Integer theWindowHeight) const Standard_OVERRIDE;
452 //! Copy content of Back buffer to the Front buffer.
453 void copyBackToFront();
455 //! Initialize blit quad.
456 OpenGl_VertexBuffer* initBlitQuad (const Standard_Boolean theToFlip);
458 //! Blend together views pair into stereo image.
459 void drawStereoPair (OpenGl_FrameBuffer* theDrawFbo);
463 OpenGl_GraphicDriver* myDriver;
464 Handle(OpenGl_Window) myWindow;
465 Handle(OpenGl_Workspace) myWorkspace;
466 Handle(OpenGl_Caps) myCaps;
467 Standard_Boolean& myDeviceLostFlag;
468 Standard_Boolean myWasRedrawnGL;
470 Standard_Boolean myCulling;
471 Graphic3d_TypeOfShadingModel myShadingModel;
472 Graphic3d_TypeOfBackfacingModel myBackfacing;
473 Quantity_ColorRGBA myBgColor;
474 Graphic3d_SequenceOfHClipPlane myClipPlanes;
475 Handle(Graphic3d_Camera) myCamera;
476 Handle(OpenGl_FrameBuffer) myFBO;
477 Standard_Boolean myUseGLLight;
478 Standard_Boolean myToShowTrihedron;
479 Standard_Boolean myToShowGradTrihedron;
480 TCollection_AsciiString myBackgroundImagePath;
481 Handle(Graphic3d_TextureEnv) myTextureEnvData;
482 Graphic3d_GraduatedTrihedron myGTrihedronData;
484 OpenGl_ListOfLight myNoShadingLight;
485 OpenGl_ListOfLight myLights;
486 OpenGl_LayerList myZLayers; //!< main list of displayed structure, sorted by layers
488 Graphic3d_WorldViewProjState myWorldViewProjState; //!< camera modification state
489 OpenGl_StateCounter* myStateCounter;
490 Standard_Size myCurrLightSourceState;
492 typedef std::pair<Standard_Size, Standard_Size> StateInfo;
494 StateInfo myLastOrientationState;
495 StateInfo myLastViewMappingState;
496 StateInfo myLastLightSourceState;
498 //! Is needed for selection of overlapping objects and storage of the current view volume
499 OpenGl_BVHTreeSelector myBVHSelector;
501 OpenGl_Trihedron myTrihedron;
502 OpenGl_GraduatedTrihedron myGraduatedTrihedron;
504 Handle(OpenGl_Texture) myTextureEnv;
506 protected: //! @name Rendering properties
508 //! Two framebuffers (left and right views) store cached main presentation
509 //! of the view (without presentation of immediate layers).
510 GLint myFboColorFormat; //!< sized format for color attachments
511 GLint myFboDepthFormat; //!< sized format for depth-stencil attachments
512 Handle(OpenGl_FrameBuffer) myMainSceneFbos[2];
513 Handle(OpenGl_FrameBuffer) myImmediateSceneFbos[2]; //!< Additional buffers for immediate layer in stereo mode.
514 OpenGl_VertexBuffer myFullScreenQuad; //!< Vertices for full-screen quad rendering.
515 OpenGl_VertexBuffer myFullScreenQuadFlip;
516 Standard_Boolean myToFlipOutput; //!< Flag to draw result image upside-down
517 unsigned int myFrameCounter; //!< redraw counter, for debugging
518 Standard_Boolean myHasFboBlit; //!< disable FBOs on failure
519 Standard_Boolean myToDisableMSAA; //!< disable MSAA after failure
520 Standard_Boolean myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer)
521 Standard_Boolean myBackBufferRestored;
522 Standard_Boolean myIsImmediateDrawn; //!< flag indicates that immediate mode buffer contains some data
524 protected: //! @name Background parameters
526 OpenGl_AspectFace* myTextureParams; //!< Stores texture and its parameters for textured background
527 OpenGl_BackgroundArray* myBgGradientArray; //!< Primitive array for gradient background
528 OpenGl_BackgroundArray* myBgTextureArray; //!< Primitive array for texture background
530 protected: //! @name data types related to ray-tracing
532 //! Result of OpenGL shaders initialization.
533 enum RaytraceInitStatus
540 //! Describes update mode (state).
541 enum RaytraceUpdateMode
543 OpenGl_GUM_CHECK, //!< check geometry state
544 OpenGl_GUM_PREPARE, //!< collect unchanged objects
545 OpenGl_GUM_REBUILD //!< rebuild changed and new objects
548 //! Defines frequently used shader variables.
549 enum ShaderVariableIndex
563 OpenGl_RT_uUnviewMat,
568 OpenGl_RT_uLightAmbnt,
569 OpenGl_RT_uLightCount,
572 OpenGl_RT_uBackColorTop,
573 OpenGl_RT_uBackColorBot,
575 // ray-tracing params
576 OpenGl_RT_uShadowsEnabled,
577 OpenGl_RT_uReflectEnabled,
578 OpenGl_RT_uSphereMapEnabled,
579 OpenGl_RT_uSphereMapForBack,
580 OpenGl_RT_uTexSamplersArray,
581 OpenGl_RT_uBlockedRngEnabled,
583 // sampled frame params
584 OpenGl_RT_uSampleWeight,
585 OpenGl_RT_uFrameRndSeed,
587 // adaptive FSAA params
592 OpenGl_RT_NbVariables // special field
595 //! Defines texture samplers.
596 enum ShaderSamplerNames
598 OpenGl_RT_SceneNodeInfoTexture = 0,
599 OpenGl_RT_SceneMinPointTexture = 1,
600 OpenGl_RT_SceneMaxPointTexture = 2,
601 OpenGl_RT_SceneTransformTexture = 3,
603 OpenGl_RT_GeometryVertexTexture = 4,
604 OpenGl_RT_GeometryNormalTexture = 5,
605 OpenGl_RT_GeometryTexCrdTexture = 6,
606 OpenGl_RT_GeometryTriangTexture = 7,
608 OpenGl_RT_EnvironmentMapTexture = 8,
610 OpenGl_RT_RaytraceMaterialTexture = 9,
611 OpenGl_RT_RaytraceLightSrcTexture = 10,
613 OpenGl_RT_FsaaInputTexture = 11,
614 OpenGl_RT_PrevAccumTexture = 12,
615 OpenGl_RT_DepthTexture = 13,
617 OpenGl_RT_OpenGlColorTexture = 14,
618 OpenGl_RT_OpenGlDepthTexture = 15
621 //! Tool class for management of shader sources.
626 //! Default shader prefix - empty string.
627 static const TCollection_AsciiString EMPTY_PREFIX;
629 //! Creates new uninitialized shader source.
637 //! Returns error description in case of load fail.
638 const TCollection_AsciiString& ErrorDescription() const
643 //! Returns prefix to insert before the source.
644 const TCollection_AsciiString& Prefix() const
649 //! Sets prefix to insert before the source.
650 void SetPrefix (const TCollection_AsciiString& thePrefix)
652 myPrefix = thePrefix;
655 //! Returns shader source combined with prefix.
656 TCollection_AsciiString Source() const;
658 //! Loads shader source from specified files.
659 Standard_Boolean Load (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
663 TCollection_AsciiString mySource; //!< Source string of the shader object
664 TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
665 TCollection_AsciiString myError; //!< error state
669 //! Default ray-tracing depth.
670 static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
672 //! Default size of traversal stack.
673 static const Standard_Integer THE_DEFAULT_STACK_SIZE = 10;
675 //! Compile-time ray-tracing parameters.
676 struct RaytracingParams
678 //! Actual size of traversal stack in shader program.
679 Standard_Integer StackSize;
681 //! Actual ray-tracing depth (number of ray bounces).
682 Standard_Integer NbBounces;
684 //! Enables/disables light propagation through transparent media.
685 Standard_Boolean TransparentShadows;
687 //! Enables/disables global illumination (GI) effects.
688 Standard_Boolean GlobalIllumination;
690 //! Enables/disables the use of OpenGL bindless textures.
691 Standard_Boolean UseBindlessTextures;
693 //! Creates default compile-time ray-tracing parameters.
695 : StackSize (THE_DEFAULT_STACK_SIZE),
696 NbBounces (THE_DEFAULT_NB_BOUNCES),
697 TransparentShadows (Standard_False),
698 GlobalIllumination (Standard_False),
699 UseBindlessTextures (Standard_False)
705 //! Describes state of OpenGL structure.
708 Standard_Size StructureState;
709 Standard_Size InstancedState;
711 //! Creates new structure state.
712 StructState (const Standard_Size theStructureState = 0,
713 const Standard_Size theInstancedState = 0)
714 : StructureState (theStructureState),
715 InstancedState (theInstancedState)
720 //! Creates new structure state.
721 StructState (const OpenGl_Structure* theStructure)
723 StructureState = theStructure->ModificationState();
725 InstancedState = theStructure->InstancedStructure() != NULL ?
726 theStructure->InstancedStructure()->ModificationState() : 0;
730 protected: //! @name methods related to ray-tracing
732 //! Updates 3D scene geometry for ray-tracing.
733 Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode theMode,
734 const Standard_Integer theViewId,
735 const Handle(OpenGl_Context)& theGlContext);
737 //! Updates 3D scene light sources for ray-tracing.
738 Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
740 //! Updates environment map for ray-tracing.
741 Standard_Boolean updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext);
743 //! Checks to see if the OpenGL structure is modified.
744 Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
746 //! Adds OpenGL structure to ray-traced scene geometry.
747 Standard_Boolean addRaytraceStructure (const OpenGl_Structure* theStructure,
748 const Handle(OpenGl_Context)& theGlContext);
750 //! Adds OpenGL groups to ray-traced scene geometry.
751 Standard_Boolean addRaytraceGroups (const OpenGl_Structure* theStructure,
752 const OpenGl_RaytraceMaterial& theStructMat,
753 const Graphic3d_Mat4* theTransform,
754 const Handle(OpenGl_Context)& theGlContext);
756 //! Creates ray-tracing material properties.
757 OpenGl_RaytraceMaterial convertMaterial (const OpenGl_AspectFace* theAspect,
758 const Handle(OpenGl_Context)& theGlContext);
760 //! Adds OpenGL primitive array to ray-traced scene geometry.
761 OpenGl_TriangleSet* addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
762 const Standard_Integer theMatID,
763 const OpenGl_Mat4* theTrans);
765 //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
766 Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
767 const Standard_Integer theMatID,
768 const Standard_Integer theCount,
769 const Standard_Integer theOffset,
770 const OpenGl_PrimitiveArray& theArray);
772 //! Adds OpenGL triangle array to ray-traced scene geometry.
773 Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
774 const Standard_Integer theMatID,
775 const Standard_Integer theCount,
776 const Standard_Integer theOffset,
777 const Handle(Graphic3d_IndexBuffer)& theIndices);
779 //! Adds OpenGL triangle fan array to ray-traced scene geometry.
780 Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
781 const Standard_Integer theMatID,
782 const Standard_Integer theCount,
783 const Standard_Integer theOffset,
784 const Handle(Graphic3d_IndexBuffer)& theIndices);
786 //! Adds OpenGL triangle strip array to ray-traced scene geometry.
787 Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
788 const Standard_Integer theMatID,
789 const Standard_Integer theCount,
790 const Standard_Integer theOffset,
791 const Handle(Graphic3d_IndexBuffer)& theIndices);
793 //! Adds OpenGL quadrangle array to ray-traced scene geometry.
794 Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
795 const Standard_Integer theMatID,
796 const Standard_Integer theCount,
797 const Standard_Integer theOffset,
798 const Handle(Graphic3d_IndexBuffer)& theIndices);
800 //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
801 Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
802 const Standard_Integer theMatID,
803 const Standard_Integer theCount,
804 const Standard_Integer theOffset,
805 const Handle(Graphic3d_IndexBuffer)& theIndices);
807 //! Adds OpenGL polygon array to ray-traced scene geometry.
808 Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
809 const Standard_Integer theMatID,
810 const Standard_Integer theCount,
811 const Standard_Integer theOffset,
812 const Handle(Graphic3d_IndexBuffer)& theIndices);
814 //! Uploads ray-trace data to the GPU.
815 Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
817 //! Generates shader prefix based on current ray-tracing options.
818 TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
820 //! Performs safe exit when shaders initialization fails.
821 Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
822 const Handle(OpenGl_Context)& theGlContext);
824 //! Loads and compiles shader object from specified source.
825 Handle(OpenGl_ShaderObject) initShader (const GLenum theType,
826 const ShaderSource& theSource,
827 const Handle(OpenGl_Context)& theGlContext);
829 //! Creates shader program from the given vertex and fragment shaders.
830 Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)& theGlContext,
831 const Handle(OpenGl_ShaderObject)& theVertShader,
832 const Handle(OpenGl_ShaderObject)& theFragShader);
834 //! Initializes OpenGL/GLSL shader programs.
835 Standard_Boolean initRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
837 //! Releases OpenGL/GLSL shader programs.
838 void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
840 //! Updates auxiliary OpenGL frame buffers.
841 Standard_Boolean updateRaytraceBuffers (const Standard_Integer theSizeX,
842 const Standard_Integer theSizeY,
843 const Handle(OpenGl_Context)& theGlContext);
845 //! Generates viewing rays for corners of screen quad.
846 void updateCamera (const OpenGl_Mat4& theOrientation,
847 const OpenGl_Mat4& theViewMapping,
848 OpenGl_Vec3* theOrigins,
849 OpenGl_Vec3* theDirects,
850 OpenGl_Mat4& theView,
851 OpenGl_Mat4& theUnView);
853 //! Binds ray-trace textures to corresponding texture units.
854 void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
856 //! Unbinds ray-trace textures from corresponding texture unit.
857 void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
859 //! Sets uniform state for the given ray-tracing shader program.
860 Standard_Boolean setUniformState (const OpenGl_Vec3* theOrigins,
861 const OpenGl_Vec3* theDirects,
862 const OpenGl_Mat4& theViewMat,
863 const OpenGl_Mat4& theUnviewMat,
864 const Standard_Integer theProgramId,
865 const Handle(OpenGl_Context)& theGlContext);
867 //! Runs ray-tracing shader programs.
868 Standard_Boolean runRaytraceShaders (const Standard_Integer theSizeX,
869 const Standard_Integer theSizeY,
870 const OpenGl_Vec3* theOrigins,
871 const OpenGl_Vec3* theDirects,
872 const OpenGl_Mat4& theViewMat,
873 const OpenGl_Mat4& theUnviewMat,
874 Graphic3d_Camera::Projection theProjection,
875 OpenGl_FrameBuffer* theReadDrawFbo,
876 const Handle(OpenGl_Context)& theGlContext);
878 //! Redraws the window using OpenGL/GLSL ray-tracing.
879 Standard_Boolean raytrace (const Standard_Integer theSizeX,
880 const Standard_Integer theSizeY,
881 Graphic3d_Camera::Projection theProjection,
882 OpenGl_FrameBuffer* theReadDrawFbo,
883 const Handle(OpenGl_Context)& theGlContext);
885 protected: //! @name fields related to ray-tracing
887 //! Result of shaders initialization.
888 RaytraceInitStatus myRaytraceInitStatus;
890 //! Is geometry data valid?
891 Standard_Boolean myIsRaytraceDataValid;
893 //! Warning about missing extension GL_ARB_bindless_texture has been displayed?
894 Standard_Boolean myIsRaytraceWarnTextures;
896 //! 3D scene geometry data for ray-tracing.
897 OpenGl_RaytraceGeometry myRaytraceGeometry;
899 //! Compile-time ray-tracing parameters.
900 RaytracingParams myRaytraceParameters;
902 //! Radius of bounding sphere of the scene.
903 Standard_ShortReal myRaytraceSceneRadius;
904 //! Scene epsilon to prevent self-intersections.
905 Standard_ShortReal myRaytraceSceneEpsilon;
907 //! OpenGL/GLSL source of ray-tracing fragment shader.
908 ShaderSource myRaytraceShaderSource;
909 //! OpenGL/GLSL source of adaptive-AA fragment shader.
910 ShaderSource myPostFSAAShaderSource;
912 //! OpenGL/GLSL ray-tracing fragment shader.
913 Handle(OpenGl_ShaderObject) myRaytraceShader;
914 //! OpenGL/GLSL adaptive-AA fragment shader.
915 Handle(OpenGl_ShaderObject) myPostFSAAShader;
917 //! OpenGL/GLSL ray-tracing shader program.
918 Handle(OpenGl_ShaderProgram) myRaytraceProgram;
919 //! OpenGL/GLSL adaptive-AA shader program.
920 Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
921 //! OpenGL/GLSL program for displaying texture.
922 Handle(OpenGl_ShaderProgram) myOutImageProgram;
924 //! Texture buffer of data records of bottom-level BVH nodes.
925 Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
926 //! Texture buffer of minimum points of bottom-level BVH nodes.
927 Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
928 //! Texture buffer of maximum points of bottom-level BVH nodes.
929 Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
930 //! Texture buffer of transformations of high-level BVH nodes.
931 Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
933 //! Texture buffer of vertex coords.
934 Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
935 //! Texture buffer of vertex normals.
936 Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
937 //! Texture buffer of vertex UV coords.
938 Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
939 //! Texture buffer of triangle indices.
940 Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
942 //! Texture buffer of material properties.
943 Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
944 //! Texture buffer of light source properties.
945 Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
947 //! 1st framebuffer (FBO) to perform adaptive FSAA.
948 Handle(OpenGl_FrameBuffer) myRaytraceFBO1[2];
949 //! 2nd framebuffer (FBO) to perform adaptive FSAA.
950 Handle(OpenGl_FrameBuffer) myRaytraceFBO2[2];
951 //! Framebuffer (FBO) for preliminary OpenGL output.
952 Handle(OpenGl_FrameBuffer) myOpenGlFBO;
953 Handle(OpenGl_FrameBuffer) myOpenGlFBO2;
955 //! Vertex buffer (VBO) for drawing dummy quad.
956 OpenGl_VertexBuffer myRaytraceScreenQuad;
958 //! Cached locations of frequently used uniform variables.
959 Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
961 //! State of OpenGL structures reflected to ray-tracing.
962 std::map<const OpenGl_Structure*, StructState> myStructureStates;
964 //! PrimitiveArray to TriangleSet map for scene partial update.
965 std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
967 //! Set of IDs of non-raytracable elements (to detect updates).
968 std::set<Standard_Integer> myNonRaytraceStructureIDs;
970 //! Render filter to filter out all raytracable structures.
971 Handle(OpenGl_RaytraceFilter) myRaytraceFilter;
973 //! Marks if environment map should be updated.
974 Standard_Boolean myToUpdateEnvironmentMap;
976 //! State of OpenGL layer list.
977 Standard_Size myLayerListState;
979 //! Number of accumulated frames (for progressive rendering).
980 Standard_Integer myAccumFrames;
982 //! Stored ray origins used for detection of camera movements.
983 OpenGl_Vec3 myPreviousOrigins[3];
985 //! Bullard RNG to produce random sequence.
986 math_BullardGenerator myRNG;
990 DEFINE_STANDARD_ALLOC
991 DEFINE_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView) // Type definition
993 friend class OpenGl_GraphicDriver;
994 friend class OpenGl_Workspace;
997 #endif // _OpenGl_View_Header