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.
19 #include <OpenGl_GlCore11.hxx>
21 #include <Graphic3d_GraphicDriver.hxx>
22 #include <Graphic3d_TextureParams.hxx>
23 #include <Graphic3d_Texture2Dmanual.hxx>
24 #include <Graphic3d_TransformUtils.hxx>
25 #include <Image_AlienPixMap.hxx>
27 #include <NCollection_Mat4.hxx>
29 #include <OpenGl_AspectLine.hxx>
30 #include <OpenGl_Context.hxx>
31 #include <OpenGl_Matrix.hxx>
32 #include <OpenGl_Workspace.hxx>
33 #include <OpenGl_View.hxx>
34 #include <OpenGl_Trihedron.hxx>
35 #include <OpenGl_GraduatedTrihedron.hxx>
36 #include <OpenGl_PrimitiveArray.hxx>
37 #include <OpenGl_PrinterContext.hxx>
38 #include <OpenGl_ShaderManager.hxx>
39 #include <OpenGl_ShaderProgram.hxx>
40 #include <OpenGl_Structure.hxx>
41 #include <OpenGl_ArbFBO.hxx>
47 static const GLfloat THE_DEFAULT_AMBIENT[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
48 static const GLfloat THE_DEFAULT_SPOT_DIR[3] = { 0.0f, 0.0f, -1.0f };
49 static const GLfloat THE_DEFAULT_SPOT_EXPONENT = 0.0f;
50 static const GLfloat THE_DEFAULT_SPOT_CUTOFF = 180.0f;
53 extern void InitLayerProp (const int theListId); //szvgl: defined in OpenGl_GraphicDriver_Layer.cxx
55 #if !defined(GL_ES_VERSION_2_0)
57 //=======================================================================
58 //function : bindLight
60 //=======================================================================
61 static void bindLight (const OpenGl_Light& theLight,
63 Graphic3d_Vec4& theAmbientColor,
64 const Handle(OpenGl_Workspace)& theWorkspace)
66 // Only 8 lights in OpenGL...
67 if (theLightGlId > GL_LIGHT7)
72 if (theLight.Type == Graphic3d_TOLS_AMBIENT)
74 // add RGBA intensity of the ambient light
75 theAmbientColor += theLight.Color;
79 const Handle(OpenGl_Context)& aContext = theWorkspace->GetGlContext();
81 // the light is a headlight?
82 if (theLight.IsHeadlight)
84 aContext->WorldViewState.Push();
85 aContext->WorldViewState.SetIdentity();
87 aContext->ApplyWorldViewMatrix();
91 switch (theLight.Type)
93 case Graphic3d_TOLS_AMBIENT : break; // handled by separate if-clause at beginning of method
94 case Graphic3d_TOLS_DIRECTIONAL:
96 // if the last parameter of GL_POSITION, is zero, the corresponding light source is a Directional one
97 const OpenGl_Vec4 anInfDir = -theLight.Direction;
99 // to create a realistic effect, set the GL_SPECULAR parameter to the same value as the GL_DIFFUSE.
100 glLightfv (theLightGlId, GL_AMBIENT, THE_DEFAULT_AMBIENT);
101 glLightfv (theLightGlId, GL_DIFFUSE, theLight.Color.GetData());
102 glLightfv (theLightGlId, GL_SPECULAR, theLight.Color.GetData());
103 glLightfv (theLightGlId, GL_POSITION, anInfDir.GetData());
104 glLightfv (theLightGlId, GL_SPOT_DIRECTION, THE_DEFAULT_SPOT_DIR);
105 glLightf (theLightGlId, GL_SPOT_EXPONENT, THE_DEFAULT_SPOT_EXPONENT);
106 glLightf (theLightGlId, GL_SPOT_CUTOFF, THE_DEFAULT_SPOT_CUTOFF);
109 case Graphic3d_TOLS_POSITIONAL:
111 // to create a realistic effect, set the GL_SPECULAR parameter to the same value as the GL_DIFFUSE
112 glLightfv (theLightGlId, GL_AMBIENT, THE_DEFAULT_AMBIENT);
113 glLightfv (theLightGlId, GL_DIFFUSE, theLight.Color.GetData());
114 glLightfv (theLightGlId, GL_SPECULAR, theLight.Color.GetData());
115 glLightfv (theLightGlId, GL_POSITION, theLight.Position.GetData());
116 glLightfv (theLightGlId, GL_SPOT_DIRECTION, THE_DEFAULT_SPOT_DIR);
117 glLightf (theLightGlId, GL_SPOT_EXPONENT, THE_DEFAULT_SPOT_EXPONENT);
118 glLightf (theLightGlId, GL_SPOT_CUTOFF, THE_DEFAULT_SPOT_CUTOFF);
119 glLightf (theLightGlId, GL_CONSTANT_ATTENUATION, theLight.ConstAttenuation());
120 glLightf (theLightGlId, GL_LINEAR_ATTENUATION, theLight.LinearAttenuation());
121 glLightf (theLightGlId, GL_QUADRATIC_ATTENUATION, 0.0);
124 case Graphic3d_TOLS_SPOT:
126 glLightfv (theLightGlId, GL_AMBIENT, THE_DEFAULT_AMBIENT);
127 glLightfv (theLightGlId, GL_DIFFUSE, theLight.Color.GetData());
128 glLightfv (theLightGlId, GL_SPECULAR, theLight.Color.GetData());
129 glLightfv (theLightGlId, GL_POSITION, theLight.Position.GetData());
130 glLightfv (theLightGlId, GL_SPOT_DIRECTION, theLight.Direction.GetData());
131 glLightf (theLightGlId, GL_SPOT_EXPONENT, theLight.Concentration() * 128.0f);
132 glLightf (theLightGlId, GL_SPOT_CUTOFF, (theLight.Angle() * 180.0f) / GLfloat(M_PI));
133 glLightf (theLightGlId, GL_CONSTANT_ATTENUATION, theLight.ConstAttenuation());
134 glLightf (theLightGlId, GL_LINEAR_ATTENUATION, theLight.LinearAttenuation());
135 glLightf (theLightGlId, GL_QUADRATIC_ATTENUATION, 0.0f);
140 // restore matrix in case of headlight
141 if (theLight.IsHeadlight)
143 aContext->WorldViewState.Pop();
146 glEnable (theLightGlId++);
150 //=======================================================================
151 //function : drawBackground
153 //=======================================================================
154 void OpenGl_View::drawBackground (const Handle(OpenGl_Workspace)& theWorkspace)
156 const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
158 if ((theWorkspace->NamedStatus & OPENGL_NS_WHITEBACK) != 0 // no background
159 || (!myBgTextureArray->IsDefined() // no texture
160 && !myBgGradientArray->IsDefined())) // no gradient
165 const Standard_Boolean wasUsedZBuffer = theWorkspace->SetUseZBuffer (Standard_False);
168 aCtx->core11fwd->glDisable (GL_DEPTH_TEST);
171 aCtx->ProjectionState.Push();
172 aCtx->WorldViewState.Push();
173 aCtx->ModelWorldState.Push();
174 aCtx->ProjectionState.SetIdentity();
175 aCtx->WorldViewState.SetIdentity();
176 aCtx->ModelWorldState.SetIdentity();
177 aCtx->ApplyProjectionMatrix();
178 aCtx->ApplyModelViewMatrix();
180 // Drawing background gradient if:
181 // - gradient fill type is not Aspect_GFM_NONE and
182 // - either background texture is no specified or it is drawn in Aspect_FM_CENTERED mode
183 if (myBgGradientArray->IsDefined()
184 && (!myTextureParams->Aspect()->ToMapTexture()
185 || myBgTextureArray->TextureFillMethod() == Aspect_FM_CENTERED
186 || myBgTextureArray->TextureFillMethod() == Aspect_FM_NONE))
188 #if !defined(GL_ES_VERSION_2_0)
189 GLint aShadingModelOld = GL_SMOOTH;
190 if (aCtx->core11 != NULL)
192 aCtx->core11fwd->glDisable (GL_LIGHTING);
193 aCtx->core11fwd->glGetIntegerv (GL_SHADE_MODEL, &aShadingModelOld);
194 aCtx->core11->glShadeModel (GL_SMOOTH);
198 if (myBgGradientArray->IsDataChanged())
200 myBgGradientArray->Init (theWorkspace);
203 myBgGradientArray->Render (theWorkspace);
205 #if !defined(GL_ES_VERSION_2_0)
206 if (aCtx->core11 != NULL)
208 aCtx->core11->glShadeModel (aShadingModelOld);
213 // Drawing background image if it is defined
214 // (texture is defined and fill type is not Aspect_FM_NONE)
215 if (myBgTextureArray->IsDefined()
216 && myTextureParams->Aspect()->ToMapTexture())
218 aCtx->core11fwd->glDisable (GL_BLEND);
220 const OpenGl_AspectFace* anOldAspectFace = theWorkspace->SetAspectFace (myTextureParams);
222 if (myBgTextureArray->IsDataChanged()
223 || myBgTextureArray->IsViewSizeChanged (theWorkspace))
225 myBgTextureArray->Init (theWorkspace);
228 myBgTextureArray->Render (theWorkspace);
231 theWorkspace->SetAspectFace (anOldAspectFace);
234 aCtx->ModelWorldState.Pop();
235 aCtx->WorldViewState.Pop();
236 aCtx->ProjectionState.Pop();
237 aCtx->ApplyProjectionMatrix();
238 aCtx->ApplyModelViewMatrix();
242 theWorkspace->SetUseZBuffer (Standard_True);
243 aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
247 //=======================================================================
250 //=======================================================================
251 void OpenGl_View::Redraw()
253 const Standard_Boolean wasDisabledMSAA = myToDisableMSAA;
254 const Standard_Boolean hadFboBlit = myHasFboBlit;
255 if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
256 && !myCaps->vboDisable
257 && !myCaps->keepArrayData)
261 myDeviceLostFlag = Standard_True;
264 myCaps->keepArrayData = Standard_True;
267 if (!myWorkspace->Activate())
272 myWindow->SetSwapInterval();
275 const Graphic3d_StereoMode aStereoMode = myRenderParams.StereoMode;
276 Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
277 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
279 // release pending GL resources
280 aCtx->ReleaseDelayed();
282 // fetch OpenGl context state
285 // set resolution ratio
286 aCtx->SetResolutionRatio (RenderingParams().ResolutionRatio());
288 OpenGl_FrameBuffer* aFrameBuffer = myFBO.operator->();
289 bool toSwap = aCtx->IsRender()
290 && !aCtx->caps->buffersNoSwap
291 && aFrameBuffer == NULL;
293 Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWindow->Width();
294 Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myWindow->Height();
296 // determine multisampling parameters
297 Standard_Integer aNbSamples = !myToDisableMSAA
298 ? Max (Min (myRenderParams.NbMsaaSamples, aCtx->MaxMsaaSamples()), 0)
302 aNbSamples = OpenGl_Context::GetPowerOfTwo (aNbSamples, aCtx->MaxMsaaSamples());
305 if ( aFrameBuffer == NULL
306 && !aCtx->DefaultFrameBuffer().IsNull()
307 && aCtx->DefaultFrameBuffer()->IsValid())
309 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
313 && (myTransientDrawToFront
314 || aProjectType == Graphic3d_Camera::Projection_Stereo
317 if (myMainSceneFbos[0]->GetVPSizeX() != aSizeX
318 || myMainSceneFbos[0]->GetVPSizeY() != aSizeY
319 || myMainSceneFbos[0]->NbSamples() != aNbSamples)
321 if (!myTransientDrawToFront)
323 myImmediateSceneFbos[0]->Release (aCtx.operator->());
324 myImmediateSceneFbos[1]->Release (aCtx.operator->());
325 myImmediateSceneFbos[0]->ChangeViewport (0, 0);
326 myImmediateSceneFbos[1]->ChangeViewport (0, 0);
329 // prepare FBOs containing main scene
330 // for further blitting and rendering immediate presentations on top
331 if (aCtx->core20fwd != NULL)
333 myMainSceneFbos[0]->Init (aCtx, aSizeX, aSizeY, myFboColorFormat, myFboDepthFormat, aNbSamples);
335 if (myTransientDrawToFront
336 && !aCtx->caps->useSystemBuffer
337 && myMainSceneFbos[0]->IsValid())
339 myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0]);
345 myMainSceneFbos [0]->Release (aCtx.operator->());
346 myMainSceneFbos [1]->Release (aCtx.operator->());
347 myImmediateSceneFbos[0]->Release (aCtx.operator->());
348 myImmediateSceneFbos[1]->Release (aCtx.operator->());
349 myMainSceneFbos [0]->ChangeViewport (0, 0);
350 myMainSceneFbos [1]->ChangeViewport (0, 0);
351 myImmediateSceneFbos[0]->ChangeViewport (0, 0);
352 myImmediateSceneFbos[1]->ChangeViewport (0, 0);
355 if (aProjectType == Graphic3d_Camera::Projection_Stereo
356 && myMainSceneFbos[0]->IsValid())
358 myMainSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0]);
359 if (!myMainSceneFbos[1]->IsValid())
362 aProjectType = Graphic3d_Camera::Projection_Perspective;
364 else if (!myTransientDrawToFront)
368 else if (!aCtx->HasStereoBuffers() || aStereoMode != Graphic3d_StereoMode_QuadBuffer)
370 myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0]);
371 myImmediateSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0]);
372 if (!myImmediateSceneFbos[0]->IsValid()
373 || !myImmediateSceneFbos[1]->IsValid())
375 aProjectType = Graphic3d_Camera::Projection_Perspective;
380 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
382 OpenGl_FrameBuffer* aMainFbos[2] =
384 myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
385 myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
387 OpenGl_FrameBuffer* anImmFbos[2] =
389 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
390 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
393 if (!myTransientDrawToFront)
395 anImmFbos[0] = aMainFbos[0];
396 anImmFbos[1] = aMainFbos[1];
398 else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
399 || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
405 #if !defined(GL_ES_VERSION_2_0)
406 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
408 redraw (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0]);
409 myBackBufferRestored = Standard_True;
410 myIsImmediateDrawn = Standard_False;
411 #if !defined(GL_ES_VERSION_2_0)
412 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
414 if (!redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], anImmFbos[0]))
418 else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip && toSwap)
423 #if !defined(GL_ES_VERSION_2_0)
424 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
426 redraw (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1]);
427 myBackBufferRestored = Standard_True;
428 myIsImmediateDrawn = Standard_False;
429 if (!redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], anImmFbos[1]))
434 if (anImmFbos[0] != NULL)
436 drawStereoPair (aFrameBuffer);
441 OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
442 OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
443 if (!aCtx->caps->useSystemBuffer && myImmediateSceneFbos[0]->IsValid())
445 anImmFbo = myImmediateSceneFbos[0].operator->();
447 if (!myTransientDrawToFront)
452 #if !defined(GL_ES_VERSION_2_0)
454 && aFrameBuffer == NULL)
456 aCtx->SetReadDrawBuffer (GL_BACK);
459 redraw (aProjectType, aMainFbo != NULL ? aMainFbo : aFrameBuffer);
460 myBackBufferRestored = Standard_True;
461 myIsImmediateDrawn = Standard_False;
462 if (!redrawImmediate (aProjectType, aMainFbo, anImmFbo))
468 && anImmFbo != aFrameBuffer)
470 blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
474 #if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
475 if (OpenGl_AVIWriter_AllowWriting (myWindow->PlatformWindow()->NativeHandle()))
478 glGetIntegerv (GL_VIEWPORT, params);
479 int nWidth = params[2] & ~0x7;
480 int nHeight = params[3] & ~0x7;
482 const int nBitsPerPixel = 24;
483 GLubyte* aDumpData = new GLubyte[nWidth * nHeight * nBitsPerPixel / 8];
485 glPixelStorei (GL_PACK_ALIGNMENT, 1);
486 glReadPixels (0, 0, nWidth, nHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, aDumpData);
487 OpenGl_AVIWriter_AVIWriter (aDumpData, nWidth, nHeight, nBitsPerPixel);
492 if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
493 && myRenderParams.IsGlobalIlluminationEnabled)
501 if (wasDisabledMSAA != myToDisableMSAA
502 || hadFboBlit != myHasFboBlit)
512 if (!myMainSceneFbos[0]->IsValid())
514 myBackBufferRestored = Standard_False;
519 aCtx->core11fwd->glFlush();
522 // reset render mode state
525 myWasRedrawnGL = Standard_True;
528 // =======================================================================
529 // function : RedrawImmediate
531 // =======================================================================
532 void OpenGl_View::RedrawImmediate()
534 if (!myWorkspace->Activate())
537 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
538 if (!myTransientDrawToFront
539 || !myBackBufferRestored
540 || (aCtx->caps->buffersNoSwap && !myMainSceneFbos[0]->IsValid()))
546 const Graphic3d_StereoMode aStereoMode = myRenderParams.StereoMode;
547 Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
548 OpenGl_FrameBuffer* aFrameBuffer = myFBO.operator->();
550 if ( aFrameBuffer == NULL
551 && !aCtx->DefaultFrameBuffer().IsNull()
552 && aCtx->DefaultFrameBuffer()->IsValid())
554 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
557 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
559 if (myMainSceneFbos[0]->IsValid()
560 && !myMainSceneFbos[1]->IsValid())
562 aProjectType = Graphic3d_Camera::Projection_Perspective;
567 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
569 OpenGl_FrameBuffer* aMainFbos[2] =
571 myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
572 myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
574 OpenGl_FrameBuffer* anImmFbos[2] =
576 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
577 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
579 if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
580 || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
586 if (aCtx->arbFBO != NULL)
588 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
590 #if !defined(GL_ES_VERSION_2_0)
591 if (anImmFbos[0] == NULL)
593 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
596 toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye,
599 Standard_True) || toSwap;
600 if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
602 && !aCtx->caps->buffersNoSwap)
607 if (aCtx->arbFBO != NULL)
609 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
611 #if !defined(GL_ES_VERSION_2_0)
612 if (anImmFbos[1] == NULL)
614 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
617 toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye,
620 Standard_True) || toSwap;
621 if (anImmFbos[0] != NULL)
623 drawStereoPair (aFrameBuffer);
628 OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
629 OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
630 if (!aCtx->caps->useSystemBuffer && myImmediateSceneFbos[0]->IsValid())
632 anImmFbo = myImmediateSceneFbos[0].operator->();
634 #if !defined(GL_ES_VERSION_2_0)
635 if (aMainFbo == NULL)
637 aCtx->SetReadDrawBuffer (GL_BACK);
640 toSwap = redrawImmediate (aProjectType,
643 Standard_True) || toSwap;
645 && anImmFbo != aFrameBuffer)
647 blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
654 if (toSwap && !aCtx->caps->buffersNoSwap)
660 aCtx->core11fwd->glFlush();
663 myWasRedrawnGL = Standard_True;
666 // =======================================================================
669 // =======================================================================
670 void OpenGl_View::redraw (const Graphic3d_Camera::Projection theProjection, OpenGl_FrameBuffer* theReadDrawFbo)
672 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
673 if (theReadDrawFbo != NULL)
675 theReadDrawFbo->BindBuffer (aCtx);
676 theReadDrawFbo->SetupViewport (aCtx);
680 aCtx->core11fwd->glViewport (0, 0, myWindow->Width(), myWindow->Height());
683 // request reset of material
684 myWorkspace->NamedStatus |= OPENGL_NS_RESMAT;
685 myWorkspace->UseZBuffer() = Standard_True;
686 myWorkspace->UseDepthWrite() = Standard_True;
687 GLbitfield toClear = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
688 glDepthFunc (GL_LEQUAL);
689 glDepthMask (GL_TRUE);
690 glEnable (GL_DEPTH_TEST);
692 #if !defined(GL_ES_VERSION_2_0)
695 glClearDepthf (1.0f);
698 if (myWorkspace->NamedStatus & OPENGL_NS_WHITEBACK)
700 // set background to white
701 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
705 const OpenGl_Vec4& aBgColor = myBgColor;
706 glClearColor (aBgColor.r(), aBgColor.g(), aBgColor.b(), 0.0f);
711 render (theProjection, theReadDrawFbo, Standard_False);
714 // =======================================================================
715 // function : redrawMonoImmediate
717 // =======================================================================
718 bool OpenGl_View::redrawImmediate (const Graphic3d_Camera::Projection theProjection,
719 OpenGl_FrameBuffer* theReadFbo,
720 OpenGl_FrameBuffer* theDrawFbo,
721 const Standard_Boolean theIsPartialUpdate)
723 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
724 GLboolean toCopyBackToFront = GL_FALSE;
725 if (theDrawFbo == theReadFbo
726 && theDrawFbo != NULL)
728 myBackBufferRestored = Standard_False;
730 else if (theReadFbo != NULL
731 && theReadFbo->IsValid()
734 if (!blitBuffers (theReadFbo, theDrawFbo))
739 else if (theDrawFbo == NULL)
741 #if !defined(GL_ES_VERSION_2_0)
742 aCtx->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
744 if (toCopyBackToFront)
746 if (!HasImmediateStructures()
747 && !theIsPartialUpdate)
749 // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
756 myBackBufferRestored = Standard_False;
761 myBackBufferRestored = Standard_False;
763 myIsImmediateDrawn = Standard_True;
765 myWorkspace->UseZBuffer() = Standard_True;
766 myWorkspace->UseDepthWrite() = Standard_True;
767 glDepthFunc (GL_LEQUAL);
768 glDepthMask (GL_TRUE);
769 glEnable (GL_DEPTH_TEST);
770 #if !defined(GL_ES_VERSION_2_0)
773 glClearDepthf (1.0f);
776 render (theProjection, theDrawFbo, Standard_True);
778 return !toCopyBackToFront;
781 //=======================================================================
784 //=======================================================================
785 void OpenGl_View::render (Graphic3d_Camera::Projection theProjection,
786 OpenGl_FrameBuffer* theOutputFBO,
787 const Standard_Boolean theToDrawImmediate)
789 // ==================================
790 // Step 1: Prepare for render
791 // ==================================
793 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
795 #if !defined(GL_ES_VERSION_2_0)
796 // Disable current clipping planes
797 if (aContext->core11 != NULL)
799 const Standard_Integer aMaxPlanes = aContext->MaxClipPlanes();
800 for (Standard_Integer aClipPlaneId = GL_CLIP_PLANE0; aClipPlaneId < GL_CLIP_PLANE0 + aMaxPlanes; ++aClipPlaneId)
802 aContext->core11fwd->glDisable (aClipPlaneId);
807 // Update states of OpenGl_BVHTreeSelector (frustum culling algorithm).
808 myBVHSelector.SetViewVolume (myCamera);
809 myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height());
811 const Handle(OpenGl_ShaderManager)& aManager = aContext->ShaderManager();
812 if (StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index()) != myLastLightSourceState)
814 aManager->UpdateLightSourceStateTo (myShadingModel == Graphic3d_TOSM_NONE ? &myNoShadingLight : &myLights);
815 myLastLightSourceState = StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index());
818 // Update matrices if camera has changed.
819 Graphic3d_WorldViewProjState aWVPState = myCamera->WorldViewProjState();
820 const Standard_Boolean isCameraChanged = myWorldViewProjState != aWVPState;
821 const Standard_Boolean isSameView = aManager->IsSameView (this);
824 aContext->ProjectionState.SetCurrent (myCamera->ProjectionMatrixF());
825 aContext->WorldViewState .SetCurrent (myCamera->OrientationMatrixF());
829 // Apply new matrix state if camera has changed or this view differs from the one
830 // that was previously used for configuring matrices of shader manager
831 // (ApplyProjectionMatrix and ApplyWorldViewMatrix will affect the manager).
832 if (isCameraChanged || !isSameView)
834 aContext->ApplyProjectionMatrix();
835 aContext->ApplyWorldViewMatrix();
838 if (aManager->ModelWorldState().Index() == 0)
840 aContext->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
843 myWorldViewProjState = aWVPState;
845 // ====================================
846 // Step 2: Redraw background
847 // ====================================
850 if (!theToDrawImmediate)
852 drawBackground (myWorkspace);
855 #if !defined(GL_ES_VERSION_2_0)
856 // Switch off lighting by default
857 if (aContext->core11 != NULL)
859 glDisable(GL_LIGHTING);
863 // =================================
864 // Step 3: Redraw main plane
865 // =================================
867 // Setup face culling
868 GLboolean isCullFace = GL_FALSE;
869 if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
871 isCullFace = glIsEnabled (GL_CULL_FACE);
872 if (myBackfacing == Graphic3d_TOBM_DISABLE)
874 glEnable (GL_CULL_FACE);
875 glCullFace (GL_BACK);
878 glDisable (GL_CULL_FACE);
881 #if !defined(GL_ES_VERSION_2_0)
882 // if the view is scaled normal vectors are scaled to unit
883 // length for correct displaying of shaded objects
884 const gp_Pnt anAxialScale = myCamera->AxialScale();
885 if (anAxialScale.X() != 1.F ||
886 anAxialScale.Y() != 1.F ||
887 anAxialScale.Z() != 1.F)
889 aContext->SetGlNormalizeEnabled (Standard_True);
893 aContext->SetGlNormalizeEnabled (Standard_False);
896 // Apply InteriorShadingMethod
897 if (aContext->core11 != NULL)
899 aContext->core11->glShadeModel (myShadingModel == Graphic3d_TOSM_FACET
900 || myShadingModel == Graphic3d_TOSM_NONE ? GL_FLAT : GL_SMOOTH);
904 aManager->SetShadingModel (myShadingModel);
907 if (theProjection == Graphic3d_Camera::Projection_MonoLeftEye)
909 aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoLeftF());
910 aContext->ApplyProjectionMatrix();
912 else if (theProjection == Graphic3d_Camera::Projection_MonoRightEye)
914 aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoRightF());
915 aContext->ApplyProjectionMatrix();
918 myWorkspace->SetEnvironmentTexture (myTextureEnv);
920 renderScene (theProjection, theOutputFBO, theToDrawImmediate);
922 myWorkspace->SetEnvironmentTexture (Handle(OpenGl_Texture)());
924 // ===============================
926 // ===============================
928 // Resetting GL parameters according to the default aspects
929 // in order to synchronize GL state with the graphic driver state
930 // before drawing auxiliary stuff (trihedrons, overlayer)
931 myWorkspace->ResetAppliedAspect();
934 // We need to disable (unbind) all shaders programs to ensure
935 // that all objects without specified aspect will be drawn
936 // correctly (such as background)
937 aContext->BindProgram (NULL);
940 if (!theToDrawImmediate)
942 renderTrihedron (myWorkspace);
944 // Restore face culling
945 if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
949 glEnable (GL_CULL_FACE);
950 glCullFace (GL_BACK);
953 glDisable (GL_CULL_FACE);
957 // ==============================================================
958 // Step 6: Keep shader manager informed about last View
959 // ==============================================================
961 if (!aManager.IsNull())
963 aManager->SetLastView (this);
967 // =======================================================================
968 // function : InvalidateBVHData
970 // =======================================================================
971 void OpenGl_View::InvalidateBVHData (const Graphic3d_ZLayerId theLayerId)
973 myZLayers.InvalidateBVHData (theLayerId);
976 //=======================================================================
977 //function : renderStructs
979 //=======================================================================
980 void OpenGl_View::renderStructs (Graphic3d_Camera::Projection theProjection,
981 OpenGl_FrameBuffer* theReadDrawFbo,
982 const Standard_Boolean theToDrawImmediate)
984 if ( myZLayers.NbStructures() <= 0 )
987 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
988 Standard_Boolean toRenderGL = theToDrawImmediate ||
989 myRenderParams.Method != Graphic3d_RM_RAYTRACING ||
990 myRaytraceInitStatus == OpenGl_RT_FAIL ||
995 toRenderGL = !initRaytraceResources (aCtx) ||
996 !updateRaytraceGeometry (OpenGl_GUM_CHECK, myId, aCtx);
998 toRenderGL |= !myIsRaytraceDataValid; // if no ray-trace data use OpenGL
1002 const Standard_Integer aSizeX = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeX() : myWindow->Width();
1003 const Standard_Integer aSizeY = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeY() : myWindow->Height();
1004 myOpenGlFBO ->InitLazy (aCtx, aSizeX, aSizeY, myFboColorFormat, myFboDepthFormat, 0);
1006 if (myRaytraceFilter.IsNull())
1007 myRaytraceFilter = new OpenGl_RaytraceFilter;
1009 myRaytraceFilter->SetPrevRenderFilter (myWorkspace->GetRenderFilter());
1011 if (theReadDrawFbo != NULL)
1012 theReadDrawFbo->UnbindBuffer (aCtx);
1014 // Prepare preliminary OpenGL output
1015 if (aCtx->arbFBOBlit != NULL)
1017 // Render bottom OSD layer
1018 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Bottom);
1020 myWorkspace->SetRenderFilter (myRaytraceFilter);
1022 if (theReadDrawFbo != NULL)
1024 theReadDrawFbo->BindReadBuffer (aCtx);
1028 aCtx->arbFBO->glBindFramebuffer (GL_READ_FRAMEBUFFER, 0);
1031 myOpenGlFBO->BindDrawBuffer (aCtx);
1033 aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, aSizeX, aSizeY,
1034 0, 0, aSizeX, aSizeY,
1035 GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT,
1038 // Render non-polygonal elements in default layer
1039 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Default);
1041 myWorkspace->SetRenderFilter (myRaytraceFilter->PrevRenderFilter());
1044 if (theReadDrawFbo != NULL)
1046 theReadDrawFbo->BindBuffer (aCtx);
1050 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, 0);
1053 // Reset OpenGl aspects state to default to avoid enabling of
1054 // backface culling which is not supported in ray-tracing.
1055 myWorkspace->ResetAppliedAspect();
1057 // Ray-tracing polygonal primitive arrays
1058 raytrace (aSizeX, aSizeY, theProjection, theReadDrawFbo, aCtx);
1060 // Render upper (top and topmost) OpenGL layers
1061 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Upper);
1065 // Redraw 3D scene using OpenGL in standard
1066 // mode or in case of ray-tracing failure
1069 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_All);
1071 // Set flag that scene was redrawn by standard pipeline
1072 myWasRedrawnGL = Standard_True;
1076 //=======================================================================
1077 //function : renderTrihedron
1079 //=======================================================================
1080 void OpenGl_View::renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace)
1082 // display global trihedron
1083 if (myToShowTrihedron)
1085 // disable environment texture
1086 Handle(OpenGl_Texture) anEnvironmentTexture = theWorkspace->EnvironmentTexture();
1087 theWorkspace->SetEnvironmentTexture (Handle(OpenGl_Texture)());
1089 myTrihedron.Render (theWorkspace);
1091 // restore environment texture
1092 theWorkspace->SetEnvironmentTexture (anEnvironmentTexture);
1094 if (myToShowGradTrihedron)
1096 myGraduatedTrihedron.Render (theWorkspace);
1100 // =======================================================================
1101 // function : Invalidate
1103 // =======================================================================
1104 void OpenGl_View::Invalidate()
1106 myBackBufferRestored = Standard_False;
1109 //=======================================================================
1110 //function : renderScene
1112 //=======================================================================
1113 void OpenGl_View::renderScene (Graphic3d_Camera::Projection theProjection,
1114 OpenGl_FrameBuffer* theReadDrawFbo,
1115 const Standard_Boolean theToDrawImmediate)
1117 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
1120 // set printing scale/tiling transformation
1121 Handle(OpenGl_PrinterContext) aPrintContext = myWorkspace->PrinterContext();
1122 if (!aPrintContext.IsNull())
1124 aContext->ProjectionState.Push();
1125 aContext->ProjectionState.SetCurrent (aPrintContext->ProjTransformation() * aContext->ProjectionState.Current());
1126 aContext->ApplyProjectionMatrix();
1130 // Specify clipping planes in view transformation space
1131 aContext->ChangeClipping().RemoveAll (aContext);
1132 if (!myClipPlanes.IsEmpty())
1134 Graphic3d_SequenceOfHClipPlane aUserPlanes;
1135 Graphic3d_SequenceOfHClipPlane::Iterator aClippingIt (myClipPlanes);
1136 for (; aClippingIt.More(); aClippingIt.Next())
1138 const Handle(Graphic3d_ClipPlane)& aClipPlane = aClippingIt.Value();
1139 if (aClipPlane->IsOn())
1141 aUserPlanes.Append (aClipPlane);
1145 if (!aUserPlanes.IsEmpty())
1147 aContext->ChangeClipping().AddWorld (aContext, aUserPlanes);
1150 aContext->ShaderManager()->UpdateClippingState();
1153 #if !defined(GL_ES_VERSION_2_0)
1155 if (aContext->core11 != NULL)
1158 Graphic3d_Vec4 anAmbientColor (THE_DEFAULT_AMBIENT[0],
1159 THE_DEFAULT_AMBIENT[1],
1160 THE_DEFAULT_AMBIENT[2],
1161 THE_DEFAULT_AMBIENT[3]);
1162 GLenum aLightGlId = GL_LIGHT0;
1164 OpenGl_ListOfLight::Iterator aLightIt (myShadingModel == Graphic3d_TOSM_NONE ? myNoShadingLight : myLights);
1165 for (; aLightIt.More(); aLightIt.Next())
1167 bindLight (aLightIt.Value(), aLightGlId, anAmbientColor, myWorkspace);
1170 // apply accumulated ambient color
1171 anAmbientColor.a() = 1.0f;
1172 glLightModelfv (GL_LIGHT_MODEL_AMBIENT, anAmbientColor.GetData());
1174 if (aLightGlId != GL_LIGHT0)
1176 glEnable (GL_LIGHTING);
1178 // switch off unused lights
1179 for (; aLightGlId <= GL_LIGHT7; ++aLightGlId)
1181 glDisable (aLightGlId);
1186 // Clear status bitfields
1187 myWorkspace->NamedStatus &= ~(OPENGL_NS_2NDPASSNEED | OPENGL_NS_2NDPASSDO);
1190 renderStructs (theProjection, theReadDrawFbo, theToDrawImmediate);
1191 myWorkspace->DisableTexture();
1194 if (myWorkspace->NamedStatus & OPENGL_NS_2NDPASSNEED)
1196 myWorkspace->NamedStatus |= OPENGL_NS_2NDPASSDO;
1198 // Remember OpenGl properties
1199 GLint aSaveBlendDst = GL_ONE_MINUS_SRC_ALPHA, aSaveBlendSrc = GL_SRC_ALPHA;
1200 GLint aSaveZbuffFunc;
1201 GLboolean aSaveZbuffWrite;
1202 glGetBooleanv (GL_DEPTH_WRITEMASK, &aSaveZbuffWrite);
1203 glGetIntegerv (GL_DEPTH_FUNC, &aSaveZbuffFunc);
1204 #if !defined(GL_ES_VERSION_2_0)
1205 glGetIntegerv (GL_BLEND_DST, &aSaveBlendDst);
1206 glGetIntegerv (GL_BLEND_SRC, &aSaveBlendSrc);
1208 GLboolean wasZbuffEnabled = glIsEnabled (GL_DEPTH_TEST);
1209 GLboolean wasBlendEnabled = glIsEnabled (GL_BLEND);
1211 // Change the properties for second rendering pass
1212 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1213 glEnable (GL_BLEND);
1215 glDepthFunc (GL_EQUAL);
1216 glDepthMask (GL_FALSE);
1217 glEnable (GL_DEPTH_TEST);
1220 renderStructs (theProjection, theReadDrawFbo, theToDrawImmediate);
1221 myWorkspace->DisableTexture();
1223 // Restore properties back
1224 glBlendFunc (aSaveBlendSrc, aSaveBlendDst);
1225 if (!wasBlendEnabled)
1226 glDisable (GL_BLEND);
1228 glDepthFunc (aSaveZbuffFunc);
1229 glDepthMask (aSaveZbuffWrite);
1230 if (!wasZbuffEnabled)
1231 glDisable (GL_DEPTH_FUNC);
1234 // Apply restored view matrix.
1235 aContext->ApplyWorldViewMatrix();
1237 aContext->ChangeClipping().RemoveAll (aContext);
1238 if (!myClipPlanes.IsEmpty())
1240 aContext->ShaderManager()->RevertClippingState();
1244 // set printing scale/tiling transformation
1245 if (!aPrintContext.IsNull())
1247 aContext->ProjectionState.Pop();
1248 aContext->ApplyProjectionMatrix();
1253 // =======================================================================
1254 // function : bindDefaultFbo
1256 // =======================================================================
1257 void OpenGl_View::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
1259 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1260 OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
1262 : (!aCtx->DefaultFrameBuffer().IsNull()
1263 && aCtx->DefaultFrameBuffer()->IsValid()
1264 ? aCtx->DefaultFrameBuffer().operator->()
1268 anFbo->BindBuffer (aCtx);
1269 anFbo->SetupViewport (aCtx);
1273 #if !defined(GL_ES_VERSION_2_0)
1274 aCtx->SetReadDrawBuffer (GL_BACK);
1276 if (aCtx->arbFBO != NULL)
1278 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1281 aCtx->core11fwd->glViewport (0, 0, myWindow->Width(), myWindow->Height());
1285 // =======================================================================
1286 // function : initBlitQuad
1288 // =======================================================================
1289 OpenGl_VertexBuffer* OpenGl_View::initBlitQuad (const Standard_Boolean theToFlip)
1291 OpenGl_VertexBuffer* aVerts = NULL;
1294 aVerts = &myFullScreenQuad;
1295 if (!aVerts->IsValid())
1297 OpenGl_Vec4 aQuad[4] =
1299 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
1300 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 1.0f),
1301 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
1302 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 1.0f)
1304 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1309 aVerts = &myFullScreenQuadFlip;
1310 if (!aVerts->IsValid())
1312 OpenGl_Vec4 aQuad[4] =
1314 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 1.0f),
1315 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 0.0f),
1316 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 1.0f),
1317 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 0.0f)
1319 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1325 // =======================================================================
1326 // function : blitBuffers
1328 // =======================================================================
1329 bool OpenGl_View::blitBuffers (OpenGl_FrameBuffer* theReadFbo,
1330 OpenGl_FrameBuffer* theDrawFbo,
1331 const Standard_Boolean theToFlip)
1333 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1334 if (theReadFbo == NULL || aCtx->IsFeedback())
1338 else if (theReadFbo == theDrawFbo)
1343 // clear destination before blitting
1344 if (theDrawFbo != NULL
1345 && theDrawFbo->IsValid())
1347 theDrawFbo->BindBuffer (aCtx);
1351 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1353 #if !defined(GL_ES_VERSION_2_0)
1354 aCtx->core20fwd->glClearDepth (1.0);
1356 aCtx->core20fwd->glClearDepthf (1.0f);
1358 aCtx->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1360 #if !defined(GL_ES_VERSION_2_0)
1361 if (aCtx->arbFBOBlit != NULL
1362 && theReadFbo->NbSamples() != 0)
1364 GLbitfield aCopyMask = 0;
1365 theReadFbo->BindReadBuffer (aCtx);
1366 if (theDrawFbo != NULL
1367 && theDrawFbo->IsValid())
1369 theDrawFbo->BindDrawBuffer (aCtx);
1370 if (theDrawFbo->HasColor()
1371 && theReadFbo->HasColor())
1373 aCopyMask |= GL_COLOR_BUFFER_BIT;
1375 if (theDrawFbo->HasDepth()
1376 && theReadFbo->HasDepth())
1378 aCopyMask |= GL_DEPTH_BUFFER_BIT;
1383 if (theReadFbo->HasColor())
1385 aCopyMask |= GL_COLOR_BUFFER_BIT;
1387 if (theReadFbo->HasDepth())
1389 aCopyMask |= GL_DEPTH_BUFFER_BIT;
1391 aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1394 // we don't copy stencil buffer here... does it matter for performance?
1395 aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, theReadFbo->GetVPSizeX(), theReadFbo->GetVPSizeY(),
1396 0, 0, theReadFbo->GetVPSizeX(), theReadFbo->GetVPSizeY(),
1397 aCopyMask, GL_NEAREST);
1398 const int anErr = ::glGetError();
1399 if (anErr != GL_NO_ERROR)
1401 // glBlitFramebuffer() might fail in several cases:
1402 // - Both FBOs have MSAA and they are samples number does not match.
1403 // OCCT checks that this does not happen,
1404 // however some graphics drivers provide an option for overriding MSAA.
1405 // In this case window MSAA might be non-zero (and application can not check it)
1406 // and might not match MSAA of our offscreen FBOs.
1407 // - Pixel formats of FBOs do not match.
1408 // This also might happen with window has pixel format,
1409 // e.g. Mesa fails blitting RGBA8 -> RGB8 while other drivers support this conversion.
1410 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "FBO blitting has failed [Error #" + anErr + "]\n"
1411 + " Please check your graphics driver settings or try updating driver.";
1412 if (theReadFbo->NbSamples() != 0)
1414 myToDisableMSAA = true;
1415 aMsg += "\n MSAA settings should not be overridden by driver!";
1417 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1418 GL_DEBUG_TYPE_ERROR,
1420 GL_DEBUG_SEVERITY_HIGH,
1424 if (theDrawFbo != NULL
1425 && theDrawFbo->IsValid())
1427 theDrawFbo->BindBuffer (aCtx);
1431 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1437 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1438 aCtx->core20fwd->glDepthMask (GL_TRUE);
1439 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1441 myWorkspace->DisableTexture();
1443 OpenGl_VertexBuffer* aVerts = initBlitQuad (theToFlip);
1444 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1445 if (aVerts->IsValid()
1446 && aManager->BindFboBlitProgram())
1448 theReadFbo->ColorTexture() ->Bind (aCtx, GL_TEXTURE0 + 0);
1449 theReadFbo->DepthStencilTexture()->Bind (aCtx, GL_TEXTURE0 + 1);
1450 aVerts->BindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1452 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1454 aVerts->UnbindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1455 theReadFbo->DepthStencilTexture()->Unbind (aCtx, GL_TEXTURE0 + 1);
1456 theReadFbo->ColorTexture() ->Unbind (aCtx, GL_TEXTURE0 + 0);
1457 aCtx->BindProgram (NULL);
1461 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1462 + "Error! FBO blitting has failed";
1463 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1464 GL_DEBUG_TYPE_ERROR,
1466 GL_DEBUG_SEVERITY_HIGH,
1468 myHasFboBlit = Standard_False;
1469 theReadFbo->Release (aCtx.operator->());
1476 // =======================================================================
1477 // function : drawStereoPair
1479 // =======================================================================
1480 void OpenGl_View::drawStereoPair (OpenGl_FrameBuffer* theDrawFbo)
1482 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1483 bindDefaultFbo (theDrawFbo);
1484 OpenGl_FrameBuffer* aPair[2] =
1486 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1487 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1489 if (aPair[0] == NULL
1491 || !myTransientDrawToFront)
1493 aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
1494 aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
1497 if (aPair[0] == NULL
1498 || aPair[1] == NULL)
1503 if (aPair[0]->NbSamples() != 0)
1505 // resolve MSAA buffers before drawing
1506 if (!myOpenGlFBO ->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, myFboDepthFormat, 0)
1507 || !myOpenGlFBO2->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, 0, 0))
1509 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1510 GL_DEBUG_TYPE_ERROR,
1512 GL_DEBUG_SEVERITY_HIGH,
1513 "Error! Unable to allocate FBO for blitting stereo pair");
1514 bindDefaultFbo (theDrawFbo);
1518 if (!blitBuffers (aPair[0], myOpenGlFBO .operator->(), Standard_False)
1519 || !blitBuffers (aPair[1], myOpenGlFBO2.operator->(), Standard_False))
1521 bindDefaultFbo (theDrawFbo);
1525 aPair[0] = myOpenGlFBO .operator->();
1526 aPair[1] = myOpenGlFBO2.operator->();
1527 bindDefaultFbo (theDrawFbo);
1532 Standard_Integer left;
1533 Standard_Integer top;
1534 Standard_Integer right;
1535 Standard_Integer bottom;
1536 Standard_Integer dx() { return right - left; }
1537 Standard_Integer dy() { return bottom - top; }
1540 myWindow->PlatformWindow()->Position (aGeom.left, aGeom.top, aGeom.right, aGeom.bottom);
1542 Standard_Boolean toReverse = myRenderParams.ToReverseStereo;
1543 const Standard_Boolean isOddY = (aGeom.top + aGeom.dy()) % 2 == 1;
1544 const Standard_Boolean isOddX = aGeom.left % 2 == 1;
1546 && (myRenderParams.StereoMode == Graphic3d_StereoMode_RowInterlaced
1547 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1549 toReverse = !toReverse;
1552 && (myRenderParams.StereoMode == Graphic3d_StereoMode_ColumnInterlaced
1553 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1555 toReverse = !toReverse;
1560 std::swap (aPair[0], aPair[1]);
1563 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1564 aCtx->core20fwd->glDepthMask (GL_TRUE);
1565 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1567 myWorkspace->DisableTexture();
1568 OpenGl_VertexBuffer* aVerts = initBlitQuad (myToFlipOutput);
1570 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1571 if (aVerts->IsValid()
1572 && aManager->BindStereoProgram (myRenderParams.StereoMode))
1574 if (myRenderParams.StereoMode == Graphic3d_StereoMode_Anaglyph)
1576 OpenGl_Mat4 aFilterL, aFilterR;
1577 aFilterL.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1578 aFilterR.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1579 switch (myRenderParams.AnaglyphFilter)
1581 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Simple:
1583 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1584 aFilterR.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1585 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1588 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Optimized:
1590 aFilterL.SetRow (0, Graphic3d_Vec4 ( 0.4154f, 0.4710f, 0.16666667f, 0.0f));
1591 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.0458f, -0.0484f, -0.0257f, 0.0f));
1592 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.0547f, -0.0615f, 0.0128f, 0.0f));
1593 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1594 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.01090909f, -0.03636364f, -0.00606061f, 0.0f));
1595 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.37560000f, 0.73333333f, 0.01111111f, 0.0f));
1596 aFilterR.SetRow (2, Graphic3d_Vec4 (-0.06510000f, -0.12870000f, 1.29710000f, 0.0f));
1597 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1600 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Simple:
1602 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1603 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1604 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1607 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Optimized:
1609 aFilterL.SetRow (0, Graphic3d_Vec4 ( 1.062f, -0.205f, 0.299f, 0.0f));
1610 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.026f, 0.908f, 0.068f, 0.0f));
1611 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.038f, -0.173f, 0.022f, 0.0f));
1612 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1613 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.016f, -0.123f, -0.017f, 0.0f));
1614 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.006f, 0.062f, -0.017f, 0.0f));
1615 aFilterR.SetRow (2, Graphic3d_Vec4 ( 0.094f, 0.185f, 0.911f, 0.0f));
1616 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1619 case Graphic3d_RenderingParams::Anaglyph_GreenMagenta_Simple:
1621 aFilterR.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1622 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1623 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1626 case Graphic3d_RenderingParams::Anaglyph_UserDefined:
1628 aFilterL = myRenderParams.AnaglyphLeft;
1629 aFilterR = myRenderParams.AnaglyphRight;
1633 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultL", aFilterL);
1634 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultR", aFilterR);
1637 aPair[0]->ColorTexture()->Bind (aCtx, GL_TEXTURE0 + 0);
1638 aPair[1]->ColorTexture()->Bind (aCtx, GL_TEXTURE0 + 1);
1639 aVerts->BindVertexAttrib (aCtx, 0);
1641 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1643 aVerts->UnbindVertexAttrib (aCtx, 0);
1644 aPair[1]->ColorTexture()->Unbind (aCtx, GL_TEXTURE0 + 1);
1645 aPair[0]->ColorTexture()->Unbind (aCtx, GL_TEXTURE0 + 0);
1649 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1650 + "Error! Anaglyph has failed";
1651 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1652 GL_DEBUG_TYPE_ERROR,
1654 GL_DEBUG_SEVERITY_HIGH,
1659 // =======================================================================
1660 // function : copyBackToFront
1662 // =======================================================================
1663 void OpenGl_View::copyBackToFront()
1665 #if !defined(GL_ES_VERSION_2_0)
1667 OpenGl_Mat4 aProjectMat;
1668 Graphic3d_TransformUtils::Ortho2D (aProjectMat,
1669 0.f, static_cast<GLfloat> (myWindow->Width()), 0.f, static_cast<GLfloat> (myWindow->Height()));
1671 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1672 aCtx->WorldViewState.Push();
1673 aCtx->ProjectionState.Push();
1675 aCtx->WorldViewState.SetIdentity();
1676 aCtx->ProjectionState.SetCurrent (aProjectMat);
1678 aCtx->ApplyProjectionMatrix();
1679 aCtx->ApplyWorldViewMatrix();
1681 aCtx->DisableFeatures();
1683 switch (aCtx->DrawBuffer())
1687 aCtx->SetReadBuffer (GL_BACK_LEFT);
1688 aCtx->SetDrawBuffer (GL_FRONT_LEFT);
1693 aCtx->SetReadBuffer (GL_BACK_RIGHT);
1694 aCtx->SetDrawBuffer (GL_FRONT_RIGHT);
1699 aCtx->SetReadBuffer (GL_BACK);
1700 aCtx->SetDrawBuffer (GL_FRONT);
1705 glRasterPos2i (0, 0);
1706 glCopyPixels (0, 0, myWindow->Width() + 1, myWindow->Height() + 1, GL_COLOR);
1707 //glCopyPixels (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
1709 aCtx->EnableFeatures();
1711 aCtx->WorldViewState.Pop();
1712 aCtx->ProjectionState.Pop();
1713 aCtx->ApplyProjectionMatrix();
1715 // read/write from front buffer now
1716 aCtx->SetReadBuffer (aCtx->DrawBuffer());
1718 myIsImmediateDrawn = Standard_False;