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_StructureManager.hxx>
23 #include <Graphic3d_TextureParams.hxx>
24 #include <Graphic3d_Texture2Dmanual.hxx>
25 #include <Graphic3d_TransformUtils.hxx>
26 #include <Image_AlienPixMap.hxx>
28 #include <NCollection_Mat4.hxx>
30 #include <OpenGl_AspectLine.hxx>
31 #include <OpenGl_Context.hxx>
32 #include <OpenGl_FrameStats.hxx>
33 #include <OpenGl_Matrix.hxx>
34 #include <OpenGl_Workspace.hxx>
35 #include <OpenGl_View.hxx>
36 #include <OpenGl_GraduatedTrihedron.hxx>
37 #include <OpenGl_PrimitiveArray.hxx>
38 #include <OpenGl_ShaderManager.hxx>
39 #include <OpenGl_ShaderProgram.hxx>
40 #include <OpenGl_Structure.hxx>
41 #include <OpenGl_ArbFBO.hxx>
45 //! Format Frame Buffer format for logging messages.
46 static TCollection_AsciiString printFboFormat (const Handle(OpenGl_FrameBuffer)& theFbo)
48 return TCollection_AsciiString() + theFbo->GetInitVPSizeX() + "x" + theFbo->GetInitVPSizeY() + "@" + theFbo->NbSamples();
51 //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
52 static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
53 Standard_Integer theSizeX,
54 Standard_Integer theSizeY,
55 Standard_Integer theNbSamples)
57 return !theFboToCheck->IsValid()
58 && theFboToCheck->GetInitVPSizeX() == theSizeX
59 && theFboToCheck->GetInitVPSizeY() == theSizeY
60 && theFboToCheck->NbSamples() == theNbSamples;
63 //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
64 static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
65 const Handle(OpenGl_FrameBuffer)& theFboRef)
67 return checkWasFailedFbo (theFboToCheck, theFboRef->GetVPSizeX(), theFboRef->GetVPSizeY(), theFboRef->NbSamples());
71 //=======================================================================
72 //function : drawBackground
74 //=======================================================================
75 void OpenGl_View::drawBackground (const Handle(OpenGl_Workspace)& theWorkspace)
77 const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
79 if (!myBgTextureArray->IsDefined() // no texture
80 && !myBgGradientArray->IsDefined()) // no gradient
85 const Standard_Boolean wasUsedZBuffer = theWorkspace->SetUseZBuffer (Standard_False);
88 aCtx->core11fwd->glDisable (GL_DEPTH_TEST);
91 // Drawing background gradient if:
92 // - gradient fill type is not Aspect_GFM_NONE and
93 // - either background texture is no specified or it is drawn in Aspect_FM_CENTERED mode
94 if (myBgGradientArray->IsDefined()
95 && (!myTextureParams->Aspect()->ToMapTexture()
96 || myBgTextureArray->TextureFillMethod() == Aspect_FM_CENTERED
97 || myBgTextureArray->TextureFillMethod() == Aspect_FM_NONE))
99 #if !defined(GL_ES_VERSION_2_0)
100 GLint aShadingModelOld = GL_SMOOTH;
101 if (aCtx->core11 != NULL
102 && aCtx->caps->ffpEnable)
104 aCtx->core11fwd->glDisable (GL_LIGHTING);
105 aCtx->core11fwd->glGetIntegerv (GL_SHADE_MODEL, &aShadingModelOld);
106 aCtx->core11->glShadeModel (GL_SMOOTH);
110 myBgGradientArray->Render (theWorkspace);
112 #if !defined(GL_ES_VERSION_2_0)
113 if (aCtx->core11 != NULL
114 && aCtx->caps->ffpEnable)
116 aCtx->core11->glShadeModel (aShadingModelOld);
121 // Drawing background image if it is defined
122 // (texture is defined and fill type is not Aspect_FM_NONE)
123 if (myBgTextureArray->IsDefined()
124 && myTextureParams->Aspect()->ToMapTexture())
126 aCtx->core11fwd->glDisable (GL_BLEND);
128 const OpenGl_AspectFace* anOldAspectFace = theWorkspace->SetAspectFace (myTextureParams);
129 myBgTextureArray->Render (theWorkspace);
130 theWorkspace->SetAspectFace (anOldAspectFace);
135 theWorkspace->SetUseZBuffer (Standard_True);
136 aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
140 //=======================================================================
143 //=======================================================================
144 void OpenGl_View::Redraw()
146 const Standard_Boolean wasDisabledMSAA = myToDisableMSAA;
147 const Standard_Boolean hadFboBlit = myHasFboBlit;
148 if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
149 && !myCaps->vboDisable
150 && !myCaps->keepArrayData)
152 // caps are shared across all views, thus we need to invalidate all of them
153 // if (myWasRedrawnGL) { myStructureManager->SetDeviceLost(); }
154 myDriver->setDeviceLost();
155 myCaps->keepArrayData = Standard_True;
158 if (!myWorkspace->Activate())
163 myWindow->SetSwapInterval();
166 const Graphic3d_StereoMode aStereoMode = myRenderParams.StereoMode;
167 Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
168 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
169 aCtx->FrameStats()->FrameStart (myWorkspace->View(), false);
171 // release pending GL resources
172 aCtx->ReleaseDelayed();
174 // fetch OpenGl context state
177 OpenGl_FrameBuffer* aFrameBuffer = myFBO.operator->();
178 bool toSwap = aCtx->IsRender()
179 && !aCtx->caps->buffersNoSwap
180 && aFrameBuffer == NULL;
182 const Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWindow->Width();
183 const Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myWindow->Height();
184 const Standard_Integer aRendSizeX = Standard_Integer(myRenderParams.RenderResolutionScale * aSizeX + 0.5f);
185 const Standard_Integer aRendSizeY = Standard_Integer(myRenderParams.RenderResolutionScale * aSizeY + 0.5f);
191 myBackBufferRestored = Standard_False;
192 myIsImmediateDrawn = Standard_False;
196 // determine multisampling parameters
197 Standard_Integer aNbSamples = !myToDisableMSAA && aSizeX == aRendSizeX
198 ? Max (Min (myRenderParams.NbMsaaSamples, aCtx->MaxMsaaSamples()), 0)
202 aNbSamples = OpenGl_Context::GetPowerOfTwo (aNbSamples, aCtx->MaxMsaaSamples());
205 bool toUseOit = myRenderParams.TransparencyMethod == Graphic3d_RTM_BLEND_OIT
206 && checkOitCompatibility (aCtx, aNbSamples > 0);
208 const bool toInitImmediateFbo = myTransientDrawToFront
209 && (!aCtx->caps->useSystemBuffer || (toUseOit && HasImmediateStructures()));
211 if ( aFrameBuffer == NULL
212 && !aCtx->DefaultFrameBuffer().IsNull()
213 && aCtx->DefaultFrameBuffer()->IsValid())
215 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
219 && (myTransientDrawToFront
220 || aProjectType == Graphic3d_Camera::Projection_Stereo
223 || aSizeX != aRendSizeX))
225 if (myMainSceneFbos[0]->GetVPSizeX() != aRendSizeX
226 || myMainSceneFbos[0]->GetVPSizeY() != aRendSizeY
227 || myMainSceneFbos[0]->NbSamples() != aNbSamples)
229 if (!myTransientDrawToFront)
231 myImmediateSceneFbos[0]->Release (aCtx.operator->());
232 myImmediateSceneFbos[1]->Release (aCtx.operator->());
233 myImmediateSceneFbos[0]->ChangeViewport (0, 0);
234 myImmediateSceneFbos[1]->ChangeViewport (0, 0);
237 // prepare FBOs containing main scene
238 // for further blitting and rendering immediate presentations on top
239 if (aCtx->core20fwd != NULL)
241 const bool wasFailedMain0 = checkWasFailedFbo (myMainSceneFbos[0], aRendSizeX, aRendSizeY, aNbSamples);
242 if (!myMainSceneFbos[0]->Init (aCtx, aRendSizeX, aRendSizeY, myFboColorFormat, myFboDepthFormat, aNbSamples)
245 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO "
246 + printFboFormat (myMainSceneFbos[0]) + " initialization has failed";
247 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
251 if (myMainSceneFbos[0]->IsValid() && (toInitImmediateFbo || myImmediateSceneFbos[0]->IsValid()))
253 const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
254 if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
257 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO "
258 + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
259 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
265 myMainSceneFbos [0]->Release (aCtx.operator->());
266 myMainSceneFbos [1]->Release (aCtx.operator->());
267 myImmediateSceneFbos[0]->Release (aCtx.operator->());
268 myImmediateSceneFbos[1]->Release (aCtx.operator->());
269 myMainSceneFbos [0]->ChangeViewport (0, 0);
270 myMainSceneFbos [1]->ChangeViewport (0, 0);
271 myImmediateSceneFbos[0]->ChangeViewport (0, 0);
272 myImmediateSceneFbos[1]->ChangeViewport (0, 0);
275 if (aProjectType == Graphic3d_Camera::Projection_Stereo
276 && myMainSceneFbos[0]->IsValid())
278 const bool wasFailedMain1 = checkWasFailedFbo (myMainSceneFbos[1], myMainSceneFbos[0]);
279 if (!myMainSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
282 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO (second) "
283 + printFboFormat (myMainSceneFbos[1]) + " initialization has failed";
284 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
286 if (!myMainSceneFbos[1]->IsValid())
289 aProjectType = Graphic3d_Camera::Projection_Perspective;
291 else if (!myTransientDrawToFront)
295 else if (!aCtx->HasStereoBuffers() || aStereoMode != Graphic3d_StereoMode_QuadBuffer)
297 const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
298 const bool wasFailedImm1 = checkWasFailedFbo (myImmediateSceneFbos[1], myMainSceneFbos[0]);
299 if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
302 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
303 + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
304 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
306 if (!myImmediateSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
309 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
310 + printFboFormat (myImmediateSceneFbos[1]) + " initialization has failed";
311 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
313 if (!myImmediateSceneFbos[0]->IsValid()
314 || !myImmediateSceneFbos[1]->IsValid())
316 aProjectType = Graphic3d_Camera::Projection_Perspective;
321 // create color and coverage accumulation buffers required for OIT algorithm
324 Standard_Integer anFboIt = 0;
325 for (; anFboIt < 2; ++anFboIt)
327 Handle(OpenGl_FrameBuffer)& aMainSceneFbo = myMainSceneFbos [anFboIt];
328 Handle(OpenGl_FrameBuffer)& aMainSceneFboOit = myMainSceneFbosOit [anFboIt];
329 Handle(OpenGl_FrameBuffer)& anImmediateSceneFbo = myImmediateSceneFbos [anFboIt];
330 Handle(OpenGl_FrameBuffer)& anImmediateSceneFboOit = myImmediateSceneFbosOit[anFboIt];
331 if (aMainSceneFbo->IsValid()
332 && (aMainSceneFboOit->GetVPSizeX() != aRendSizeX
333 || aMainSceneFboOit->GetVPSizeY() != aRendSizeY
334 || aMainSceneFboOit->NbSamples() != aNbSamples))
336 Standard_Integer aColorConfig = 0;
337 for (;;) // seemly responding to driver limitation (GL_FRAMEBUFFER_UNSUPPORTED)
339 if (myFboOitColorConfig.IsEmpty())
341 if (!chooseOitColorConfiguration (aCtx, aColorConfig++, myFboOitColorConfig))
346 if (aMainSceneFboOit->Init (aCtx, aRendSizeX, aRendSizeY, myFboOitColorConfig, aMainSceneFbo->DepthStencilTexture(), aNbSamples))
350 myFboOitColorConfig.Clear();
352 if (!aMainSceneFboOit->IsValid())
357 else if (!aMainSceneFbo->IsValid())
359 aMainSceneFboOit->Release (aCtx.operator->());
360 aMainSceneFboOit->ChangeViewport (0, 0);
363 if (anImmediateSceneFbo->IsValid()
364 && (anImmediateSceneFboOit->GetVPSizeX() != aRendSizeX
365 || anImmediateSceneFboOit->GetVPSizeY() != aRendSizeY
366 || anImmediateSceneFboOit->NbSamples() != aNbSamples))
368 if (!anImmediateSceneFboOit->Init (aCtx, aRendSizeX, aRendSizeY, myFboOitColorConfig,
369 anImmediateSceneFbo->DepthStencilTexture(), aNbSamples))
374 else if (!anImmediateSceneFbo->IsValid())
376 anImmediateSceneFboOit->Release (aCtx.operator->());
377 anImmediateSceneFboOit->ChangeViewport (0, 0);
380 if (anFboIt == 0) // only the first OIT framebuffer is mandatory
382 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
383 "Initialization of float texture framebuffer for use with\n"
384 " blended order-independent transparency rendering algorithm has failed.\n"
385 " Blended order-independent transparency will not be available.\n");
388 myToDisableOITMSAA = Standard_True;
392 myToDisableOIT = Standard_True;
397 if (!toUseOit && myMainSceneFbosOit[0]->IsValid())
399 myMainSceneFbosOit [0]->Release (aCtx.operator->());
400 myMainSceneFbosOit [1]->Release (aCtx.operator->());
401 myImmediateSceneFbosOit[0]->Release (aCtx.operator->());
402 myImmediateSceneFbosOit[1]->Release (aCtx.operator->());
403 myMainSceneFbosOit [0]->ChangeViewport (0, 0);
404 myMainSceneFbosOit [1]->ChangeViewport (0, 0);
405 myImmediateSceneFbosOit[0]->ChangeViewport (0, 0);
406 myImmediateSceneFbosOit[1]->ChangeViewport (0, 0);
409 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
411 OpenGl_FrameBuffer* aMainFbos[2] =
413 myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
414 myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
416 OpenGl_FrameBuffer* aMainFbosOit[2] =
418 myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL,
419 myMainSceneFbosOit[1]->IsValid() ? myMainSceneFbosOit[1].operator->() :
420 myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL
423 OpenGl_FrameBuffer* anImmFbos[2] =
425 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
426 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
428 OpenGl_FrameBuffer* anImmFbosOit[2] =
430 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
431 myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
432 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
435 if (!myTransientDrawToFront)
437 anImmFbos [0] = aMainFbos [0];
438 anImmFbos [1] = aMainFbos [1];
439 anImmFbosOit[0] = aMainFbosOit[0];
440 anImmFbosOit[1] = aMainFbosOit[1];
442 else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
443 || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
445 anImmFbos [0] = NULL;
446 anImmFbos [1] = NULL;
447 anImmFbosOit[0] = NULL;
448 anImmFbosOit[1] = NULL;
451 #if !defined(GL_ES_VERSION_2_0)
452 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
454 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
455 aMainFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
457 redraw (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], aMainFbosOit[0]);
458 myBackBufferRestored = Standard_True;
459 myIsImmediateDrawn = Standard_False;
460 #if !defined(GL_ES_VERSION_2_0)
461 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
463 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
464 anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
465 if (!redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], anImmFbos[0], anImmFbosOit[0]))
469 else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip && toSwap)
474 #if !defined(GL_ES_VERSION_2_0)
475 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
477 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
478 aMainFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
480 redraw (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], aMainFbosOit[1]);
481 myBackBufferRestored = Standard_True;
482 myIsImmediateDrawn = Standard_False;
483 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
484 anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
485 if (!redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], anImmFbos[1], anImmFbosOit[1]))
490 if (anImmFbos[0] != NULL)
492 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(), 1.0f);
493 drawStereoPair (aFrameBuffer);
498 OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : aFrameBuffer;
499 OpenGl_FrameBuffer* aMainFboOit = myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL;
500 OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
501 OpenGl_FrameBuffer* anImmFboOit = NULL;
502 if (!myTransientDrawToFront)
505 anImmFboOit = aMainFboOit;
507 else if (myImmediateSceneFbos[0]->IsValid())
509 anImmFbo = myImmediateSceneFbos[0].operator->();
510 anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
513 #if !defined(GL_ES_VERSION_2_0)
514 if (aMainFbo == NULL)
516 aCtx->SetReadDrawBuffer (GL_BACK);
519 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
520 aMainFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
522 redraw (aProjectType, aMainFbo, aMainFboOit);
523 myBackBufferRestored = Standard_True;
524 myIsImmediateDrawn = Standard_False;
525 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
526 anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
527 if (!redrawImmediate (aProjectType, aMainFbo, anImmFbo, anImmFboOit))
533 && anImmFbo != aFrameBuffer)
535 blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
539 if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
540 && myRenderParams.IsGlobalIlluminationEnabled)
548 if (wasDisabledMSAA != myToDisableMSAA
549 || hadFboBlit != myHasFboBlit)
555 // reset state for safety
556 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
557 if (aCtx->caps->ffpEnable)
559 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
566 if (!myMainSceneFbos[0]->IsValid())
568 myBackBufferRestored = Standard_False;
573 aCtx->core11fwd->glFlush();
576 // reset render mode state
578 aCtx->FrameStats()->FrameEnd (myWorkspace->View(), false);
580 myWasRedrawnGL = Standard_True;
583 // =======================================================================
584 // function : RedrawImmediate
586 // =======================================================================
587 void OpenGl_View::RedrawImmediate()
589 if (!myWorkspace->Activate())
592 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
593 if (!myTransientDrawToFront
594 || !myBackBufferRestored
595 || (aCtx->caps->buffersNoSwap && !myMainSceneFbos[0]->IsValid()))
601 const Graphic3d_StereoMode aStereoMode = myRenderParams.StereoMode;
602 Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
603 OpenGl_FrameBuffer* aFrameBuffer = myFBO.operator->();
604 aCtx->FrameStats()->FrameStart (myWorkspace->View(), true);
606 if ( aFrameBuffer == NULL
607 && !aCtx->DefaultFrameBuffer().IsNull()
608 && aCtx->DefaultFrameBuffer()->IsValid())
610 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
613 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
615 if (myMainSceneFbos[0]->IsValid()
616 && !myMainSceneFbos[1]->IsValid())
618 aProjectType = Graphic3d_Camera::Projection_Perspective;
623 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
625 OpenGl_FrameBuffer* aMainFbos[2] =
627 myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
628 myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
630 OpenGl_FrameBuffer* anImmFbos[2] =
632 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
633 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
635 OpenGl_FrameBuffer* anImmFbosOit[2] =
637 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
638 myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
639 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
641 if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
642 || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
646 anImmFbosOit[0] = NULL;
647 anImmFbosOit[1] = NULL;
650 if (aCtx->arbFBO != NULL)
652 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
654 #if !defined(GL_ES_VERSION_2_0)
655 if (anImmFbos[0] == NULL)
657 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
661 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
662 anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
663 toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye,
667 Standard_True) || toSwap;
668 if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
670 && !aCtx->caps->buffersNoSwap)
675 if (aCtx->arbFBO != NULL)
677 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
679 #if !defined(GL_ES_VERSION_2_0)
680 if (anImmFbos[1] == NULL)
682 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
685 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
686 anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
687 toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye,
691 Standard_True) || toSwap;
692 if (anImmFbos[0] != NULL)
694 drawStereoPair (aFrameBuffer);
699 OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
700 OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
701 OpenGl_FrameBuffer* anImmFboOit = NULL;
702 if (myImmediateSceneFbos[0]->IsValid())
704 anImmFbo = myImmediateSceneFbos[0].operator->();
705 anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
707 #if !defined(GL_ES_VERSION_2_0)
708 if (aMainFbo == NULL)
710 aCtx->SetReadDrawBuffer (GL_BACK);
713 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
714 anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
715 toSwap = redrawImmediate (aProjectType,
719 Standard_True) || toSwap;
721 && anImmFbo != aFrameBuffer)
723 blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
730 // reset state for safety
731 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
732 if (aCtx->caps->ffpEnable)
734 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
737 if (toSwap && !aCtx->caps->buffersNoSwap)
743 aCtx->core11fwd->glFlush();
745 aCtx->FrameStats()->FrameEnd (myWorkspace->View(), true);
747 myWasRedrawnGL = Standard_True;
750 // =======================================================================
753 // =======================================================================
754 void OpenGl_View::redraw (const Graphic3d_Camera::Projection theProjection,
755 OpenGl_FrameBuffer* theReadDrawFbo,
756 OpenGl_FrameBuffer* theOitAccumFbo)
758 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
759 if (theReadDrawFbo != NULL)
761 theReadDrawFbo->BindBuffer (aCtx);
762 theReadDrawFbo->SetupViewport (aCtx);
766 const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
767 aCtx->ResizeViewport (aViewport);
770 // request reset of material
771 aCtx->ShaderManager()->UpdateMaterialState();
773 myWorkspace->UseZBuffer() = Standard_True;
774 myWorkspace->UseDepthWrite() = Standard_True;
775 GLbitfield toClear = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
776 glDepthFunc (GL_LEQUAL);
777 glDepthMask (GL_TRUE);
778 glEnable (GL_DEPTH_TEST);
780 #if !defined(GL_ES_VERSION_2_0)
783 glClearDepthf (1.0f);
786 const OpenGl_Vec4& aBgColor = myBgColor;
787 glClearColor (aBgColor.r(), aBgColor.g(), aBgColor.b(), 0.0f);
791 render (theProjection, theReadDrawFbo, theOitAccumFbo, Standard_False);
794 // =======================================================================
795 // function : redrawMonoImmediate
797 // =======================================================================
798 bool OpenGl_View::redrawImmediate (const Graphic3d_Camera::Projection theProjection,
799 OpenGl_FrameBuffer* theReadFbo,
800 OpenGl_FrameBuffer* theDrawFbo,
801 OpenGl_FrameBuffer* theOitAccumFbo,
802 const Standard_Boolean theIsPartialUpdate)
804 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
805 GLboolean toCopyBackToFront = GL_FALSE;
806 if (theDrawFbo == theReadFbo
807 && theDrawFbo != NULL)
809 myBackBufferRestored = Standard_False;
811 else if (theReadFbo != NULL
812 && theReadFbo->IsValid()
815 if (!blitBuffers (theReadFbo, theDrawFbo))
820 else if (theDrawFbo == NULL)
822 #if !defined(GL_ES_VERSION_2_0)
823 aCtx->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
825 if (toCopyBackToFront
826 && myTransientDrawToFront)
828 if (!HasImmediateStructures()
829 && !theIsPartialUpdate)
831 // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
834 if (!copyBackToFront())
836 toCopyBackToFront = GL_FALSE;
837 myBackBufferRestored = Standard_False;
842 myBackBufferRestored = Standard_False;
847 myBackBufferRestored = Standard_False;
849 myIsImmediateDrawn = Standard_True;
851 myWorkspace->UseZBuffer() = Standard_True;
852 myWorkspace->UseDepthWrite() = Standard_True;
853 glDepthFunc (GL_LEQUAL);
854 glDepthMask (GL_TRUE);
855 glEnable (GL_DEPTH_TEST);
856 #if !defined(GL_ES_VERSION_2_0)
859 glClearDepthf (1.0f);
862 render (theProjection, theDrawFbo, theOitAccumFbo, Standard_True);
864 return !toCopyBackToFront;
867 //=======================================================================
870 //=======================================================================
871 void OpenGl_View::render (Graphic3d_Camera::Projection theProjection,
872 OpenGl_FrameBuffer* theOutputFBO,
873 OpenGl_FrameBuffer* theOitAccumFbo,
874 const Standard_Boolean theToDrawImmediate)
876 // ==================================
877 // Step 1: Prepare for render
878 // ==================================
880 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
881 aContext->SetSampleAlphaToCoverage (myRenderParams.ToEnableAlphaToCoverage);
883 #if !defined(GL_ES_VERSION_2_0)
884 // Disable current clipping planes
885 if (aContext->core11 != NULL)
887 const Standard_Integer aMaxPlanes = aContext->MaxClipPlanes();
888 for (Standard_Integer aClipPlaneId = GL_CLIP_PLANE0; aClipPlaneId < GL_CLIP_PLANE0 + aMaxPlanes; ++aClipPlaneId)
890 aContext->core11fwd->glDisable (aClipPlaneId);
895 // update states of OpenGl_BVHTreeSelector (frustum culling algorithm);
896 // note that we pass here window dimensions ignoring Graphic3d_RenderingParams::RenderResolutionScale
897 myBVHSelector.SetViewVolume (myCamera);
898 myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height(), myRenderParams.ResolutionRatio());
899 myBVHSelector.CacheClipPtsProjections();
901 const Handle(OpenGl_ShaderManager)& aManager = aContext->ShaderManager();
902 const Handle(Graphic3d_LightSet)& aLights = myShadingModel == Graphic3d_TOSM_UNLIT ? myNoShadingLight : myLights;
903 Standard_Size aLightsRevision = 0;
904 if (!aLights.IsNull())
906 aLightsRevision = aLights->UpdateRevision();
908 if (StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index()) != myLastLightSourceState
909 || aLightsRevision != myLightsRevision)
911 myLightsRevision = aLightsRevision;
912 aManager->UpdateLightSourceStateTo (aLights);
913 myLastLightSourceState = StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index());
916 // Update matrices if camera has changed.
917 Graphic3d_WorldViewProjState aWVPState = myCamera->WorldViewProjState();
918 if (myWorldViewProjState != aWVPState)
921 myWorldViewProjState = aWVPState;
924 myLocalOrigin.SetCoord (0.0, 0.0, 0.0);
925 aContext->ProjectionState.SetCurrent (myCamera->ProjectionMatrixF());
926 aContext->WorldViewState .SetCurrent (myCamera->OrientationMatrixF());
927 aContext->ApplyProjectionMatrix();
928 aContext->ApplyWorldViewMatrix();
929 if (aManager->ModelWorldState().Index() == 0)
931 aContext->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
934 // ====================================
935 // Step 2: Redraw background
936 // ====================================
939 if (!theToDrawImmediate)
941 drawBackground (myWorkspace);
944 #if !defined(GL_ES_VERSION_2_0)
945 // Switch off lighting by default
946 if (aContext->core11 != NULL
947 && aContext->caps->ffpEnable)
949 glDisable(GL_LIGHTING);
953 // =================================
954 // Step 3: Redraw main plane
955 // =================================
957 // Setup face culling
958 GLboolean isCullFace = GL_FALSE;
959 if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
961 isCullFace = glIsEnabled (GL_CULL_FACE);
962 if (myBackfacing == Graphic3d_TOBM_DISABLE)
964 glEnable (GL_CULL_FACE);
965 glCullFace (GL_BACK);
968 glDisable (GL_CULL_FACE);
971 #if !defined(GL_ES_VERSION_2_0)
972 // if the view is scaled normal vectors are scaled to unit
973 // length for correct displaying of shaded objects
974 const gp_Pnt anAxialScale = myCamera->AxialScale();
975 if (anAxialScale.X() != 1.F ||
976 anAxialScale.Y() != 1.F ||
977 anAxialScale.Z() != 1.F)
979 aContext->SetGlNormalizeEnabled (Standard_True);
983 aContext->SetGlNormalizeEnabled (Standard_False);
986 // Apply InteriorShadingMethod
987 if (aContext->core11 != NULL)
989 aContext->core11->glShadeModel (myShadingModel == Graphic3d_TOSM_FACET
990 || myShadingModel == Graphic3d_TOSM_UNLIT ? GL_FLAT : GL_SMOOTH);
994 aManager->SetShadingModel (myShadingModel);
997 if (theProjection == Graphic3d_Camera::Projection_MonoLeftEye)
999 aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoLeftF());
1000 aContext->ApplyProjectionMatrix();
1002 else if (theProjection == Graphic3d_Camera::Projection_MonoRightEye)
1004 aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoRightF());
1005 aContext->ApplyProjectionMatrix();
1008 myWorkspace->SetEnvironmentTexture (myTextureEnv);
1010 renderScene (theProjection, theOutputFBO, theOitAccumFbo, theToDrawImmediate);
1012 myWorkspace->SetEnvironmentTexture (Handle(OpenGl_TextureSet)());
1014 // ===============================
1015 // Step 4: Trihedron
1016 // ===============================
1018 // Resetting GL parameters according to the default aspects
1019 // in order to synchronize GL state with the graphic driver state
1020 // before drawing auxiliary stuff (trihedrons, overlayer)
1021 myWorkspace->ResetAppliedAspect();
1024 if (!theToDrawImmediate)
1026 renderTrihedron (myWorkspace);
1028 // Restore face culling
1029 if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
1033 glEnable (GL_CULL_FACE);
1034 glCullFace (GL_BACK);
1037 glDisable (GL_CULL_FACE);
1045 myWorkspace->ResetAppliedAspect();
1046 aContext->SetSampleAlphaToCoverage (false);
1048 // reset FFP state for safety
1049 aContext->BindProgram (Handle(OpenGl_ShaderProgram)());
1050 if (aContext->caps->ffpEnable)
1052 aContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1055 // ==============================================================
1056 // Step 6: Keep shader manager informed about last View
1057 // ==============================================================
1059 if (!aManager.IsNull())
1061 aManager->SetLastView (this);
1065 // =======================================================================
1066 // function : InvalidateBVHData
1068 // =======================================================================
1069 void OpenGl_View::InvalidateBVHData (const Graphic3d_ZLayerId theLayerId)
1071 myZLayers.InvalidateBVHData (theLayerId);
1074 //=======================================================================
1075 //function : renderStructs
1077 //=======================================================================
1078 void OpenGl_View::renderStructs (Graphic3d_Camera::Projection theProjection,
1079 OpenGl_FrameBuffer* theReadDrawFbo,
1080 OpenGl_FrameBuffer* theOitAccumFbo,
1081 const Standard_Boolean theToDrawImmediate)
1083 myZLayers.UpdateCulling (myWorkspace, theToDrawImmediate);
1084 if ( myZLayers.NbStructures() <= 0 )
1087 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1088 Standard_Boolean toRenderGL = theToDrawImmediate ||
1089 myRenderParams.Method != Graphic3d_RM_RAYTRACING ||
1090 myRaytraceInitStatus == OpenGl_RT_FAIL ||
1095 toRenderGL = !initRaytraceResources (aCtx) ||
1096 !updateRaytraceGeometry (OpenGl_GUM_CHECK, myId, aCtx);
1098 toRenderGL |= !myIsRaytraceDataValid; // if no ray-trace data use OpenGL
1102 const Standard_Integer aSizeX = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeX() : myWindow->Width();
1103 const Standard_Integer aSizeY = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeY() : myWindow->Height();
1104 myOpenGlFBO ->InitLazy (aCtx, aSizeX, aSizeY, myFboColorFormat, myFboDepthFormat, 0);
1106 if (theReadDrawFbo != NULL)
1107 theReadDrawFbo->UnbindBuffer (aCtx);
1109 // Prepare preliminary OpenGL output
1110 if (aCtx->arbFBOBlit != NULL)
1112 // Render bottom OSD layer
1113 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Bottom, theReadDrawFbo, theOitAccumFbo);
1115 const Standard_Integer aPrevFilter = myWorkspace->RenderFilter() & ~(Standard_Integer )(OpenGl_RenderFilter_NonRaytraceableOnly);
1116 myWorkspace->SetRenderFilter (aPrevFilter | OpenGl_RenderFilter_NonRaytraceableOnly);
1118 if (theReadDrawFbo != NULL)
1120 theReadDrawFbo->BindDrawBuffer (aCtx);
1124 aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, 0);
1127 // Render non-polygonal elements in default layer
1128 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Default, theReadDrawFbo, theOitAccumFbo);
1130 myWorkspace->SetRenderFilter (aPrevFilter);
1133 if (theReadDrawFbo != NULL)
1135 theReadDrawFbo->BindBuffer (aCtx);
1139 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, 0);
1142 // Reset OpenGl aspects state to default to avoid enabling of
1143 // backface culling which is not supported in ray-tracing.
1144 myWorkspace->ResetAppliedAspect();
1146 // Ray-tracing polygonal primitive arrays
1147 raytrace (aSizeX, aSizeY, theProjection, theReadDrawFbo, aCtx);
1149 // Render upper (top and topmost) OpenGL layers
1150 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Upper, theReadDrawFbo, theOitAccumFbo);
1154 // Redraw 3D scene using OpenGL in standard
1155 // mode or in case of ray-tracing failure
1158 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_All, theReadDrawFbo, theOitAccumFbo);
1160 // Set flag that scene was redrawn by standard pipeline
1161 myWasRedrawnGL = Standard_True;
1165 //=======================================================================
1166 //function : renderTrihedron
1168 //=======================================================================
1169 void OpenGl_View::renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace)
1171 if (myToShowGradTrihedron)
1173 myGraduatedTrihedron.Render (theWorkspace);
1177 //=======================================================================
1178 //function : renderFrameStats
1180 //=======================================================================
1181 void OpenGl_View::renderFrameStats()
1183 if (myRenderParams.ToShowStats
1184 && myRenderParams.CollectedStats != Graphic3d_RenderingParams::PerfCounters_NONE)
1186 myFrameStatsPrs.Update (myWorkspace);
1187 myFrameStatsPrs.Render (myWorkspace);
1191 // =======================================================================
1192 // function : Invalidate
1194 // =======================================================================
1195 void OpenGl_View::Invalidate()
1197 myBackBufferRestored = Standard_False;
1200 //=======================================================================
1201 //function : renderScene
1203 //=======================================================================
1204 void OpenGl_View::renderScene (Graphic3d_Camera::Projection theProjection,
1205 OpenGl_FrameBuffer* theReadDrawFbo,
1206 OpenGl_FrameBuffer* theOitAccumFbo,
1207 const Standard_Boolean theToDrawImmediate)
1209 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
1211 // Specify clipping planes in view transformation space
1212 aContext->ChangeClipping().Reset (myClipPlanes);
1213 if (!myClipPlanes.IsNull()
1214 && !myClipPlanes->IsEmpty())
1216 aContext->ShaderManager()->UpdateClippingState();
1219 renderStructs (theProjection, theReadDrawFbo, theOitAccumFbo, theToDrawImmediate);
1220 aContext->BindTextures (Handle(OpenGl_TextureSet)());
1222 // Apply restored view matrix.
1223 aContext->ApplyWorldViewMatrix();
1225 aContext->ChangeClipping().Reset (Handle(Graphic3d_SequenceOfHClipPlane)());
1226 if (!myClipPlanes.IsNull()
1227 && !myClipPlanes->IsEmpty())
1229 aContext->ShaderManager()->RevertClippingState();
1233 // =======================================================================
1234 // function : bindDefaultFbo
1236 // =======================================================================
1237 void OpenGl_View::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
1239 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1240 OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
1242 : (!aCtx->DefaultFrameBuffer().IsNull()
1243 && aCtx->DefaultFrameBuffer()->IsValid()
1244 ? aCtx->DefaultFrameBuffer().operator->()
1248 anFbo->BindBuffer (aCtx);
1249 anFbo->SetupViewport (aCtx);
1253 #if !defined(GL_ES_VERSION_2_0)
1254 aCtx->SetReadDrawBuffer (GL_BACK);
1256 if (aCtx->arbFBO != NULL)
1258 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1261 const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
1262 aCtx->ResizeViewport (aViewport);
1266 // =======================================================================
1267 // function : initBlitQuad
1269 // =======================================================================
1270 OpenGl_VertexBuffer* OpenGl_View::initBlitQuad (const Standard_Boolean theToFlip)
1272 OpenGl_VertexBuffer* aVerts = NULL;
1275 aVerts = &myFullScreenQuad;
1276 if (!aVerts->IsValid())
1278 OpenGl_Vec4 aQuad[4] =
1280 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
1281 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 1.0f),
1282 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
1283 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 1.0f)
1285 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1290 aVerts = &myFullScreenQuadFlip;
1291 if (!aVerts->IsValid())
1293 OpenGl_Vec4 aQuad[4] =
1295 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 1.0f),
1296 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 0.0f),
1297 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 1.0f),
1298 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 0.0f)
1300 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1306 // =======================================================================
1307 // function : blitBuffers
1309 // =======================================================================
1310 bool OpenGl_View::blitBuffers (OpenGl_FrameBuffer* theReadFbo,
1311 OpenGl_FrameBuffer* theDrawFbo,
1312 const Standard_Boolean theToFlip)
1314 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1315 const Standard_Integer aReadSizeX = theReadFbo != NULL ? theReadFbo->GetVPSizeX() : myWindow->Width();
1316 const Standard_Integer aReadSizeY = theReadFbo != NULL ? theReadFbo->GetVPSizeY() : myWindow->Height();
1317 const Standard_Integer aDrawSizeX = theDrawFbo != NULL ? theDrawFbo->GetVPSizeX() : myWindow->Width();
1318 const Standard_Integer aDrawSizeY = theDrawFbo != NULL ? theDrawFbo->GetVPSizeY() : myWindow->Height();
1319 if (theReadFbo == NULL || aCtx->IsFeedback())
1323 else if (theReadFbo == theDrawFbo)
1328 // clear destination before blitting
1329 if (theDrawFbo != NULL
1330 && theDrawFbo->IsValid())
1332 theDrawFbo->BindBuffer (aCtx);
1336 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1338 const Standard_Integer aViewport[4] = { 0, 0, aDrawSizeX, aDrawSizeY };
1339 aCtx->ResizeViewport (aViewport);
1341 #if !defined(GL_ES_VERSION_2_0)
1342 aCtx->core20fwd->glClearDepth (1.0);
1344 aCtx->core20fwd->glClearDepthf (1.0f);
1346 aCtx->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1348 if (aCtx->arbFBOBlit != NULL
1349 && theReadFbo->NbSamples() != 0)
1351 GLbitfield aCopyMask = 0;
1352 theReadFbo->BindReadBuffer (aCtx);
1353 if (theDrawFbo != NULL
1354 && theDrawFbo->IsValid())
1356 theDrawFbo->BindDrawBuffer (aCtx);
1357 if (theDrawFbo->HasColor()
1358 && theReadFbo->HasColor())
1360 aCopyMask |= GL_COLOR_BUFFER_BIT;
1362 if (theDrawFbo->HasDepth()
1363 && theReadFbo->HasDepth())
1365 aCopyMask |= GL_DEPTH_BUFFER_BIT;
1370 if (theReadFbo->HasColor())
1372 aCopyMask |= GL_COLOR_BUFFER_BIT;
1374 if (theReadFbo->HasDepth())
1376 aCopyMask |= GL_DEPTH_BUFFER_BIT;
1378 aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1381 // we don't copy stencil buffer here... does it matter for performance?
1382 aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, aReadSizeX, aReadSizeY,
1383 0, 0, aDrawSizeX, aDrawSizeY,
1384 aCopyMask, GL_NEAREST);
1385 const int anErr = ::glGetError();
1386 if (anErr != GL_NO_ERROR)
1388 // glBlitFramebuffer() might fail in several cases:
1389 // - Both FBOs have MSAA and they are samples number does not match.
1390 // OCCT checks that this does not happen,
1391 // however some graphics drivers provide an option for overriding MSAA.
1392 // In this case window MSAA might be non-zero (and application can not check it)
1393 // and might not match MSAA of our offscreen FBOs.
1394 // - Pixel formats of FBOs do not match.
1395 // This also might happen with window has pixel format,
1396 // e.g. Mesa fails blitting RGBA8 -> RGB8 while other drivers support this conversion.
1397 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "FBO blitting has failed [Error #" + anErr + "]\n"
1398 + " Please check your graphics driver settings or try updating driver.";
1399 if (theReadFbo->NbSamples() != 0)
1401 myToDisableMSAA = true;
1402 aMsg += "\n MSAA settings should not be overridden by driver!";
1404 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1405 GL_DEBUG_TYPE_ERROR,
1407 GL_DEBUG_SEVERITY_HIGH,
1411 if (theDrawFbo != NULL
1412 && theDrawFbo->IsValid())
1414 theDrawFbo->BindBuffer (aCtx);
1418 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1423 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1424 aCtx->core20fwd->glDepthMask (GL_TRUE);
1425 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1426 #if defined(GL_ES_VERSION_2_0)
1427 if (!aCtx->IsGlGreaterEqual (3, 0)
1428 && !aCtx->extFragDepth)
1430 aCtx->core20fwd->glDisable (GL_DEPTH_TEST);
1434 aCtx->BindTextures (Handle(OpenGl_TextureSet)());
1436 const Graphic3d_TypeOfTextureFilter aFilter = (aDrawSizeX == aReadSizeX && aDrawSizeY == aReadSizeY) ? Graphic3d_TOTF_NEAREST : Graphic3d_TOTF_BILINEAR;
1437 const GLint aFilterGl = aFilter == Graphic3d_TOTF_NEAREST ? GL_NEAREST : GL_LINEAR;
1439 OpenGl_VertexBuffer* aVerts = initBlitQuad (theToFlip);
1440 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1441 if (aVerts->IsValid()
1442 && aManager->BindFboBlitProgram())
1444 theReadFbo->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
1445 if (theReadFbo->ColorTexture()->Sampler()->Parameters()->Filter() != aFilter)
1447 theReadFbo->ColorTexture()->Sampler()->Parameters()->SetFilter (aFilter);
1448 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
1449 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
1452 theReadFbo->DepthStencilTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
1453 if (theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->Filter() != aFilter)
1455 theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->SetFilter (aFilter);
1456 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
1457 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
1460 aVerts->BindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1462 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1464 aVerts->UnbindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1465 theReadFbo->DepthStencilTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
1466 theReadFbo->ColorTexture() ->Unbind (aCtx, Graphic3d_TextureUnit_0);
1467 aCtx->BindProgram (NULL);
1471 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1472 + "Error! FBO blitting has failed";
1473 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1474 GL_DEBUG_TYPE_ERROR,
1476 GL_DEBUG_SEVERITY_HIGH,
1478 myHasFboBlit = Standard_False;
1479 theReadFbo->Release (aCtx.operator->());
1486 // =======================================================================
1487 // function : drawStereoPair
1489 // =======================================================================
1490 void OpenGl_View::drawStereoPair (OpenGl_FrameBuffer* theDrawFbo)
1492 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1493 bindDefaultFbo (theDrawFbo);
1494 OpenGl_FrameBuffer* aPair[2] =
1496 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1497 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1499 if (aPair[0] == NULL
1501 || !myTransientDrawToFront)
1503 aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
1504 aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
1507 if (aPair[0] == NULL
1508 || aPair[1] == NULL)
1513 if (aPair[0]->NbSamples() != 0)
1515 // resolve MSAA buffers before drawing
1516 if (!myOpenGlFBO ->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, myFboDepthFormat, 0)
1517 || !myOpenGlFBO2->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, 0, 0))
1519 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1520 GL_DEBUG_TYPE_ERROR,
1522 GL_DEBUG_SEVERITY_HIGH,
1523 "Error! Unable to allocate FBO for blitting stereo pair");
1524 bindDefaultFbo (theDrawFbo);
1528 if (!blitBuffers (aPair[0], myOpenGlFBO .operator->(), Standard_False)
1529 || !blitBuffers (aPair[1], myOpenGlFBO2.operator->(), Standard_False))
1531 bindDefaultFbo (theDrawFbo);
1535 aPair[0] = myOpenGlFBO .operator->();
1536 aPair[1] = myOpenGlFBO2.operator->();
1537 bindDefaultFbo (theDrawFbo);
1542 Standard_Integer left;
1543 Standard_Integer top;
1544 Standard_Integer right;
1545 Standard_Integer bottom;
1546 Standard_Integer dx() { return right - left; }
1547 Standard_Integer dy() { return bottom - top; }
1550 myWindow->PlatformWindow()->Position (aGeom.left, aGeom.top, aGeom.right, aGeom.bottom);
1552 Standard_Boolean toReverse = myRenderParams.ToReverseStereo;
1553 const Standard_Boolean isOddY = (aGeom.top + aGeom.dy()) % 2 == 1;
1554 const Standard_Boolean isOddX = aGeom.left % 2 == 1;
1556 && (myRenderParams.StereoMode == Graphic3d_StereoMode_RowInterlaced
1557 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1559 toReverse = !toReverse;
1562 && (myRenderParams.StereoMode == Graphic3d_StereoMode_ColumnInterlaced
1563 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1565 toReverse = !toReverse;
1570 std::swap (aPair[0], aPair[1]);
1573 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1574 aCtx->core20fwd->glDepthMask (GL_TRUE);
1575 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1577 aCtx->BindTextures (Handle(OpenGl_TextureSet)());
1578 OpenGl_VertexBuffer* aVerts = initBlitQuad (myToFlipOutput);
1580 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1581 if (aVerts->IsValid()
1582 && aManager->BindStereoProgram (myRenderParams.StereoMode))
1584 if (myRenderParams.StereoMode == Graphic3d_StereoMode_Anaglyph)
1586 OpenGl_Mat4 aFilterL, aFilterR;
1587 aFilterL.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1588 aFilterR.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1589 switch (myRenderParams.AnaglyphFilter)
1591 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Simple:
1593 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1594 aFilterR.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1595 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1598 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Optimized:
1600 aFilterL.SetRow (0, Graphic3d_Vec4 ( 0.4154f, 0.4710f, 0.16666667f, 0.0f));
1601 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.0458f, -0.0484f, -0.0257f, 0.0f));
1602 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.0547f, -0.0615f, 0.0128f, 0.0f));
1603 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1604 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.01090909f, -0.03636364f, -0.00606061f, 0.0f));
1605 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.37560000f, 0.73333333f, 0.01111111f, 0.0f));
1606 aFilterR.SetRow (2, Graphic3d_Vec4 (-0.06510000f, -0.12870000f, 1.29710000f, 0.0f));
1607 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1610 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Simple:
1612 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1613 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1614 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1617 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Optimized:
1619 aFilterL.SetRow (0, Graphic3d_Vec4 ( 1.062f, -0.205f, 0.299f, 0.0f));
1620 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.026f, 0.908f, 0.068f, 0.0f));
1621 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.038f, -0.173f, 0.022f, 0.0f));
1622 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1623 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.016f, -0.123f, -0.017f, 0.0f));
1624 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.006f, 0.062f, -0.017f, 0.0f));
1625 aFilterR.SetRow (2, Graphic3d_Vec4 ( 0.094f, 0.185f, 0.911f, 0.0f));
1626 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1629 case Graphic3d_RenderingParams::Anaglyph_GreenMagenta_Simple:
1631 aFilterR.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1632 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1633 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1636 case Graphic3d_RenderingParams::Anaglyph_UserDefined:
1638 aFilterL = myRenderParams.AnaglyphLeft;
1639 aFilterR = myRenderParams.AnaglyphRight;
1643 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultL", aFilterL);
1644 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultR", aFilterR);
1647 aPair[0]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
1648 aPair[1]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
1649 aVerts->BindVertexAttrib (aCtx, 0);
1651 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1653 aVerts->UnbindVertexAttrib (aCtx, 0);
1654 aPair[1]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
1655 aPair[0]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_0);
1659 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1660 + "Error! Anaglyph has failed";
1661 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1662 GL_DEBUG_TYPE_ERROR,
1664 GL_DEBUG_SEVERITY_HIGH,
1669 // =======================================================================
1670 // function : copyBackToFront
1672 // =======================================================================
1673 bool OpenGl_View::copyBackToFront()
1675 myIsImmediateDrawn = Standard_False;
1676 #if !defined(GL_ES_VERSION_2_0)
1677 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1678 if (aCtx->core11 == NULL)
1683 OpenGl_Mat4 aProjectMat;
1684 Graphic3d_TransformUtils::Ortho2D (aProjectMat,
1685 0.0f, static_cast<GLfloat> (myWindow->Width()),
1686 0.0f, static_cast<GLfloat> (myWindow->Height()));
1688 aCtx->WorldViewState.Push();
1689 aCtx->ProjectionState.Push();
1691 aCtx->WorldViewState.SetIdentity();
1692 aCtx->ProjectionState.SetCurrent (aProjectMat);
1694 aCtx->ApplyProjectionMatrix();
1695 aCtx->ApplyWorldViewMatrix();
1697 // synchronize FFP state before copying pixels
1698 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
1699 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1700 aCtx->DisableFeatures();
1702 switch (aCtx->DrawBuffer())
1706 aCtx->SetReadBuffer (GL_BACK_LEFT);
1707 aCtx->SetDrawBuffer (GL_FRONT_LEFT);
1712 aCtx->SetReadBuffer (GL_BACK_RIGHT);
1713 aCtx->SetDrawBuffer (GL_FRONT_RIGHT);
1718 aCtx->SetReadBuffer (GL_BACK);
1719 aCtx->SetDrawBuffer (GL_FRONT);
1724 aCtx->core11->glRasterPos2i (0, 0);
1725 aCtx->core11->glCopyPixels (0, 0, myWindow->Width() + 1, myWindow->Height() + 1, GL_COLOR);
1726 //aCtx->core11->glCopyPixels (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
1728 aCtx->EnableFeatures();
1730 aCtx->WorldViewState.Pop();
1731 aCtx->ProjectionState.Pop();
1732 aCtx->ApplyProjectionMatrix();
1734 // read/write from front buffer now
1735 aCtx->SetReadBuffer (aCtx->DrawBuffer());
1742 // =======================================================================
1743 // function : checkOitCompatibility
1745 // =======================================================================
1746 Standard_Boolean OpenGl_View::checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
1747 const Standard_Boolean theMSAA)
1749 // determine if OIT is supported by current OpenGl context
1750 Standard_Boolean& aToDisableOIT = theMSAA ? myToDisableMSAA : myToDisableOIT;
1753 return Standard_False;
1756 TCollection_ExtendedString aCompatibilityMsg;
1757 if (theGlContext->hasFloatBuffer == OpenGl_FeatureNotAvailable
1758 && theGlContext->hasHalfFloatBuffer == OpenGl_FeatureNotAvailable)
1760 aCompatibilityMsg += "OpenGL context does not support floating-point RGBA color buffer format.\n";
1762 if (theMSAA && theGlContext->hasSampleVariables == OpenGl_FeatureNotAvailable)
1764 aCompatibilityMsg += "Current version of GLSL does not support built-in sample variables.\n";
1766 if (theGlContext->hasDrawBuffers == OpenGl_FeatureNotAvailable)
1768 aCompatibilityMsg += "OpenGL context does not support multiple draw buffers.\n";
1770 if (aCompatibilityMsg.IsEmpty())
1772 return Standard_True;
1775 aCompatibilityMsg += " Blended order-independent transparency will not be available.\n";
1776 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1777 GL_DEBUG_TYPE_ERROR,
1779 GL_DEBUG_SEVERITY_HIGH,
1782 aToDisableOIT = Standard_True;
1783 return Standard_False;
1786 // =======================================================================
1787 // function : chooseOitColorConfiguration
1789 // =======================================================================
1790 bool OpenGl_View::chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
1791 const Standard_Integer theConfigIndex,
1792 OpenGl_ColorFormats& theFormats)
1795 switch (theConfigIndex)
1797 case 0: // choose best applicable color format combination
1799 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1800 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_R16F : GL_R32F);
1803 case 1: // choose non-optimal applicable color format combination
1805 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1806 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1810 return false; // color combination does not exist