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);
898 && aContext->core11 != NULL)
900 Standard_Real aFogFrontConverted = (Standard_Real )myFog.Front + myCamera->Distance();
901 if (myCamera->ZFar() < aFogFrontConverted)
903 aFogFrontConverted = myCamera->ZFar();
904 myFog.Front = (Standard_ShortReal )(aFogFrontConverted - myCamera->Distance());
907 Standard_Real aFogBackConverted = (Standard_Real )myFog.Back + myCamera->Distance();
908 if (myCamera->ZFar() < aFogFrontConverted)
910 aFogBackConverted = myCamera->ZFar();
911 myFog.Back = (Standard_ShortReal )(aFogBackConverted - myCamera->Distance());
914 if (aFogFrontConverted > aFogBackConverted)
916 myFog.Front = (Standard_ShortReal )(aFogFrontConverted - myCamera->Distance());
917 myFog.Back = (Standard_ShortReal )(aFogBackConverted - myCamera->Distance());
920 glFogi(GL_FOG_MODE, GL_LINEAR);
921 glFogf(GL_FOG_START, (Standard_ShortReal )aFogFrontConverted);
922 glFogf(GL_FOG_END, (Standard_ShortReal )aFogBackConverted);
923 glFogfv(GL_FOG_COLOR, myFog.Color.GetData());
926 else if (aContext->core11 != NULL)
931 // Apply InteriorShadingMethod
932 if (aContext->core11 != NULL)
934 aContext->core11->glShadeModel (myShadingModel == Graphic3d_TOSM_FACET
935 || myShadingModel == Graphic3d_TOSM_NONE ? GL_FLAT : GL_SMOOTH);
939 aManager->SetShadingModel (myShadingModel);
942 if (theProjection == Graphic3d_Camera::Projection_MonoLeftEye)
944 aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoLeftF());
945 aContext->ApplyProjectionMatrix();
947 else if (theProjection == Graphic3d_Camera::Projection_MonoRightEye)
949 aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoRightF());
950 aContext->ApplyProjectionMatrix();
953 myWorkspace->SetEnvironmentTexture (myTextureEnv);
955 renderScene (theProjection, theOutputFBO, theToDrawImmediate);
957 myWorkspace->SetEnvironmentTexture (Handle(OpenGl_Texture)());
959 // ===============================
961 // ===============================
963 // Resetting GL parameters according to the default aspects
964 // in order to synchronize GL state with the graphic driver state
965 // before drawing auxiliary stuff (trihedrons, overlayer)
966 myWorkspace->ResetAppliedAspect();
969 // We need to disable (unbind) all shaders programs to ensure
970 // that all objects without specified aspect will be drawn
971 // correctly (such as background)
972 aContext->BindProgram (NULL);
975 if (!theToDrawImmediate)
977 renderTrihedron (myWorkspace);
979 // Restore face culling
980 if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
984 glEnable (GL_CULL_FACE);
985 glCullFace (GL_BACK);
988 glDisable (GL_CULL_FACE);
992 // ==============================================================
993 // Step 6: Keep shader manager informed about last View
994 // ==============================================================
996 if (!aManager.IsNull())
998 aManager->SetLastView (this);
1002 // =======================================================================
1003 // function : InvalidateBVHData
1005 // =======================================================================
1006 void OpenGl_View::InvalidateBVHData (const Graphic3d_ZLayerId theLayerId)
1008 myZLayers.InvalidateBVHData (theLayerId);
1011 //=======================================================================
1012 //function : renderStructs
1014 //=======================================================================
1015 void OpenGl_View::renderStructs (Graphic3d_Camera::Projection theProjection,
1016 OpenGl_FrameBuffer* theReadDrawFbo,
1017 const Standard_Boolean theToDrawImmediate)
1019 if ( myZLayers.NbStructures() <= 0 )
1022 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1023 Standard_Boolean toRenderGL = theToDrawImmediate ||
1024 myRenderParams.Method != Graphic3d_RM_RAYTRACING ||
1025 myRaytraceInitStatus == OpenGl_RT_FAIL ||
1030 toRenderGL = !initRaytraceResources (aCtx) ||
1031 !updateRaytraceGeometry (OpenGl_GUM_CHECK, myId, aCtx);
1033 toRenderGL |= !myIsRaytraceDataValid; // if no ray-trace data use OpenGL
1037 const Standard_Integer aSizeX = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeX() : myWindow->Width();
1038 const Standard_Integer aSizeY = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeY() : myWindow->Height();
1039 myOpenGlFBO ->InitLazy (aCtx, aSizeX, aSizeY, myFboColorFormat, myFboDepthFormat, 0);
1041 if (myRaytraceFilter.IsNull())
1042 myRaytraceFilter = new OpenGl_RaytraceFilter;
1044 myRaytraceFilter->SetPrevRenderFilter (myWorkspace->GetRenderFilter());
1046 if (theReadDrawFbo != NULL)
1047 theReadDrawFbo->UnbindBuffer (aCtx);
1049 // Prepare preliminary OpenGL output
1050 if (aCtx->arbFBOBlit != NULL)
1052 // Render bottom OSD layer
1053 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Bottom);
1055 myWorkspace->SetRenderFilter (myRaytraceFilter);
1057 if (theReadDrawFbo != NULL)
1059 theReadDrawFbo->BindReadBuffer (aCtx);
1063 aCtx->arbFBO->glBindFramebuffer (GL_READ_FRAMEBUFFER, 0);
1066 myOpenGlFBO->BindDrawBuffer (aCtx);
1068 aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, aSizeX, aSizeY,
1069 0, 0, aSizeX, aSizeY,
1070 GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT,
1073 // Render non-polygonal elements in default layer
1074 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Default);
1076 myWorkspace->SetRenderFilter (myRaytraceFilter->PrevRenderFilter());
1079 if (theReadDrawFbo != NULL)
1081 theReadDrawFbo->BindBuffer (aCtx);
1085 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, 0);
1088 // Reset OpenGl aspects state to default to avoid enabling of
1089 // backface culling which is not supported in ray-tracing.
1090 myWorkspace->ResetAppliedAspect();
1092 // Ray-tracing polygonal primitive arrays
1093 raytrace (aSizeX, aSizeY, theProjection, theReadDrawFbo, aCtx);
1095 // Render upper (top and topmost) OpenGL layers
1096 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Upper);
1100 // Redraw 3D scene using OpenGL in standard
1101 // mode or in case of ray-tracing failure
1104 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_All);
1106 // Set flag that scene was redrawn by standard pipeline
1107 myWasRedrawnGL = Standard_True;
1111 //=======================================================================
1112 //function : renderTrihedron
1114 //=======================================================================
1115 void OpenGl_View::renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace)
1117 // display global trihedron
1118 if (myToShowTrihedron)
1120 // disable environment texture
1121 Handle(OpenGl_Texture) anEnvironmentTexture = theWorkspace->EnvironmentTexture();
1122 theWorkspace->SetEnvironmentTexture (Handle(OpenGl_Texture)());
1124 myTrihedron.Render (theWorkspace);
1126 // restore environment texture
1127 theWorkspace->SetEnvironmentTexture (anEnvironmentTexture);
1129 if (myToShowGradTrihedron)
1131 myGraduatedTrihedron.Render (theWorkspace);
1135 // =======================================================================
1136 // function : Invalidate
1138 // =======================================================================
1139 void OpenGl_View::Invalidate()
1141 myBackBufferRestored = Standard_False;
1144 //=======================================================================
1145 //function : renderScene
1147 //=======================================================================
1148 void OpenGl_View::renderScene (Graphic3d_Camera::Projection theProjection,
1149 OpenGl_FrameBuffer* theReadDrawFbo,
1150 const Standard_Boolean theToDrawImmediate)
1152 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
1154 if (myZClip.Back.IsOn || myZClip.Front.IsOn)
1156 Handle(Graphic3d_ClipPlane) aPlaneBack;
1157 Handle(Graphic3d_ClipPlane) aPlaneFront;
1159 if (myZClip.Back.IsOn)
1161 Standard_Real aClipBackConverted = (Standard_Real )myZClip.Front.Limit + myCamera->Distance();
1162 if (myCamera->ZFar() < aClipBackConverted)
1164 aClipBackConverted = myCamera->ZFar();
1165 myZClip.Back.Limit = (Standard_ShortReal )(aClipBackConverted - myCamera->Distance());
1167 const Graphic3d_ClipPlane::Equation aBackEquation (0.0, 0.0, 1.0, (Standard_ShortReal )aClipBackConverted);
1168 aPlaneBack = new Graphic3d_ClipPlane (aBackEquation);
1171 if (myZClip.Front.IsOn)
1173 Standard_Real aClipFrontConverted = (Standard_Real )myZClip.Front.Limit + myCamera->Distance();
1174 if (myCamera->ZNear() > aClipFrontConverted)
1176 aClipFrontConverted = myCamera->ZNear();
1177 myZClip.Front.Limit = (Standard_ShortReal )(aClipFrontConverted - myCamera->Distance());
1179 const Graphic3d_ClipPlane::Equation aFrontEquation (0.0, 0.0, -1.0, (Standard_ShortReal )-aClipFrontConverted);
1180 aPlaneFront = new Graphic3d_ClipPlane (aFrontEquation);
1183 // Specify slicing planes with identity transformation
1184 if (!aPlaneBack.IsNull() || !aPlaneFront.IsNull())
1186 Graphic3d_SequenceOfHClipPlane aSlicingPlanes;
1187 if (!aPlaneBack.IsNull())
1189 aSlicingPlanes.Append (aPlaneBack);
1192 if (!aPlaneFront.IsNull())
1194 aSlicingPlanes.Append (aPlaneFront);
1197 // add planes at loaded view matrix state
1198 aContext->ChangeClipping().AddView (aContext, aSlicingPlanes);
1201 aContext->ShaderManager()->UpdateClippingState();
1205 // set printing scale/tiling transformation
1206 Handle(OpenGl_PrinterContext) aPrintContext = myWorkspace->PrinterContext();
1207 if (!aPrintContext.IsNull())
1209 aContext->ProjectionState.Push();
1210 aContext->ProjectionState.SetCurrent (aPrintContext->ProjTransformation() * aContext->ProjectionState.Current());
1211 aContext->ApplyProjectionMatrix();
1215 // Specify clipping planes in view transformation space
1216 if (!myClipPlanes.IsEmpty())
1218 Graphic3d_SequenceOfHClipPlane aUserPlanes;
1219 Graphic3d_SequenceOfHClipPlane::Iterator aClippingIt (myClipPlanes);
1220 for (; aClippingIt.More(); aClippingIt.Next())
1222 const Handle(Graphic3d_ClipPlane)& aClipPlane = aClippingIt.Value();
1223 if (aClipPlane->IsOn())
1225 aUserPlanes.Append (aClipPlane);
1229 if (!aUserPlanes.IsEmpty())
1231 aContext->ChangeClipping().AddWorld (aContext, aUserPlanes);
1234 aContext->ShaderManager()->UpdateClippingState();
1237 #if !defined(GL_ES_VERSION_2_0)
1239 if (aContext->core11 != NULL)
1242 Graphic3d_Vec4 anAmbientColor (THE_DEFAULT_AMBIENT[0],
1243 THE_DEFAULT_AMBIENT[1],
1244 THE_DEFAULT_AMBIENT[2],
1245 THE_DEFAULT_AMBIENT[3]);
1246 GLenum aLightGlId = GL_LIGHT0;
1248 OpenGl_ListOfLight::Iterator aLightIt (myShadingModel == Graphic3d_TOSM_NONE ? myNoShadingLight : myLights);
1249 for (; aLightIt.More(); aLightIt.Next())
1251 bindLight (aLightIt.Value(), aLightGlId, anAmbientColor, myWorkspace);
1254 // apply accumulated ambient color
1255 anAmbientColor.a() = 1.0f;
1256 glLightModelfv (GL_LIGHT_MODEL_AMBIENT, anAmbientColor.GetData());
1258 if (aLightGlId != GL_LIGHT0)
1260 glEnable (GL_LIGHTING);
1262 // switch off unused lights
1263 for (; aLightGlId <= GL_LIGHT7; ++aLightGlId)
1265 glDisable (aLightGlId);
1270 // Clear status bitfields
1271 myWorkspace->NamedStatus &= ~(OPENGL_NS_2NDPASSNEED | OPENGL_NS_2NDPASSDO);
1274 renderStructs (theProjection, theReadDrawFbo, theToDrawImmediate);
1275 myWorkspace->DisableTexture();
1278 if (myWorkspace->NamedStatus & OPENGL_NS_2NDPASSNEED)
1280 myWorkspace->NamedStatus |= OPENGL_NS_2NDPASSDO;
1282 // Remember OpenGl properties
1283 GLint aSaveBlendDst = GL_ONE_MINUS_SRC_ALPHA, aSaveBlendSrc = GL_SRC_ALPHA;
1284 GLint aSaveZbuffFunc;
1285 GLboolean aSaveZbuffWrite;
1286 glGetBooleanv (GL_DEPTH_WRITEMASK, &aSaveZbuffWrite);
1287 glGetIntegerv (GL_DEPTH_FUNC, &aSaveZbuffFunc);
1288 #if !defined(GL_ES_VERSION_2_0)
1289 glGetIntegerv (GL_BLEND_DST, &aSaveBlendDst);
1290 glGetIntegerv (GL_BLEND_SRC, &aSaveBlendSrc);
1292 GLboolean wasZbuffEnabled = glIsEnabled (GL_DEPTH_TEST);
1293 GLboolean wasBlendEnabled = glIsEnabled (GL_BLEND);
1295 // Change the properties for second rendering pass
1296 glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1297 glEnable (GL_BLEND);
1299 glDepthFunc (GL_EQUAL);
1300 glDepthMask (GL_FALSE);
1301 glEnable (GL_DEPTH_TEST);
1304 renderStructs (theProjection, theReadDrawFbo, theToDrawImmediate);
1305 myWorkspace->DisableTexture();
1307 // Restore properties back
1308 glBlendFunc (aSaveBlendSrc, aSaveBlendDst);
1309 if (!wasBlendEnabled)
1310 glDisable (GL_BLEND);
1312 glDepthFunc (aSaveZbuffFunc);
1313 glDepthMask (aSaveZbuffWrite);
1314 if (!wasZbuffEnabled)
1315 glDisable (GL_DEPTH_FUNC);
1318 // Apply restored view matrix.
1319 aContext->ApplyWorldViewMatrix();
1321 aContext->ChangeClipping().RemoveAll (aContext);
1322 if (!myClipPlanes.IsEmpty())
1324 aContext->ShaderManager()->RevertClippingState();
1326 if (myZClip.Back.IsOn || myZClip.Front.IsOn)
1328 aContext->ShaderManager()->RevertClippingState();
1332 // set printing scale/tiling transformation
1333 if (!aPrintContext.IsNull())
1335 aContext->ProjectionState.Pop();
1336 aContext->ApplyProjectionMatrix();
1341 // =======================================================================
1342 // function : bindDefaultFbo
1344 // =======================================================================
1345 void OpenGl_View::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
1347 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1348 OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
1350 : (!aCtx->DefaultFrameBuffer().IsNull()
1351 && aCtx->DefaultFrameBuffer()->IsValid()
1352 ? aCtx->DefaultFrameBuffer().operator->()
1356 anFbo->BindBuffer (aCtx);
1357 anFbo->SetupViewport (aCtx);
1361 #if !defined(GL_ES_VERSION_2_0)
1362 aCtx->SetReadDrawBuffer (GL_BACK);
1364 if (aCtx->arbFBO != NULL)
1366 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1369 aCtx->core11fwd->glViewport (0, 0, myWindow->Width(), myWindow->Height());
1373 // =======================================================================
1374 // function : initBlitQuad
1376 // =======================================================================
1377 OpenGl_VertexBuffer* OpenGl_View::initBlitQuad (const Standard_Boolean theToFlip)
1379 OpenGl_VertexBuffer* aVerts = NULL;
1382 aVerts = &myFullScreenQuad;
1383 if (!aVerts->IsValid())
1385 OpenGl_Vec4 aQuad[4] =
1387 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
1388 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 1.0f),
1389 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
1390 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 1.0f)
1392 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1397 aVerts = &myFullScreenQuadFlip;
1398 if (!aVerts->IsValid())
1400 OpenGl_Vec4 aQuad[4] =
1402 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 1.0f),
1403 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 0.0f),
1404 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 1.0f),
1405 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 0.0f)
1407 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1413 // =======================================================================
1414 // function : blitBuffers
1416 // =======================================================================
1417 bool OpenGl_View::blitBuffers (OpenGl_FrameBuffer* theReadFbo,
1418 OpenGl_FrameBuffer* theDrawFbo,
1419 const Standard_Boolean theToFlip)
1421 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1422 if (theReadFbo == NULL || aCtx->IsFeedback())
1426 else if (theReadFbo == theDrawFbo)
1431 // clear destination before blitting
1432 if (theDrawFbo != NULL
1433 && theDrawFbo->IsValid())
1435 theDrawFbo->BindBuffer (aCtx);
1439 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1441 #if !defined(GL_ES_VERSION_2_0)
1442 aCtx->core20fwd->glClearDepth (1.0);
1444 aCtx->core20fwd->glClearDepthf (1.0f);
1446 aCtx->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1448 #if !defined(GL_ES_VERSION_2_0)
1449 if (aCtx->arbFBOBlit != NULL
1450 && theReadFbo->NbSamples() != 0)
1452 GLbitfield aCopyMask = 0;
1453 theReadFbo->BindReadBuffer (aCtx);
1454 if (theDrawFbo != NULL
1455 && theDrawFbo->IsValid())
1457 theDrawFbo->BindDrawBuffer (aCtx);
1458 if (theDrawFbo->HasColor()
1459 && theReadFbo->HasColor())
1461 aCopyMask |= GL_COLOR_BUFFER_BIT;
1463 if (theDrawFbo->HasDepth()
1464 && theReadFbo->HasDepth())
1466 aCopyMask |= GL_DEPTH_BUFFER_BIT;
1471 if (theReadFbo->HasColor())
1473 aCopyMask |= GL_COLOR_BUFFER_BIT;
1475 if (theReadFbo->HasDepth())
1477 aCopyMask |= GL_DEPTH_BUFFER_BIT;
1479 aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1482 // we don't copy stencil buffer here... does it matter for performance?
1483 aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, theReadFbo->GetVPSizeX(), theReadFbo->GetVPSizeY(),
1484 0, 0, theReadFbo->GetVPSizeX(), theReadFbo->GetVPSizeY(),
1485 aCopyMask, GL_NEAREST);
1486 const int anErr = ::glGetError();
1487 if (anErr != GL_NO_ERROR)
1489 // glBlitFramebuffer() might fail in several cases:
1490 // - Both FBOs have MSAA and they are samples number does not match.
1491 // OCCT checks that this does not happen,
1492 // however some graphics drivers provide an option for overriding MSAA.
1493 // In this case window MSAA might be non-zero (and application can not check it)
1494 // and might not match MSAA of our offscreen FBOs.
1495 // - Pixel formats of FBOs do not match.
1496 // This also might happen with window has pixel format,
1497 // e.g. Mesa fails blitting RGBA8 -> RGB8 while other drivers support this conversion.
1498 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "FBO blitting has failed [Error #" + anErr + "]\n"
1499 + " Please check your graphics driver settings or try updating driver.";
1500 if (theReadFbo->NbSamples() != 0)
1502 myToDisableMSAA = true;
1503 aMsg += "\n MSAA settings should not be overridden by driver!";
1505 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1506 GL_DEBUG_TYPE_ERROR,
1508 GL_DEBUG_SEVERITY_HIGH,
1512 if (theDrawFbo != NULL
1513 && theDrawFbo->IsValid())
1515 theDrawFbo->BindBuffer (aCtx);
1519 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1525 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1526 aCtx->core20fwd->glDepthMask (GL_TRUE);
1527 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1529 myWorkspace->DisableTexture();
1531 OpenGl_VertexBuffer* aVerts = initBlitQuad (theToFlip);
1532 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1533 if (aVerts->IsValid()
1534 && aManager->BindFboBlitProgram())
1536 theReadFbo->ColorTexture() ->Bind (aCtx, GL_TEXTURE0 + 0);
1537 theReadFbo->DepthStencilTexture()->Bind (aCtx, GL_TEXTURE0 + 1);
1538 aVerts->BindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1540 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1542 aVerts->UnbindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1543 theReadFbo->DepthStencilTexture()->Unbind (aCtx, GL_TEXTURE0 + 1);
1544 theReadFbo->ColorTexture() ->Unbind (aCtx, GL_TEXTURE0 + 0);
1545 aCtx->BindProgram (NULL);
1549 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1550 + "Error! FBO blitting has failed";
1551 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1552 GL_DEBUG_TYPE_ERROR,
1554 GL_DEBUG_SEVERITY_HIGH,
1556 myHasFboBlit = Standard_False;
1557 theReadFbo->Release (aCtx.operator->());
1564 // =======================================================================
1565 // function : drawStereoPair
1567 // =======================================================================
1568 void OpenGl_View::drawStereoPair (OpenGl_FrameBuffer* theDrawFbo)
1570 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1571 bindDefaultFbo (theDrawFbo);
1572 OpenGl_FrameBuffer* aPair[2] =
1574 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1575 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1577 if (aPair[0] == NULL
1579 || !myTransientDrawToFront)
1581 aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
1582 aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
1585 if (aPair[0] == NULL
1586 || aPair[1] == NULL)
1591 if (aPair[0]->NbSamples() != 0)
1593 // resolve MSAA buffers before drawing
1594 if (!myOpenGlFBO ->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, myFboDepthFormat, 0)
1595 || !myOpenGlFBO2->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, 0, 0))
1597 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1598 GL_DEBUG_TYPE_ERROR,
1600 GL_DEBUG_SEVERITY_HIGH,
1601 "Error! Unable to allocate FBO for blitting stereo pair");
1602 bindDefaultFbo (theDrawFbo);
1606 if (!blitBuffers (aPair[0], myOpenGlFBO .operator->(), Standard_False)
1607 || !blitBuffers (aPair[1], myOpenGlFBO2.operator->(), Standard_False))
1609 bindDefaultFbo (theDrawFbo);
1613 aPair[0] = myOpenGlFBO .operator->();
1614 aPair[1] = myOpenGlFBO2.operator->();
1615 bindDefaultFbo (theDrawFbo);
1620 Standard_Integer left;
1621 Standard_Integer top;
1622 Standard_Integer right;
1623 Standard_Integer bottom;
1624 Standard_Integer dx() { return right - left; }
1625 Standard_Integer dy() { return bottom - top; }
1628 myWindow->PlatformWindow()->Position (aGeom.left, aGeom.top, aGeom.right, aGeom.bottom);
1630 Standard_Boolean toReverse = myRenderParams.ToReverseStereo;
1631 const Standard_Boolean isOddY = (aGeom.top + aGeom.dy()) % 2 == 1;
1632 const Standard_Boolean isOddX = aGeom.left % 2 == 1;
1634 && (myRenderParams.StereoMode == Graphic3d_StereoMode_RowInterlaced
1635 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1637 toReverse = !toReverse;
1640 && (myRenderParams.StereoMode == Graphic3d_StereoMode_ColumnInterlaced
1641 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1643 toReverse = !toReverse;
1648 std::swap (aPair[0], aPair[1]);
1651 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1652 aCtx->core20fwd->glDepthMask (GL_TRUE);
1653 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1655 myWorkspace->DisableTexture();
1656 OpenGl_VertexBuffer* aVerts = initBlitQuad (myToFlipOutput);
1658 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1659 if (aVerts->IsValid()
1660 && aManager->BindStereoProgram (myRenderParams.StereoMode))
1662 if (myRenderParams.StereoMode == Graphic3d_StereoMode_Anaglyph)
1664 OpenGl_Mat4 aFilterL, aFilterR;
1665 aFilterL.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1666 aFilterR.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1667 switch (myRenderParams.AnaglyphFilter)
1669 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Simple:
1671 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1672 aFilterR.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1673 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1676 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Optimized:
1678 aFilterL.SetRow (0, Graphic3d_Vec4 ( 0.4154f, 0.4710f, 0.16666667f, 0.0f));
1679 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.0458f, -0.0484f, -0.0257f, 0.0f));
1680 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.0547f, -0.0615f, 0.0128f, 0.0f));
1681 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1682 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.01090909f, -0.03636364f, -0.00606061f, 0.0f));
1683 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.37560000f, 0.73333333f, 0.01111111f, 0.0f));
1684 aFilterR.SetRow (2, Graphic3d_Vec4 (-0.06510000f, -0.12870000f, 1.29710000f, 0.0f));
1685 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1688 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Simple:
1690 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1691 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1692 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1695 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Optimized:
1697 aFilterL.SetRow (0, Graphic3d_Vec4 ( 1.062f, -0.205f, 0.299f, 0.0f));
1698 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.026f, 0.908f, 0.068f, 0.0f));
1699 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.038f, -0.173f, 0.022f, 0.0f));
1700 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1701 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.016f, -0.123f, -0.017f, 0.0f));
1702 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.006f, 0.062f, -0.017f, 0.0f));
1703 aFilterR.SetRow (2, Graphic3d_Vec4 ( 0.094f, 0.185f, 0.911f, 0.0f));
1704 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1707 case Graphic3d_RenderingParams::Anaglyph_GreenMagenta_Simple:
1709 aFilterR.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1710 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1711 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1714 case Graphic3d_RenderingParams::Anaglyph_UserDefined:
1716 aFilterL = myRenderParams.AnaglyphLeft;
1717 aFilterR = myRenderParams.AnaglyphRight;
1721 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultL", aFilterL);
1722 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultR", aFilterR);
1725 aPair[0]->ColorTexture()->Bind (aCtx, GL_TEXTURE0 + 0);
1726 aPair[1]->ColorTexture()->Bind (aCtx, GL_TEXTURE0 + 1);
1727 aVerts->BindVertexAttrib (aCtx, 0);
1729 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1731 aVerts->UnbindVertexAttrib (aCtx, 0);
1732 aPair[1]->ColorTexture()->Unbind (aCtx, GL_TEXTURE0 + 1);
1733 aPair[0]->ColorTexture()->Unbind (aCtx, GL_TEXTURE0 + 0);
1737 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1738 + "Error! Anaglyph has failed";
1739 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1740 GL_DEBUG_TYPE_ERROR,
1742 GL_DEBUG_SEVERITY_HIGH,
1747 // =======================================================================
1748 // function : copyBackToFront
1750 // =======================================================================
1751 void OpenGl_View::copyBackToFront()
1753 #if !defined(GL_ES_VERSION_2_0)
1755 OpenGl_Mat4 aProjectMat;
1756 Graphic3d_TransformUtils::Ortho2D (aProjectMat,
1757 0.f, static_cast<GLfloat> (myWindow->Width()), 0.f, static_cast<GLfloat> (myWindow->Height()));
1759 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1760 aCtx->WorldViewState.Push();
1761 aCtx->ProjectionState.Push();
1763 aCtx->WorldViewState.SetIdentity();
1764 aCtx->ProjectionState.SetCurrent (aProjectMat);
1766 aCtx->ApplyProjectionMatrix();
1767 aCtx->ApplyWorldViewMatrix();
1769 aCtx->DisableFeatures();
1771 switch (aCtx->DrawBuffer())
1775 aCtx->SetReadBuffer (GL_BACK_LEFT);
1776 aCtx->SetDrawBuffer (GL_FRONT_LEFT);
1781 aCtx->SetReadBuffer (GL_BACK_RIGHT);
1782 aCtx->SetDrawBuffer (GL_FRONT_RIGHT);
1787 aCtx->SetReadBuffer (GL_BACK);
1788 aCtx->SetDrawBuffer (GL_FRONT);
1793 glRasterPos2i (0, 0);
1794 glCopyPixels (0, 0, myWindow->Width() + 1, myWindow->Height() + 1, GL_COLOR);
1795 //glCopyPixels (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
1797 aCtx->EnableFeatures();
1799 aCtx->WorldViewState.Pop();
1800 aCtx->ProjectionState.Pop();
1801 aCtx->ApplyProjectionMatrix();
1803 // read/write from front buffer now
1804 aCtx->SetReadBuffer (aCtx->DrawBuffer());
1806 myIsImmediateDrawn = Standard_False;