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 <InterfaceGraphic_Graphic3d.hxx>
33 #include <Graphic3d_CView.hxx>
34 #include <Graphic3d_GraduatedTrihedron.hxx>
35 #include <Graphic3d_SequenceOfHClipPlane.hxx>
36 #include <Graphic3d_TypeOfShadingModel.hxx>
37 #include <Graphic3d_TypeOfSurfaceDetail.hxx>
38 #include <Graphic3d_WorldViewProjState.hxx>
39 #include <Graphic3d_ZLayerSettings.hxx>
41 #include <OpenGl_AspectFace.hxx>
42 #include <OpenGl_BackgroundArray.hxx>
43 #include <OpenGl_BVHTreeSelector.hxx>
44 #include <OpenGl_Context.hxx>
45 #include <OpenGl_FrameBuffer.hxx>
46 #include <OpenGl_GraduatedTrihedron.hxx>
47 #include <OpenGl_LayerList.hxx>
48 #include <OpenGl_Light.hxx>
49 #include <OpenGl_LineAttributes.hxx>
50 #include <OpenGl_SceneGeometry.hxx>
51 #include <OpenGl_Structure.hxx>
52 #include <OpenGl_Trihedron.hxx>
53 #include <OpenGl_Window.hxx>
54 #include <OpenGl_Workspace.hxx>
62 Standard_Boolean IsOn;
63 Standard_ShortReal Limit; /* in the range [0., 1.] */
66 Standard_Boolean IsOn;
67 Standard_ShortReal Limit; /* in the range [0., 1.] */
73 Standard_Boolean IsOn;
74 Standard_ShortReal Front; /* in the range [0., 1.] */
75 Standard_ShortReal Back; /* in the range [0., 1.] */
81 class Graphic3d_StructureManager;
82 class OpenGl_GraphicDriver;
83 class OpenGl_StateCounter;
84 class OpenGl_RaytraceMaterial;
85 class OpenGl_TriangleSet;
86 class OpenGl_Workspace;
88 DEFINE_STANDARD_HANDLE(OpenGl_View,Graphic3d_CView)
90 //! Implementation of OpenGl view.
91 class OpenGl_View : public Graphic3d_CView
97 Standard_EXPORT OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
98 const Handle(OpenGl_GraphicDriver)& theDriver,
99 const Handle(OpenGl_Caps)& theCaps,
100 Standard_Boolean& theDeviceLostFlag,
101 OpenGl_StateCounter* theCounter);
103 //! Default destructor.
104 Standard_EXPORT virtual ~OpenGl_View();
106 Standard_EXPORT void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx);
108 //! Deletes and erases the view.
109 Standard_EXPORT virtual void Remove() Standard_OVERRIDE;
111 //! @param theDrawToFrontBuffer Advanced option to modify rendering mode:
112 //! 1. TRUE. Drawing immediate mode structures directly to the front buffer over the scene image.
113 //! Fast, so preferred for interactive work (used by default).
114 //! However these extra drawings will be missed in image dump since it is performed from back buffer.
115 //! Notice that since no pre-buffering used the V-Sync will be ignored and rendering could be seen
116 //! in run-time (in case of slow hardware) and/or tearing may appear.
117 //! So this is strongly recommended to draw only simple (fast) structures.
118 //! 2. FALSE. Drawing immediate mode structures to the back buffer.
119 //! The complete scene is redrawn first, so this mode is slower if scene contains complex data and/or V-Sync
120 //! is turned on. But it works in any case and is especially useful for view dump because the dump image is read
121 //! from the back buffer.
122 //! @return previous mode.
123 Standard_EXPORT Standard_Boolean SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer) Standard_OVERRIDE;
125 //! Creates and maps rendering window to the view.
126 //! @param theWindow [in] the window.
127 //! @param theContext [in] the rendering context. If NULL the context will be created internally.
128 Standard_EXPORT virtual void SetWindow (const Handle(Aspect_Window)& theWindow,
129 const Aspect_RenderingContext theContext) Standard_OVERRIDE;
131 //! Returns window associated with the view.
132 virtual Handle(Aspect_Window) Window() const Standard_OVERRIDE { return myWindow->PlatformWindow(); }
134 //! Returns True if the window associated to the view is defined.
135 virtual Standard_Boolean IsDefined() const { return !myWindow.IsNull(); }
137 //! Handle changing size of the rendering window.
138 Standard_EXPORT virtual void Resized() Standard_OVERRIDE;
140 //! Redraw content of the view.
141 Standard_EXPORT virtual void Redraw() Standard_OVERRIDE;
143 //! Redraw immediate content of the view.
144 Standard_EXPORT virtual void RedrawImmediate() Standard_OVERRIDE;
146 //! Marks BVH tree for given priority list as dirty and marks primitive set for rebuild.
147 Standard_EXPORT virtual void Invalidate() Standard_OVERRIDE;
149 //! Return true if view content cache has been invalidated.
150 virtual Standard_Boolean IsInvalidated() Standard_OVERRIDE { return myBackBufferRestored; }
152 //! Displays z-buffer trihedron.
153 Standard_EXPORT virtual void TriedronDisplay (const Aspect_TypeOfTriedronPosition thePosition = Aspect_TOTP_CENTER,
154 const Quantity_NameOfColor theColor = Quantity_NOC_WHITE,
155 const Standard_Real theScale = 0.02,
156 const Standard_Boolean theAsWireframe = Standard_True) Standard_OVERRIDE;
158 //! Erases z-buffer trihedron.
159 Standard_EXPORT virtual void TriedronErase() Standard_OVERRIDE;
161 //! Setup parameters of z-buffer trihedron.
162 Standard_EXPORT virtual void ZBufferTriedronSetup (const Quantity_NameOfColor theXColor = Quantity_NOC_RED,
163 const Quantity_NameOfColor theYColor = Quantity_NOC_GREEN,
164 const Quantity_NameOfColor theZColor = Quantity_NOC_BLUE1,
165 const Standard_Real theSizeRatio = 0.8,
166 const Standard_Real theAxisDiametr = 0.05,
167 const Standard_Integer theNbFacettes = 12) Standard_OVERRIDE;
169 //! Displays trihedron echo.
170 Standard_EXPORT virtual void TriedronEcho (const Aspect_TypeOfTriedronEcho theType = Aspect_TOTE_NONE) Standard_OVERRIDE;
172 //! Returns data of a graduated trihedron
173 const Graphic3d_GraduatedTrihedron& GetGraduatedTrihedron() { return myGTrihedronData; }
175 //! Displays Graduated Trihedron.
176 Standard_EXPORT virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) Standard_OVERRIDE;
178 //! Erases Graduated Trihedron.
179 Standard_EXPORT virtual void GraduatedTrihedronErase() Standard_OVERRIDE;
181 //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object.
182 //! @param theMin [in] the minimum point of scene.
183 //! @param theMax [in] the maximum point of scene.
184 Standard_EXPORT virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) Standard_OVERRIDE;
186 //! Reads depths of shown pixels of the given rectangle.
187 Standard_EXPORT virtual void ReadDepths (const Standard_Integer theX,
188 const Standard_Integer theY,
189 const Standard_Integer theWidth,
190 const Standard_Integer theHeight,
191 const Standard_Address theBuffer) const Standard_OVERRIDE;
193 //! Dump active rendering buffer into specified memory buffer.
194 Standard_EXPORT virtual Standard_Boolean BufferDump (Image_PixMap& theImage,
195 const Graphic3d_BufferType& theBufferType) Standard_OVERRIDE;
197 //! Print the contents of the view to the printer.
198 //! @param thePrinterDC pass the PrinterDeviceContext (HDC)
199 //! @param theToShowBackground when set to FALSE then print the view without background
200 //! color (background is white) else set to TRUE for printing
201 //! with current background color
202 //! @param theFileName if != NULL, then the view will be printed to a file
203 //! @param thePrintAlgorithm select print algorithm: stretch, tile
204 //! @param theScaleFactor scaling coefficient, used internally to scale the printings
205 //! accordingly to the scale factor selected in the printer properties dialog
206 //! @return Standard_True if the data is passed to the printer, otherwise Standard_False if
207 //! the print operation failed due to the printer errors, or lack of system memory. This might be related
208 //! to insufficient memory or some internal errors.
209 //! All this errors are indicated by the message boxes (on level of OpenGl_GraphicDriver).
210 //! Warning: This function can reuse FBO assigned to the view, please take it into account
211 //! if you use it for your purposes.
212 Standard_EXPORT virtual Standard_Boolean Print (const Aspect_Handle thePrinterDC,
213 const Standard_Boolean theToShowBackground,
214 const Standard_CString theFileName,
215 const Aspect_PrintAlgo thePrintAlgorithm = Aspect_PA_STRETCH,
216 const Standard_Real theScaleFactor = 1.0) Standard_OVERRIDE;
218 //! Export scene into the one of the Vector graphics formats (SVG, PS, PDF...).
219 //! In contrast to Bitmaps, Vector graphics is scalable (so you may got quality benefits
220 //! on printing to laser printer). Notice however that results may differ a lot and
221 //! do not contain some elements.
222 Standard_EXPORT virtual Standard_Boolean Export (const Standard_CString theFileName,
223 const Graphic3d_ExportFormat theFormat,
224 const Graphic3d_SortType theSortType = Graphic3d_ST_BSP_Tree) Standard_OVERRIDE;
226 //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated.
227 Standard_EXPORT virtual void InvalidateBVHData (const Standard_Integer theLayerId) Standard_OVERRIDE;
229 //! Insert a new top-level z layer with the given ID.
230 Standard_EXPORT virtual void AddZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
232 //! Remove a z layer with the given ID.
233 Standard_EXPORT virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
235 //! Sets the settings for a single Z layer of specified view.
236 Standard_EXPORT virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
237 const Graphic3d_ZLayerSettings& theSettings) Standard_OVERRIDE;
239 //! Returns pointer to an assigned framebuffer object.
240 Standard_EXPORT virtual Graphic3d_PtrFrameBuffer FBO() const Standard_OVERRIDE;
242 //! Sets framebuffer object for offscreen rendering.
243 Standard_EXPORT virtual void SetFBO (const Graphic3d_PtrFrameBuffer theFBO) Standard_OVERRIDE;
245 //! Generate offscreen FBO in the graphic library.
246 //! If not supported on hardware returns NULL.
247 Standard_EXPORT virtual Graphic3d_PtrFrameBuffer FBOCreate (const Standard_Integer theWidth,
248 const Standard_Integer theHeight) Standard_OVERRIDE;
250 //! Remove offscreen FBO from the graphic library
251 Standard_EXPORT virtual void FBORelease (Graphic3d_PtrFrameBuffer& theFBOPtr) Standard_OVERRIDE;
253 //! Read offscreen FBO configuration.
254 Standard_EXPORT virtual void FBOGetDimensions (const Graphic3d_PtrFrameBuffer theFBOPtr,
255 Standard_Integer& theWidth,
256 Standard_Integer& theHeight,
257 Standard_Integer& theWidthMax,
258 Standard_Integer& theHeightMax) Standard_OVERRIDE;
260 //! Change offscreen FBO viewport.
261 Standard_EXPORT virtual void FBOChangeViewport (Graphic3d_PtrFrameBuffer& theFBOPtr,
262 const Standard_Integer theWidth,
263 const Standard_Integer theHeight) Standard_OVERRIDE;
267 //! Returns true if anti-aliasing is enabled for the view.
268 Standard_Boolean virtual IsAntialiasingEnabled() const Standard_OVERRIDE { return myAntiAliasing; }
270 //! Enable or disable anti-aliasing in the view.
271 virtual void SetAntialiasingEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myAntiAliasing = theIsEnabled; }
273 //! Returns background fill color.
274 Standard_EXPORT virtual Aspect_Background Background() const Standard_OVERRIDE;
276 //! Sets background fill color.
277 Standard_EXPORT virtual void SetBackground (const Aspect_Background& theBackground) Standard_OVERRIDE;
279 //! Returns gradient background fill colors.
280 Standard_EXPORT virtual Aspect_GradientBackground GradientBackground() const Standard_OVERRIDE;
282 //! Sets gradient background fill colors.
283 Standard_EXPORT virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) Standard_OVERRIDE;
285 //! Returns background image texture file path.
286 Standard_EXPORT virtual TCollection_AsciiString BackgroundImage() Standard_OVERRIDE { return myBackgroundImagePath; }
288 //! Sets background image texture file path.
289 Standard_EXPORT virtual void SetBackgroundImage (const TCollection_AsciiString& theFilePath) Standard_OVERRIDE;
291 //! Returns background image fill style.
292 Standard_EXPORT virtual Aspect_FillMethod BackgroundImageStyle() const Standard_OVERRIDE;
294 //! Sets background image fill style.
295 Standard_EXPORT virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) Standard_OVERRIDE;
297 //! Returns environment texture set for the view.
298 Standard_EXPORT virtual Handle(Graphic3d_TextureEnv) TextureEnv() const Standard_OVERRIDE { return myTextureEnvData; }
300 //! Sets environment texture for the view.
301 Standard_EXPORT virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) Standard_OVERRIDE;
303 //! Returns the state of frustum culling optimization.
304 virtual Standard_Boolean IsCullingEnabled() const Standard_OVERRIDE { return myCulling; }
306 //! Enables or disables frustum culling optimization.
307 virtual void SetCullingEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myCulling = theIsEnabled; }
309 //! Returns shading model of the view.
310 virtual Graphic3d_TypeOfShadingModel ShadingModel() const Standard_OVERRIDE { return myShadingModel; }
312 //! Sets shading model of the view.
313 virtual void SetShadingModel (const Graphic3d_TypeOfShadingModel theModel) Standard_OVERRIDE { myShadingModel = theModel; }
315 //! Returns surface detail type of the view.
316 virtual Graphic3d_TypeOfSurfaceDetail SurfaceDetailType() const Standard_OVERRIDE { return mySurfaceDetail; }
318 //! Sets surface detail type of the view.
319 virtual void SetSurfaceDetailType (const Graphic3d_TypeOfSurfaceDetail theType) Standard_OVERRIDE
321 mySurfaceDetail = theType;
322 myToUpdateEnvironmentMap = Standard_True;
325 //! Return backfacing model used for the view.
326 virtual Graphic3d_TypeOfBackfacingModel BackfacingModel() const Standard_OVERRIDE { return myBackfacing; }
328 //! Sets backfacing model for the view.
329 virtual void SetBackfacingModel (const Graphic3d_TypeOfBackfacingModel theModel) Standard_OVERRIDE { myBackfacing = theModel; }
331 //! Returns camera object of the view.
332 virtual const Handle(Graphic3d_Camera)& Camera() const Standard_OVERRIDE { return myCamera; }
334 //! Sets camera used by the view.
335 virtual void SetCamera (const Handle(Graphic3d_Camera)& theCamera) Standard_OVERRIDE { myCamera = theCamera; }
337 //! Returns the activity of back z-clipping plane.
338 virtual Standard_Boolean BackZClippingIsOn() const Standard_OVERRIDE { return myZClip.Back.IsOn; }
340 //! Activates the back Z-clipping plane.
341 virtual void SetBackZClippingOn (const Standard_Boolean theIsOn) Standard_OVERRIDE { myZClip.Back.IsOn = theIsOn; }
343 //! Returns the definition of the back Z-clipping plane.
344 virtual Standard_Real ZClippingBackPlane() const Standard_OVERRIDE { return myZClip.Back.Limit; }
346 //! Sets the definition of the back Z-clipping plane.
347 virtual void SetZClippingBackPlane (const Standard_Real theValue) Standard_OVERRIDE
349 myZClip.Back.Limit = static_cast<Standard_ShortReal> (theValue);
352 //! Returns the activity of front z-clipping plane.
353 virtual Standard_Boolean FrontZClippingIsOn() const Standard_OVERRIDE { return myZClip.Front.IsOn; }
355 //! Activates the front Z-clipping plane.
356 virtual void SetFrontZClippingOn (const Standard_Boolean theIsOn) Standard_OVERRIDE{ myZClip.Front.IsOn = theIsOn; }
358 //! Returns the definition of the front Z-clipping plane.
359 virtual Standard_Real ZClippingFrontPlane() const Standard_OVERRIDE { return myZClip.Front.Limit; }
361 //! Sets the definition of the front Z-clipping plane.
362 virtual void SetZClippingFrontPlane (const Standard_Real theValue) Standard_OVERRIDE
364 myZClip.Front.Limit = static_cast<Standard_ShortReal> (theValue);
367 //! Returns the activity of depth cueing.
368 virtual Standard_Boolean DepthCueingIsOn() const Standard_OVERRIDE { return myFog.IsOn; }
370 //! Sets the activity of depth cueing.
371 virtual void SetDepthCueingOn (const Standard_Boolean theIsOn) Standard_OVERRIDE { myFog.IsOn = theIsOn; }
373 //! Returns the back depth cueing plane.
374 virtual Standard_Real DepthCueingBackPlane() const Standard_OVERRIDE { return myFog.Back; }
376 //! Set the back depth cueing plane.
377 virtual void SetDepthCueingBackPlane (const Standard_Real theValue) Standard_OVERRIDE
379 myFog.Back = static_cast<Standard_ShortReal> (theValue);
382 //! Returns the front depth cueing plane.
383 virtual Standard_Real DepthCueingFrontPlane() const Standard_OVERRIDE { return myFog.Front; }
385 //! Set the front depth cueing plane.
386 virtual void SetDepthCueingFrontPlane (const Standard_Real theValue) Standard_OVERRIDE
388 myFog.Front = static_cast<Standard_ShortReal> (theValue);
391 //! Returns true if GL lighting is enabled.
392 virtual Standard_Boolean IsGLLightEnabled() const Standard_OVERRIDE { return myUseGLLight; }
394 //! Sets GL lighting enabled or disable state.
395 virtual void SetGLLightEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myUseGLLight = theIsEnabled; }
397 //! Returns list of lights of the view.
398 virtual const Graphic3d_ListOfCLight& Lights() const Standard_OVERRIDE { return myLights; }
400 //! Sets list of lights for the view.
401 virtual void SetLights (const Graphic3d_ListOfCLight& theLights) Standard_OVERRIDE
403 myLights = theLights;
404 myCurrLightSourceState = myStateCounter->Increment();
407 //! Returns list of clip planes set for the view.
408 virtual const Graphic3d_SequenceOfHClipPlane& ClipPlanes() const Standard_OVERRIDE { return myClipPlanes; }
410 //! Sets list of clip planes for the view.
411 virtual void SetClipPlanes (const Graphic3d_SequenceOfHClipPlane& thePlanes) Standard_OVERRIDE { myClipPlanes = thePlanes; }
415 //! Returns background color.
416 const TEL_COLOUR& BackgroundColor() const { return myBgColor; }
418 //! Change trihedron.
419 OpenGl_Trihedron& ChangeTrihedron() { return myTrihedron; }
421 //! Change graduated trihedron.
422 OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
424 void SetTextureEnv (const Handle(OpenGl_Context)& theCtx,
425 const Handle(Graphic3d_TextureEnv)& theTexture);
427 //! Returns height of view volume.
428 Standard_Real Height () const { return myCamera->ViewDimensions().X(); }
430 //! Returns width of view volume.
431 Standard_Real Width () const { return myCamera->ViewDimensions().Y(); }
433 void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
435 void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
437 void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
439 //! Returns list of OpenGL Z-layers.
440 const OpenGl_LayerList& LayerList() const { return myZLayers; }
442 //! Returns list of openGL light sources.
443 const OpenGl_ListOfLight& LightList() const { return myLights; }
445 //! Returns OpenGL window implementation.
446 const Handle(OpenGl_Window) GlWindow() const { return myWindow; }
448 //! Returns OpenGL environment map.
449 const Handle(OpenGl_Texture)& GlTextureEnv() const { return myTextureEnv; }
451 //! Returns selector for BVH tree, providing a possibility to store information
452 //! about current view volume and to detect which objects are overlapping it.
453 OpenGl_BVHTreeSelector& BVHTreeSelector() { return myBVHSelector; }
455 //! Returns true if there are immediate structures to display
456 bool HasImmediateStructures() const
458 return myZLayers.NbImmediateStructures() != 0;
461 protected: //! @name Internal methods for managing GL resources
463 //! Initializes OpenGl resource for environment texture.
464 void initTextureEnv (const Handle(OpenGl_Context)& theContext);
466 protected: //! @name low-level redrawing sub-routines
468 //! Redraws view for the given monographic camera projection, or left/right eye.
469 Standard_EXPORT virtual void redraw (const Graphic3d_Camera::Projection theProjection,
470 OpenGl_FrameBuffer* theReadDrawFbo);
472 //! Redraws view for the given monographic camera projection, or left/right eye.
474 //! Method will blit snapshot containing main scene (myMainSceneFbos or BackBuffer)
475 //! into presentation buffer (myMainSceneFbos -> offscreen FBO or
476 //! myMainSceneFbos -> BackBuffer or BackBuffer -> FrontBuffer),
477 //! and redraw immediate structures on top.
479 //! When scene caching is disabled (myTransientDrawToFront, no double buffer in window, etc.),
480 //! the first step (blitting) will be skipped.
482 //! @return false if immediate structures has been rendered directly into FrontBuffer
483 //! and Buffer Swap should not be called.
484 Standard_EXPORT virtual bool redrawImmediate (const Graphic3d_Camera::Projection theProjection,
485 OpenGl_FrameBuffer* theReadFbo,
486 OpenGl_FrameBuffer* theDrawFbo,
487 const Standard_Boolean theIsPartialUpdate = Standard_False);
489 //! Blit image from/to specified buffers.
490 Standard_EXPORT bool blitBuffers (OpenGl_FrameBuffer* theReadFbo,
491 OpenGl_FrameBuffer* theDrawFbo,
492 const Standard_Boolean theToFlip = Standard_False);
494 //! Setup default FBO.
495 Standard_EXPORT void bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo = NULL);
497 protected: //! @name Rendering of GL graphics (with prepared drawing buffer).
499 //! Renders the graphical contents of the view into the preprepared window or framebuffer.
500 //! @param theProjection [in] the projection that should be used for rendering.
501 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
502 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
503 Standard_EXPORT virtual void render (Graphic3d_Camera::Projection theProjection,
504 OpenGl_FrameBuffer* theReadDrawFbo,
505 const Standard_Boolean theToDrawImmediate);
507 //! Renders the graphical scene.
508 //! @param theProjection [in] the projection that is used for rendering.
509 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
510 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
511 Standard_EXPORT virtual void renderScene (Graphic3d_Camera::Projection theProjection,
512 OpenGl_FrameBuffer* theReadDrawFbo,
513 const Standard_Boolean theToDrawImmediate);
515 //! Draw background (gradient / image)
516 Standard_EXPORT virtual void drawBackground (const Handle(OpenGl_Workspace)& theWorkspace);
518 //! Render set of structures presented in the view.
519 //! @param theProjection [in] the projection that is used for rendering.
520 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
521 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
522 Standard_EXPORT virtual void renderStructs (Graphic3d_Camera::Projection theProjection,
523 OpenGl_FrameBuffer* theReadDrawFbo,
524 const Standard_Boolean theToDrawImmediate);
526 //! Renders trihedron.
527 void renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
531 //! Adds the structure to display lists of the view.
532 Standard_EXPORT virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
533 const Standard_Integer thePriority) Standard_OVERRIDE;
535 //! Erases the structure from display lists of the view.
536 Standard_EXPORT virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) Standard_OVERRIDE;
538 //! Change Z layer of a structure already presented in view.
539 Standard_EXPORT virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure,
540 const Graphic3d_ZLayerId theNewLayerId) Standard_OVERRIDE;
542 //! Changes the priority of a structure within its Z layer in the specified view.
543 Standard_EXPORT virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure,
544 const Standard_Integer theNewPriority) Standard_OVERRIDE;
548 //! Copy content of Back buffer to the Front buffer.
549 void copyBackToFront();
551 //! Initialize blit quad.
552 OpenGl_VertexBuffer* initBlitQuad (const Standard_Boolean theToFlip);
554 //! Blend together views pair into stereo image.
555 void drawStereoPair();
559 OpenGl_GraphicDriver* myDriver;
560 Handle(OpenGl_Window) myWindow;
561 Handle(OpenGl_Workspace) myWorkspace;
562 Handle(OpenGl_Caps) myCaps;
563 Standard_Boolean& myDeviceLostFlag;
564 Standard_Boolean myWasRedrawnGL;
566 Standard_Boolean myAntiAliasing;
567 Standard_Boolean myCulling;
568 Graphic3d_TypeOfShadingModel myShadingModel;
569 Graphic3d_TypeOfSurfaceDetail mySurfaceDetail;
570 Graphic3d_TypeOfBackfacingModel myBackfacing;
571 TEL_COLOUR myBgColor;
573 OPENGL_ZCLIP myZClip;
574 Graphic3d_SequenceOfHClipPlane myClipPlanes;
575 Handle(Graphic3d_Camera) myCamera;
576 OpenGl_FrameBuffer* myFBO;
577 Standard_Boolean myUseGLLight;
578 Standard_Boolean myToShowTrihedron;
579 Standard_Boolean myToShowGradTrihedron;
580 TCollection_AsciiString myBackgroundImagePath;
581 Handle(Graphic3d_TextureEnv) myTextureEnvData;
582 Graphic3d_GraduatedTrihedron myGTrihedronData;
584 OpenGl_ListOfLight myLights;
585 OpenGl_LayerList myZLayers; //!< main list of displayed structure, sorted by layers
587 Graphic3d_WorldViewProjState myWorldViewProjState; //!< camera modification state
588 OpenGl_StateCounter* myStateCounter;
589 Standard_Size myCurrLightSourceState;
591 typedef std::pair<Standard_Size, Standard_Size> StateInfo;
593 StateInfo myLastOrientationState;
594 StateInfo myLastViewMappingState;
595 StateInfo myLastLightSourceState;
597 //! Is needed for selection of overlapping objects and storage of the current view volume
598 OpenGl_BVHTreeSelector myBVHSelector;
600 OpenGl_Trihedron myTrihedron;
601 OpenGl_GraduatedTrihedron myGraduatedTrihedron;
603 Handle(OpenGl_Texture) myTextureEnv;
605 protected: //! @name Rendering properties
607 //! Two framebuffers (left and right views) store cached main presentation
608 //! of the view (without presentation of immediate layers).
609 Handle(OpenGl_FrameBuffer) myMainSceneFbos[2];
610 Handle(OpenGl_FrameBuffer) myImmediateSceneFbos[2]; //!< Additional buffers for immediate layer in stereo mode.
611 OpenGl_VertexBuffer myFullScreenQuad; //!< Vertices for full-screen quad rendering.
612 OpenGl_VertexBuffer myFullScreenQuadFlip;
613 Standard_Boolean myToFlipOutput; //!< Flag to draw result image upside-down
614 unsigned int myFrameCounter; //!< redraw counter, for debugging
615 Standard_Boolean myHasFboBlit;
616 Standard_Boolean myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer)
617 Standard_Boolean myBackBufferRestored;
618 Standard_Boolean myIsImmediateDrawn; //!< flag indicates that immediate mode buffer contains some data
620 protected: //! @name Background parameters
622 OpenGl_AspectFace* myTextureParams; //!< Stores texture and its parameters for textured background
623 OpenGl_BackgroundArray* myBgGradientArray; //!< Primitive array for gradient background
624 OpenGl_BackgroundArray* myBgTextureArray; //!< Primitive array for texture background
626 protected: //! @name data types related to ray-tracing
628 //! Result of OpenGL shaders initialization.
629 enum RaytraceInitStatus
636 //! Describes update mode (state).
637 enum RaytraceUpdateMode
639 OpenGl_GUM_CHECK, //!< check geometry state
640 OpenGl_GUM_PREPARE, //!< collect unchanged objects
641 OpenGl_GUM_REBUILD //!< rebuild changed and new objects
644 //! Defines frequently used shader variables.
645 enum ShaderVariableIndex
658 OpenGl_RT_uUnviewMat,
663 OpenGl_RT_uLightAmbnt,
664 OpenGl_RT_uLightCount,
667 OpenGl_RT_uBackColorTop,
668 OpenGl_RT_uBackColorBot,
670 // ray-tracing params
671 OpenGl_RT_uShadowsEnabled,
672 OpenGl_RT_uReflectEnabled,
673 OpenGl_RT_uSphereMapEnabled,
674 OpenGl_RT_uSphereMapForBack,
675 OpenGl_RT_uTexSamplersArray,
676 OpenGl_RT_uBlockedRngEnabled,
678 // sampled frame params
679 OpenGl_RT_uSampleWeight,
680 OpenGl_RT_uFrameRndSeed,
682 // adaptive FSAA params
687 OpenGl_RT_NbVariables // special field
690 //! Defines texture samplers.
691 enum ShaderSamplerNames
693 OpenGl_RT_SceneNodeInfoTexture = 0,
694 OpenGl_RT_SceneMinPointTexture = 1,
695 OpenGl_RT_SceneMaxPointTexture = 2,
696 OpenGl_RT_SceneTransformTexture = 3,
698 OpenGl_RT_GeometryVertexTexture = 4,
699 OpenGl_RT_GeometryNormalTexture = 5,
700 OpenGl_RT_GeometryTexCrdTexture = 6,
701 OpenGl_RT_GeometryTriangTexture = 7,
703 OpenGl_RT_EnvironmentMapTexture = 8,
705 OpenGl_RT_RaytraceMaterialTexture = 9,
706 OpenGl_RT_RaytraceLightSrcTexture = 10,
708 OpenGl_RT_FsaaInputTexture = 11,
709 OpenGl_RT_PrevAccumTexture = 12,
711 OpenGl_RT_OpenGlColorTexture = 13,
712 OpenGl_RT_OpenGlDepthTexture = 14
715 //! Tool class for management of shader sources.
720 //! Default shader prefix - empty string.
721 static const TCollection_AsciiString EMPTY_PREFIX;
723 //! Creates new uninitialized shader source.
731 //! Returns error description in case of load fail.
732 const TCollection_AsciiString& ErrorDescription() const
737 //! Returns prefix to insert before the source.
738 const TCollection_AsciiString& Prefix() const
743 //! Sets prefix to insert before the source.
744 void SetPrefix (const TCollection_AsciiString& thePrefix)
746 myPrefix = thePrefix;
749 //! Returns shader source combined with prefix.
750 TCollection_AsciiString Source() const;
752 //! Loads shader source from specified files.
753 Standard_Boolean Load (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
757 TCollection_AsciiString mySource; //!< Source string of the shader object
758 TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
759 TCollection_AsciiString myError; //!< error state
763 //! Default ray-tracing depth.
764 static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
766 //! Default size of traversal stack.
767 static const Standard_Integer THE_DEFAULT_STACK_SIZE = 24;
769 //! Compile-time ray-tracing parameters.
770 struct RaytracingParams
772 //! Actual size of traversal stack in shader program.
773 Standard_Integer StackSize;
775 //! Actual ray-tracing depth (number of ray bounces).
776 Standard_Integer NbBounces;
778 //! Enables/disables light propagation through transparent media.
779 Standard_Boolean TransparentShadows;
781 //! Enables/disables global illumination (GI) effects.
782 Standard_Boolean GlobalIllumination;
784 //! Enables/disables the use of OpenGL bindless textures.
785 Standard_Boolean UseBindlessTextures;
787 //! Creates default compile-time ray-tracing parameters.
789 : StackSize (THE_DEFAULT_STACK_SIZE),
790 NbBounces (THE_DEFAULT_NB_BOUNCES),
791 TransparentShadows (Standard_False),
792 GlobalIllumination (Standard_False),
793 UseBindlessTextures (Standard_False)
799 //! Describes state of OpenGL structure.
802 Standard_Size StructureState;
803 Standard_Size InstancedState;
805 //! Creates new structure state.
806 StructState (const Standard_Size theStructureState = 0,
807 const Standard_Size theInstancedState = 0)
808 : StructureState (theStructureState),
809 InstancedState (theInstancedState)
814 //! Creates new structure state.
815 StructState (const OpenGl_Structure* theStructure)
817 StructureState = theStructure->ModificationState();
819 InstancedState = theStructure->InstancedStructure() != NULL ?
820 theStructure->InstancedStructure()->ModificationState() : 0;
824 protected: //! @name methods related to ray-tracing
826 //! Updates 3D scene geometry for ray-tracing.
827 Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode theMode,
828 const Standard_Integer theViewId,
829 const Handle(OpenGl_Context)& theGlContext);
831 //! Updates 3D scene light sources for ray-tracing.
832 Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
834 //! Updates environment map for ray-tracing.
835 Standard_Boolean updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext);
837 //! Checks to see if the OpenGL structure is modified.
838 Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
840 //! Adds OpenGL structure to ray-traced scene geometry.
841 Standard_Boolean addRaytraceStructure (const OpenGl_Structure* theStructure,
842 const Handle(OpenGl_Context)& theGlContext);
844 //! Adds OpenGL groups to ray-traced scene geometry.
845 Standard_Boolean addRaytraceGroups (const OpenGl_Structure* theStructure,
846 const OpenGl_RaytraceMaterial& theStructMat,
847 const Standard_ShortReal* theTransform,
848 const Handle(OpenGl_Context)& theGlContext);
850 //! Creates ray-tracing material properties.
851 OpenGl_RaytraceMaterial convertMaterial (const OpenGl_AspectFace* theAspect,
852 const Handle(OpenGl_Context)& theGlContext);
854 //! Adds OpenGL primitive array to ray-traced scene geometry.
855 OpenGl_TriangleSet* addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
856 const Standard_Integer theMatID,
857 const OpenGl_Mat4* theTrans);
859 //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
860 Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
861 const Standard_Integer theMatID,
862 const Standard_Integer theCount,
863 const Standard_Integer theOffset,
864 const OpenGl_PrimitiveArray& theArray);
866 //! Adds OpenGL triangle array to ray-traced scene geometry.
867 Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
868 const Standard_Integer theMatID,
869 const Standard_Integer theCount,
870 const Standard_Integer theOffset,
871 const Handle(Graphic3d_IndexBuffer)& theIndices);
873 //! Adds OpenGL triangle fan array to ray-traced scene geometry.
874 Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
875 const Standard_Integer theMatID,
876 const Standard_Integer theCount,
877 const Standard_Integer theOffset,
878 const Handle(Graphic3d_IndexBuffer)& theIndices);
880 //! Adds OpenGL triangle strip array to ray-traced scene geometry.
881 Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
882 const Standard_Integer theMatID,
883 const Standard_Integer theCount,
884 const Standard_Integer theOffset,
885 const Handle(Graphic3d_IndexBuffer)& theIndices);
887 //! Adds OpenGL quadrangle array to ray-traced scene geometry.
888 Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
889 const Standard_Integer theMatID,
890 const Standard_Integer theCount,
891 const Standard_Integer theOffset,
892 const Handle(Graphic3d_IndexBuffer)& theIndices);
894 //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
895 Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
896 const Standard_Integer theMatID,
897 const Standard_Integer theCount,
898 const Standard_Integer theOffset,
899 const Handle(Graphic3d_IndexBuffer)& theIndices);
901 //! Adds OpenGL polygon array to ray-traced scene geometry.
902 Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
903 const Standard_Integer theMatID,
904 const Standard_Integer theCount,
905 const Standard_Integer theOffset,
906 const Handle(Graphic3d_IndexBuffer)& theIndices);
908 //! Uploads ray-trace data to the GPU.
909 Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
911 //! Generates shader prefix based on current ray-tracing options.
912 TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
914 //! Performs safe exit when shaders initialization fails.
915 Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
916 const Handle(OpenGl_Context)& theGlContext);
918 //! Loads and compiles shader object from specified source.
919 Handle(OpenGl_ShaderObject) initShader (const GLenum theType,
920 const ShaderSource& theSource,
921 const Handle(OpenGl_Context)& theGlContext);
923 //! Creates shader program from the given vertex and fragment shaders.
924 Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)& theGlContext,
925 const Handle(OpenGl_ShaderObject)& theVertShader,
926 const Handle(OpenGl_ShaderObject)& theFragShader);
928 //! Initializes OpenGL/GLSL shader programs.
929 Standard_Boolean initRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
931 //! Releases OpenGL/GLSL shader programs.
932 void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
934 //! Updates auxiliary OpenGL frame buffers.
935 Standard_Boolean updateRaytraceBuffers (const Standard_Integer theSizeX,
936 const Standard_Integer theSizeY,
937 const Handle(OpenGl_Context)& theGlContext);
939 //! Generates viewing rays for corners of screen quad.
940 void updateCamera (const OpenGl_Mat4& theOrientation,
941 const OpenGl_Mat4& theViewMapping,
942 OpenGl_Vec3* theOrigins,
943 OpenGl_Vec3* theDirects,
944 OpenGl_Mat4& theUnView);
946 //! Binds ray-trace textures to corresponding texture units.
947 void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
949 //! Unbinds ray-trace textures from corresponding texture unit.
950 void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
952 //! Sets uniform state for the given ray-tracing shader program.
953 Standard_Boolean setUniformState (const OpenGl_Vec3* theOrigins,
954 const OpenGl_Vec3* theDirects,
955 const OpenGl_Mat4& theUnviewMat,
956 const Standard_Integer theProgramId,
957 const Handle(OpenGl_Context)& theGlContext);
959 //! Runs ray-tracing shader programs.
960 Standard_Boolean runRaytraceShaders (const Standard_Integer theSizeX,
961 const Standard_Integer theSizeY,
962 const OpenGl_Vec3* theOrigins,
963 const OpenGl_Vec3* theDirects,
964 const OpenGl_Mat4& theUnviewMat,
965 Graphic3d_Camera::Projection theProjection,
966 OpenGl_FrameBuffer* theReadDrawFbo,
967 const Handle(OpenGl_Context)& theGlContext);
969 //! Redraws the window using OpenGL/GLSL ray-tracing.
970 Standard_Boolean raytrace (const Standard_Integer theSizeX,
971 const Standard_Integer theSizeY,
972 Graphic3d_Camera::Projection theProjection,
973 OpenGl_FrameBuffer* theReadDrawFbo,
974 const Handle(OpenGl_Context)& theGlContext);
976 protected: //! @name fields related to ray-tracing
978 //! Result of shaders initialization.
979 RaytraceInitStatus myRaytraceInitStatus;
981 //! Is geometry data valid?
982 Standard_Boolean myIsRaytraceDataValid;
984 //! Warning about missing extension GL_ARB_bindless_texture has been displayed?
985 Standard_Boolean myIsRaytraceWarnTextures;
987 //! 3D scene geometry data for ray-tracing.
988 OpenGl_RaytraceGeometry myRaytraceGeometry;
990 //! Compile-time ray-tracing parameters.
991 RaytracingParams myRaytraceParameters;
993 //! Radius of bounding sphere of the scene.
994 Standard_ShortReal myRaytraceSceneRadius;
995 //! Scene epsilon to prevent self-intersections.
996 Standard_ShortReal myRaytraceSceneEpsilon;
998 //! OpenGL/GLSL source of ray-tracing fragment shader.
999 ShaderSource myRaytraceShaderSource;
1000 //! OpenGL/GLSL source of adaptive-AA fragment shader.
1001 ShaderSource myPostFSAAShaderSource;
1003 //! OpenGL/GLSL ray-tracing fragment shader.
1004 Handle(OpenGl_ShaderObject) myRaytraceShader;
1005 //! OpenGL/GLSL adaptive-AA fragment shader.
1006 Handle(OpenGl_ShaderObject) myPostFSAAShader;
1008 //! OpenGL/GLSL ray-tracing shader program.
1009 Handle(OpenGl_ShaderProgram) myRaytraceProgram;
1010 //! OpenGL/GLSL adaptive-AA shader program.
1011 Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
1012 //! OpenGL/GLSL program for displaying texture.
1013 Handle(OpenGl_ShaderProgram) myOutImageProgram;
1015 //! Texture buffer of data records of bottom-level BVH nodes.
1016 Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
1017 //! Texture buffer of minimum points of bottom-level BVH nodes.
1018 Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
1019 //! Texture buffer of maximum points of bottom-level BVH nodes.
1020 Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
1021 //! Texture buffer of transformations of high-level BVH nodes.
1022 Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
1024 //! Texture buffer of vertex coords.
1025 Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
1026 //! Texture buffer of vertex normals.
1027 Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
1028 //! Texture buffer of vertex UV coords.
1029 Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
1030 //! Texture buffer of triangle indices.
1031 Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
1033 //! Texture buffer of material properties.
1034 Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
1035 //! Texture buffer of light source properties.
1036 Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
1038 //! 1st framebuffer (FBO) to perform adaptive FSAA.
1039 Handle(OpenGl_FrameBuffer) myRaytraceFBO1[2];
1040 //! 2nd framebuffer (FBO) to perform adaptive FSAA.
1041 Handle(OpenGl_FrameBuffer) myRaytraceFBO2[2];
1042 //! Framebuffer (FBO) for preliminary OpenGL output.
1043 Handle(OpenGl_FrameBuffer) myOpenGlFBO;
1045 //! Vertex buffer (VBO) for drawing dummy quad.
1046 OpenGl_VertexBuffer myRaytraceScreenQuad;
1048 //! Cached locations of frequently used uniform variables.
1049 Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
1051 //! State of OpenGL structures reflected to ray-tracing.
1052 std::map<const OpenGl_Structure*, StructState> myStructureStates;
1054 //! PrimitiveArray to TriangleSet map for scene partial update.
1055 std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
1057 //! Set of IDs of non-raytracable elements (to detect updates).
1058 std::set<Standard_Integer> myNonRaytraceStructureIDs;
1060 //! Render filter to filter out all raytracable structures.
1061 Handle(OpenGl_RaytraceFilter) myRaytraceFilter;
1063 //! Marks if environment map should be updated.
1064 Standard_Boolean myToUpdateEnvironmentMap;
1066 //! State of OpenGL layer list.
1067 Standard_Size myLayerListState;
1069 //! Number of accumulated frames (for progressive rendering).
1070 Standard_Integer myAccumFrames;
1072 //! Stored ray origins used for detection of camera movements.
1073 OpenGl_Vec3 myPreviousOrigins[3];
1075 //! Bullard RNG to produce random sequence.
1076 math_BullardGenerator myRNG;
1080 DEFINE_STANDARD_ALLOC
1081 DEFINE_STANDARD_RTTI(OpenGl_View, Graphic3d_CView) // Type definition
1083 friend class OpenGl_GraphicDriver;
1084 friend class OpenGl_Workspace;
1087 #endif // _OpenGl_View_Header