1491a7cd4f3babd86c7167c46c377bfcea1648d8
[occt.git] / src / OpenGl / OpenGl_View_Redraw.cxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
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.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <stdio.h>
17 #include <stdlib.h>
18
19 #include <OpenGl_GlCore11.hxx>
20
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>
26
27 #include <NCollection_Mat4.hxx>
28
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_GraduatedTrihedron.hxx>
35 #include <OpenGl_PrimitiveArray.hxx>
36 #include <OpenGl_ShaderManager.hxx>
37 #include <OpenGl_ShaderProgram.hxx>
38 #include <OpenGl_Structure.hxx>
39 #include <OpenGl_ArbFBO.hxx>
40
41 namespace
42 {
43   //! Format Frame Buffer format for logging messages.
44   static TCollection_AsciiString printFboFormat (const Handle(OpenGl_FrameBuffer)& theFbo)
45   {
46     return TCollection_AsciiString() + theFbo->GetInitVPSizeX() + "x" + theFbo->GetInitVPSizeY() + "@" + theFbo->NbSamples();
47   }
48
49   //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
50   static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
51                                  Standard_Integer theSizeX,
52                                  Standard_Integer theSizeY,
53                                  Standard_Integer theNbSamples)
54   {
55     return !theFboToCheck->IsValid()
56         &&  theFboToCheck->GetInitVPSizeX() == theSizeX
57         &&  theFboToCheck->GetInitVPSizeY() == theSizeY
58         &&  theFboToCheck->NbSamples()      == theNbSamples;
59   }
60
61   //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
62   static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
63                                  const Handle(OpenGl_FrameBuffer)& theFboRef)
64   {
65     return checkWasFailedFbo (theFboToCheck, theFboRef->GetVPSizeX(), theFboRef->GetVPSizeY(), theFboRef->NbSamples());
66   }
67 }
68
69 //=======================================================================
70 //function : drawBackground
71 //purpose  :
72 //=======================================================================
73 void OpenGl_View::drawBackground (const Handle(OpenGl_Workspace)& theWorkspace)
74 {
75   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
76
77   if (!myBgTextureArray->IsDefined()   // no texture
78    && !myBgGradientArray->IsDefined()) // no gradient
79   {
80     return;
81   }
82
83   const Standard_Boolean wasUsedZBuffer = theWorkspace->SetUseZBuffer (Standard_False);
84   if (wasUsedZBuffer)
85   {
86     aCtx->core11fwd->glDisable (GL_DEPTH_TEST);
87   }
88
89   // Drawing background gradient if:
90   // - gradient fill type is not Aspect_GFM_NONE and
91   // - either background texture is no specified or it is drawn in Aspect_FM_CENTERED mode
92   if (myBgGradientArray->IsDefined()
93     && (!myTextureParams->Aspect()->ToMapTexture()
94       || myBgTextureArray->TextureFillMethod() == Aspect_FM_CENTERED
95       || myBgTextureArray->TextureFillMethod() == Aspect_FM_NONE))
96   {
97   #if !defined(GL_ES_VERSION_2_0)
98     GLint aShadingModelOld = GL_SMOOTH;
99     if (aCtx->core11 != NULL)
100     {
101       aCtx->core11fwd->glDisable (GL_LIGHTING);
102       aCtx->core11fwd->glGetIntegerv (GL_SHADE_MODEL, &aShadingModelOld);
103       aCtx->core11->glShadeModel (GL_SMOOTH);
104     }
105   #endif
106
107     myBgGradientArray->Render (theWorkspace);
108
109   #if !defined(GL_ES_VERSION_2_0)
110     if (aCtx->core11 != NULL)
111     {
112       aCtx->core11->glShadeModel (aShadingModelOld);
113     }
114   #endif
115   }
116
117   // Drawing background image if it is defined
118   // (texture is defined and fill type is not Aspect_FM_NONE)
119   if (myBgTextureArray->IsDefined()
120    && myTextureParams->Aspect()->ToMapTexture())
121   {
122     aCtx->core11fwd->glDisable (GL_BLEND);
123
124     const OpenGl_AspectFace* anOldAspectFace = theWorkspace->SetAspectFace (myTextureParams);
125     myBgTextureArray->Render (theWorkspace);
126     theWorkspace->SetAspectFace (anOldAspectFace);
127   }
128
129   if (wasUsedZBuffer)
130   {
131     theWorkspace->SetUseZBuffer (Standard_True);
132     aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
133   }
134 }
135
136 //=======================================================================
137 //function : Redraw
138 //purpose  :
139 //=======================================================================
140 void OpenGl_View::Redraw()
141 {
142   const Standard_Boolean wasDisabledMSAA = myToDisableMSAA;
143   const Standard_Boolean hadFboBlit      = myHasFboBlit;
144   if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
145   && !myCaps->vboDisable
146   && !myCaps->keepArrayData)
147   {
148     if (myWasRedrawnGL)
149     {
150       myDeviceLostFlag = Standard_True;
151     }
152
153     myCaps->keepArrayData = Standard_True;
154   }
155
156   if (!myWorkspace->Activate())
157   {
158     return;
159   }
160
161   myWindow->SetSwapInterval();
162
163   ++myFrameCounter;
164   const Graphic3d_StereoMode   aStereoMode  = myRenderParams.StereoMode;
165   Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
166   Handle(OpenGl_Context)       aCtx         = myWorkspace->GetGlContext();
167
168   // release pending GL resources
169   aCtx->ReleaseDelayed();
170
171   // fetch OpenGl context state
172   aCtx->FetchState();
173
174   OpenGl_FrameBuffer* aFrameBuffer = myFBO.operator->();
175   bool toSwap = aCtx->IsRender()
176             && !aCtx->caps->buffersNoSwap
177             &&  aFrameBuffer == NULL;
178
179   Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWindow->Width();
180   Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myWindow->Height();
181   Standard_Integer aRendSizeX = Standard_Integer(myRenderParams.RenderResolutionScale * aSizeX + 0.5f);
182   Standard_Integer aRendSizeY = Standard_Integer(myRenderParams.RenderResolutionScale * aSizeY + 0.5f);
183
184   // determine multisampling parameters
185   Standard_Integer aNbSamples = !myToDisableMSAA && aSizeX == aRendSizeX
186                               ? Max (Min (myRenderParams.NbMsaaSamples, aCtx->MaxMsaaSamples()), 0)
187                               : 0;
188   if (aNbSamples != 0)
189   {
190     aNbSamples = OpenGl_Context::GetPowerOfTwo (aNbSamples, aCtx->MaxMsaaSamples());
191   }
192
193   bool toUseOit = myRenderParams.TransparencyMethod == Graphic3d_RTM_BLEND_OIT
194                && checkOitCompatibility (aCtx, aNbSamples > 0);
195
196   const bool toInitImmediateFbo = myTransientDrawToFront
197                                && (!aCtx->caps->useSystemBuffer || (toUseOit && HasImmediateStructures()));
198
199   if ( aFrameBuffer == NULL
200    && !aCtx->DefaultFrameBuffer().IsNull()
201    &&  aCtx->DefaultFrameBuffer()->IsValid())
202   {
203     aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
204   }
205
206   if (myHasFboBlit
207    && (myTransientDrawToFront
208     || aProjectType == Graphic3d_Camera::Projection_Stereo
209     || aNbSamples != 0
210     || toUseOit
211     || aSizeX != aRendSizeX))
212   {
213     if (myMainSceneFbos[0]->GetVPSizeX() != aRendSizeX
214      || myMainSceneFbos[0]->GetVPSizeY() != aRendSizeY
215      || myMainSceneFbos[0]->NbSamples()  != aNbSamples)
216     {
217       if (!myTransientDrawToFront)
218       {
219         myImmediateSceneFbos[0]->Release (aCtx.operator->());
220         myImmediateSceneFbos[1]->Release (aCtx.operator->());
221         myImmediateSceneFbos[0]->ChangeViewport (0, 0);
222         myImmediateSceneFbos[1]->ChangeViewport (0, 0);
223       }
224
225       // prepare FBOs containing main scene
226       // for further blitting and rendering immediate presentations on top
227       if (aCtx->core20fwd != NULL)
228       {
229         const bool wasFailedMain0 = checkWasFailedFbo (myMainSceneFbos[0], aRendSizeX, aRendSizeY, aNbSamples);
230         if (!myMainSceneFbos[0]->Init (aCtx, aRendSizeX, aRendSizeY, myFboColorFormat, myFboDepthFormat, aNbSamples)
231          && !wasFailedMain0)
232         {
233           TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO "
234                                           + printFboFormat (myMainSceneFbos[0]) + " initialization has failed";
235           aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
236         }
237       }
238     }
239     if (myMainSceneFbos[0]->IsValid() && (toInitImmediateFbo || myImmediateSceneFbos[0]->IsValid()))
240     {
241       const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
242       if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
243        && !wasFailedImm0)
244       {
245         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO "
246                                         + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
247         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
248       }
249     }
250   }
251   else
252   {
253     myMainSceneFbos     [0]->Release (aCtx.operator->());
254     myMainSceneFbos     [1]->Release (aCtx.operator->());
255     myImmediateSceneFbos[0]->Release (aCtx.operator->());
256     myImmediateSceneFbos[1]->Release (aCtx.operator->());
257     myMainSceneFbos     [0]->ChangeViewport (0, 0);
258     myMainSceneFbos     [1]->ChangeViewport (0, 0);
259     myImmediateSceneFbos[0]->ChangeViewport (0, 0);
260     myImmediateSceneFbos[1]->ChangeViewport (0, 0);
261   }
262
263   if (aProjectType == Graphic3d_Camera::Projection_Stereo
264    && myMainSceneFbos[0]->IsValid())
265   {
266     const bool wasFailedMain1 = checkWasFailedFbo (myMainSceneFbos[1], myMainSceneFbos[0]);
267     if (!myMainSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
268      && !wasFailedMain1)
269     {
270       TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO (second) "
271                                       + printFboFormat (myMainSceneFbos[1]) + " initialization has failed";
272       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
273     }
274     if (!myMainSceneFbos[1]->IsValid())
275     {
276       // no enough memory?
277       aProjectType = Graphic3d_Camera::Projection_Perspective;
278     }
279     else if (!myTransientDrawToFront)
280     {
281       //
282     }
283     else if (!aCtx->HasStereoBuffers() || aStereoMode != Graphic3d_StereoMode_QuadBuffer)
284     {
285       const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
286       const bool wasFailedImm1 = checkWasFailedFbo (myImmediateSceneFbos[1], myMainSceneFbos[0]);
287       if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
288        && !wasFailedImm0)
289       {
290         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
291                                         + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
292         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
293       }
294       if (!myImmediateSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
295        && !wasFailedImm1)
296       {
297         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
298                                         + printFboFormat (myImmediateSceneFbos[1]) + " initialization has failed";
299         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
300       }
301       if (!myImmediateSceneFbos[0]->IsValid()
302        || !myImmediateSceneFbos[1]->IsValid())
303       {
304         aProjectType = Graphic3d_Camera::Projection_Perspective;
305       }
306     }
307   }
308
309   // create color and coverage accumulation buffers required for OIT algorithm
310   if (toUseOit)
311   {
312     Standard_Integer anFboIt = 0;
313     for (; anFboIt < 2; ++anFboIt)
314     {
315       Handle(OpenGl_FrameBuffer)& aMainSceneFbo          = myMainSceneFbos        [anFboIt];
316       Handle(OpenGl_FrameBuffer)& aMainSceneFboOit       = myMainSceneFbosOit     [anFboIt];
317       Handle(OpenGl_FrameBuffer)& anImmediateSceneFbo    = myImmediateSceneFbos   [anFboIt];
318       Handle(OpenGl_FrameBuffer)& anImmediateSceneFboOit = myImmediateSceneFbosOit[anFboIt];
319       if (aMainSceneFbo->IsValid()
320        && (aMainSceneFboOit->GetVPSizeX() != aRendSizeX
321         || aMainSceneFboOit->GetVPSizeY() != aRendSizeY
322         || aMainSceneFboOit->NbSamples()  != aNbSamples))
323       {
324         Standard_Integer aColorConfig = 0;
325         for (;;) // seemly responding to driver limitation (GL_FRAMEBUFFER_UNSUPPORTED)
326         {
327           if (myFboOitColorConfig.IsEmpty())
328           {
329             if (!chooseOitColorConfiguration (aCtx, aColorConfig++, myFboOitColorConfig))
330             {
331               break;
332             }
333           }
334           if (aMainSceneFboOit->Init (aCtx, aRendSizeX, aRendSizeY, myFboOitColorConfig, aMainSceneFbo->DepthStencilTexture(), aNbSamples))
335           {
336             break;
337           }
338           myFboOitColorConfig.Clear();
339         }
340         if (!aMainSceneFboOit->IsValid())
341         {
342           break;
343         }
344       }
345       else if (!aMainSceneFbo->IsValid())
346       {
347         aMainSceneFboOit->Release (aCtx.operator->());
348         aMainSceneFboOit->ChangeViewport (0, 0);
349       }
350
351       if (anImmediateSceneFbo->IsValid()
352        && (anImmediateSceneFboOit->GetVPSizeX() != aRendSizeX
353         || anImmediateSceneFboOit->GetVPSizeY() != aRendSizeY
354         || anImmediateSceneFboOit->NbSamples()  != aNbSamples))
355       {
356         if (!anImmediateSceneFboOit->Init (aCtx, aRendSizeX, aRendSizeY, myFboOitColorConfig,
357                                            anImmediateSceneFbo->DepthStencilTexture(), aNbSamples))
358         {
359           break;
360         }
361       }
362       else if (!anImmediateSceneFbo->IsValid())
363       {
364         anImmediateSceneFboOit->Release (aCtx.operator->());
365         anImmediateSceneFboOit->ChangeViewport (0, 0);
366       }
367     }
368     if (anFboIt == 0) // only the first OIT framebuffer is mandatory
369     {
370       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
371                          "Initialization of float texture framebuffer for use with\n"
372                          "  blended order-independent transparency rendering algorithm has failed.\n"
373                          "  Blended order-independent transparency will not be available.\n");
374       if (aNbSamples > 0)
375       {
376         myToDisableOITMSAA = Standard_True;
377       }
378       else
379       {
380         myToDisableOIT     = Standard_True;
381       }
382       toUseOit = false;
383     }
384   }
385   if (!toUseOit && myMainSceneFbosOit[0]->IsValid())
386   {
387     myMainSceneFbosOit     [0]->Release (aCtx.operator->());
388     myMainSceneFbosOit     [1]->Release (aCtx.operator->());
389     myImmediateSceneFbosOit[0]->Release (aCtx.operator->());
390     myImmediateSceneFbosOit[1]->Release (aCtx.operator->());
391     myMainSceneFbosOit     [0]->ChangeViewport (0, 0);
392     myMainSceneFbosOit     [1]->ChangeViewport (0, 0);
393     myImmediateSceneFbosOit[0]->ChangeViewport (0, 0);
394     myImmediateSceneFbosOit[1]->ChangeViewport (0, 0);
395   }
396
397   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
398   {
399     OpenGl_FrameBuffer* aMainFbos[2] =
400     {
401       myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
402       myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
403     };
404     OpenGl_FrameBuffer* aMainFbosOit[2] =
405     {
406       myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL,
407       myMainSceneFbosOit[1]->IsValid() ? myMainSceneFbosOit[1].operator->() :
408         myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL
409     };
410
411     OpenGl_FrameBuffer* anImmFbos[2] =
412     {
413       myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
414       myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
415     };
416     OpenGl_FrameBuffer* anImmFbosOit[2] =
417     {
418       myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
419       myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
420         myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
421     };
422
423     if (!myTransientDrawToFront)
424     {
425       anImmFbos   [0] = aMainFbos   [0];
426       anImmFbos   [1] = aMainFbos   [1];
427       anImmFbosOit[0] = aMainFbosOit[0];
428       anImmFbosOit[1] = aMainFbosOit[1];
429     }
430     else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
431           || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
432     {
433       anImmFbos   [0] = NULL;
434       anImmFbos   [1] = NULL;
435       anImmFbosOit[0] = NULL;
436       anImmFbosOit[1] = NULL;
437     }
438
439   #if !defined(GL_ES_VERSION_2_0)
440     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
441   #endif
442     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
443                          aMainFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
444
445     redraw (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], aMainFbosOit[0]);
446     myBackBufferRestored = Standard_True;
447     myIsImmediateDrawn   = Standard_False;
448   #if !defined(GL_ES_VERSION_2_0)
449     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
450   #endif
451     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
452                          anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
453     if (!redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], anImmFbos[0], anImmFbosOit[0]))
454     {
455       toSwap = false;
456     }
457     else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip && toSwap)
458     {
459       aCtx->SwapBuffers();
460     }
461
462   #if !defined(GL_ES_VERSION_2_0)
463     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
464   #endif
465     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
466                          aMainFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
467
468     redraw (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], aMainFbosOit[1]);
469     myBackBufferRestored = Standard_True;
470     myIsImmediateDrawn   = Standard_False;
471     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
472                          anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
473     if (!redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], anImmFbos[1], anImmFbosOit[1]))
474     {
475       toSwap = false;
476     }
477
478     if (anImmFbos[0] != NULL)
479     {
480       aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(), 1.0f);
481       drawStereoPair (aFrameBuffer);
482     }
483   }
484   else
485   {
486     OpenGl_FrameBuffer* aMainFbo    = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : aFrameBuffer;
487     OpenGl_FrameBuffer* aMainFboOit = myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL;
488     OpenGl_FrameBuffer* anImmFbo    = aFrameBuffer;
489     OpenGl_FrameBuffer* anImmFboOit = NULL;
490     if (!myTransientDrawToFront)
491     {
492       anImmFbo    = aMainFbo;
493       anImmFboOit = aMainFboOit;
494     }
495     else if (myImmediateSceneFbos[0]->IsValid())
496     {
497       anImmFbo    = myImmediateSceneFbos[0].operator->();
498       anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
499     }
500
501   #if !defined(GL_ES_VERSION_2_0)
502     if (aMainFbo == NULL)
503     {
504       aCtx->SetReadDrawBuffer (GL_BACK);
505     }
506   #endif
507     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
508                          aMainFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
509
510     redraw (aProjectType, aMainFbo, aMainFboOit);
511     myBackBufferRestored = Standard_True;
512     myIsImmediateDrawn   = Standard_False;
513     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
514                          anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
515     if (!redrawImmediate (aProjectType, aMainFbo, anImmFbo, anImmFboOit))
516     {
517       toSwap = false;
518     }
519
520     if (anImmFbo != NULL
521      && anImmFbo != aFrameBuffer)
522     {
523       blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
524     }
525   }
526
527   if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
528    && myRenderParams.IsGlobalIlluminationEnabled)
529   {
530     myAccumFrames++;
531   }
532
533   // bind default FBO
534   bindDefaultFbo();
535
536   if (wasDisabledMSAA != myToDisableMSAA
537    || hadFboBlit      != myHasFboBlit)
538   {
539     // retry on error
540     Redraw();
541   }
542
543   // reset state for safety
544   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
545   aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
546
547   // Swap the buffers
548   if (toSwap)
549   {
550     aCtx->SwapBuffers();
551     if (!myMainSceneFbos[0]->IsValid())
552     {
553       myBackBufferRestored = Standard_False;
554     }
555   }
556   else
557   {
558     aCtx->core11fwd->glFlush();
559   }
560
561   // reset render mode state
562   aCtx->FetchState();
563
564   myWasRedrawnGL = Standard_True;
565 }
566
567 // =======================================================================
568 // function : RedrawImmediate
569 // purpose  :
570 // =======================================================================
571 void OpenGl_View::RedrawImmediate()
572 {
573   if (!myWorkspace->Activate())
574     return;
575
576   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
577   if (!myTransientDrawToFront
578    || !myBackBufferRestored
579    || (aCtx->caps->buffersNoSwap && !myMainSceneFbos[0]->IsValid()))
580   {
581     Redraw();
582     return;
583   }
584
585   const Graphic3d_StereoMode   aStereoMode  = myRenderParams.StereoMode;
586   Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
587   OpenGl_FrameBuffer*          aFrameBuffer = myFBO.operator->();
588
589   if ( aFrameBuffer == NULL
590    && !aCtx->DefaultFrameBuffer().IsNull()
591    &&  aCtx->DefaultFrameBuffer()->IsValid())
592   {
593     aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
594   }
595
596   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
597   {
598     if (myMainSceneFbos[0]->IsValid()
599     && !myMainSceneFbos[1]->IsValid())
600     {
601       aProjectType = Graphic3d_Camera::Projection_Perspective;
602     }
603   }
604
605   bool toSwap = false;
606   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
607   {
608     OpenGl_FrameBuffer* aMainFbos[2] =
609     {
610       myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
611       myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
612     };
613     OpenGl_FrameBuffer* anImmFbos[2] =
614     {
615       myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
616       myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
617     };
618     OpenGl_FrameBuffer* anImmFbosOit[2] =
619     {
620       myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
621       myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
622         myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
623     };
624     if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
625      || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
626     {
627       anImmFbos[0]    = NULL;
628       anImmFbos[1]    = NULL;
629       anImmFbosOit[0] = NULL;
630       anImmFbosOit[1] = NULL;
631     }
632
633     if (aCtx->arbFBO != NULL)
634     {
635       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
636     }
637   #if !defined(GL_ES_VERSION_2_0)
638     if (anImmFbos[0] == NULL)
639     {
640       aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
641     }
642   #endif
643
644     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
645                          anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
646     toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye,
647                               aMainFbos[0],
648                               anImmFbos[0],
649                               anImmFbosOit[0],
650                               Standard_True) || toSwap;
651     if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
652     &&  toSwap
653     && !aCtx->caps->buffersNoSwap)
654     {
655       aCtx->SwapBuffers();
656     }
657
658     if (aCtx->arbFBO != NULL)
659     {
660       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
661     }
662   #if !defined(GL_ES_VERSION_2_0)
663     if (anImmFbos[1] == NULL)
664     {
665       aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
666     }
667   #endif
668     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
669                          anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
670     toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye,
671                               aMainFbos[1],
672                               anImmFbos[1],
673                               anImmFbosOit[1],
674                               Standard_True) || toSwap;
675     if (anImmFbos[0] != NULL)
676     {
677       drawStereoPair (aFrameBuffer);
678     }
679   }
680   else
681   {
682     OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
683     OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
684     OpenGl_FrameBuffer* anImmFboOit = NULL;
685     if (myImmediateSceneFbos[0]->IsValid())
686     {
687       anImmFbo    = myImmediateSceneFbos[0].operator->();
688       anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
689     }
690   #if !defined(GL_ES_VERSION_2_0)
691     if (aMainFbo == NULL)
692     {
693       aCtx->SetReadDrawBuffer (GL_BACK);
694     }
695   #endif
696     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
697                          anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
698     toSwap = redrawImmediate (aProjectType,
699                               aMainFbo,
700                               anImmFbo,
701                               anImmFboOit,
702                               Standard_True) || toSwap;
703     if (anImmFbo != NULL
704      && anImmFbo != aFrameBuffer)
705     {
706       blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
707     }
708   }
709
710   // bind default FBO
711   bindDefaultFbo();
712
713   // reset state for safety
714   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
715   aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
716
717   if (toSwap && !aCtx->caps->buffersNoSwap)
718   {
719     aCtx->SwapBuffers();
720   }
721   else
722   {
723     aCtx->core11fwd->glFlush();
724   }
725
726   myWasRedrawnGL = Standard_True;
727 }
728
729 // =======================================================================
730 // function : redraw
731 // purpose  :
732 // =======================================================================
733 void OpenGl_View::redraw (const Graphic3d_Camera::Projection theProjection,
734                           OpenGl_FrameBuffer*                theReadDrawFbo,
735                           OpenGl_FrameBuffer*                theOitAccumFbo)
736 {
737   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
738   if (theReadDrawFbo != NULL)
739   {
740     theReadDrawFbo->BindBuffer    (aCtx);
741     theReadDrawFbo->SetupViewport (aCtx);
742   }
743   else
744   {
745     const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
746     aCtx->ResizeViewport (aViewport);
747   }
748
749   // request reset of material
750   aCtx->ShaderManager()->UpdateMaterialState();
751
752   myWorkspace->UseZBuffer()    = Standard_True;
753   myWorkspace->UseDepthWrite() = Standard_True;
754   GLbitfield toClear = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
755   glDepthFunc (GL_LEQUAL);
756   glDepthMask (GL_TRUE);
757   glEnable (GL_DEPTH_TEST);
758
759 #if !defined(GL_ES_VERSION_2_0)
760   glClearDepth (1.0);
761 #else
762   glClearDepthf (1.0f);
763 #endif
764
765   const OpenGl_Vec4& aBgColor = myBgColor;
766   glClearColor (aBgColor.r(), aBgColor.g(), aBgColor.b(), 0.0f);
767
768   glClear (toClear);
769
770   render (theProjection, theReadDrawFbo, theOitAccumFbo, Standard_False);
771 }
772
773 // =======================================================================
774 // function : redrawMonoImmediate
775 // purpose  :
776 // =======================================================================
777 bool OpenGl_View::redrawImmediate (const Graphic3d_Camera::Projection theProjection,
778                                    OpenGl_FrameBuffer*                theReadFbo,
779                                    OpenGl_FrameBuffer*                theDrawFbo,
780                                    OpenGl_FrameBuffer*                theOitAccumFbo,
781                                    const Standard_Boolean             theIsPartialUpdate)
782 {
783   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
784   GLboolean toCopyBackToFront = GL_FALSE;
785   if (theDrawFbo == theReadFbo
786    && theDrawFbo != NULL)
787   {
788     myBackBufferRestored = Standard_False;
789   }
790   else if (theReadFbo != NULL
791         && theReadFbo->IsValid()
792         && aCtx->IsRender())
793   {
794     if (!blitBuffers (theReadFbo, theDrawFbo))
795     {
796       return true;
797     }
798   }
799   else if (theDrawFbo == NULL)
800   {
801   #if !defined(GL_ES_VERSION_2_0)
802     aCtx->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
803   #endif
804     if (toCopyBackToFront)
805     {
806       if (!HasImmediateStructures()
807        && !theIsPartialUpdate)
808       {
809         // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
810         return true;
811       }
812       if (!copyBackToFront())
813       {
814         toCopyBackToFront    = GL_FALSE;
815         myBackBufferRestored = Standard_False;
816       }
817     }
818     else
819     {
820       myBackBufferRestored = Standard_False;
821     }
822   }
823   else
824   {
825     myBackBufferRestored = Standard_False;
826   }
827   myIsImmediateDrawn = Standard_True;
828
829   myWorkspace->UseZBuffer()    = Standard_True;
830   myWorkspace->UseDepthWrite() = Standard_True;
831   glDepthFunc (GL_LEQUAL);
832   glDepthMask (GL_TRUE);
833   glEnable (GL_DEPTH_TEST);
834 #if !defined(GL_ES_VERSION_2_0)
835   glClearDepth (1.0);
836 #else
837   glClearDepthf (1.0f);
838 #endif
839
840   render (theProjection, theDrawFbo, theOitAccumFbo, Standard_True);
841
842   return !toCopyBackToFront;
843 }
844
845 //=======================================================================
846 //function : Render
847 //purpose  :
848 //=======================================================================
849 void OpenGl_View::render (Graphic3d_Camera::Projection theProjection,
850                           OpenGl_FrameBuffer*          theOutputFBO,
851                           OpenGl_FrameBuffer*          theOitAccumFbo,
852                           const Standard_Boolean       theToDrawImmediate)
853 {
854   // ==================================
855   //      Step 1: Prepare for render
856   // ==================================
857
858   const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
859
860 #if !defined(GL_ES_VERSION_2_0)
861   // Disable current clipping planes
862   if (aContext->core11 != NULL)
863   {
864     const Standard_Integer aMaxPlanes = aContext->MaxClipPlanes();
865     for (Standard_Integer aClipPlaneId = GL_CLIP_PLANE0; aClipPlaneId < GL_CLIP_PLANE0 + aMaxPlanes; ++aClipPlaneId)
866     {
867       aContext->core11fwd->glDisable (aClipPlaneId);
868     }
869   }
870 #endif
871
872   // Update states of OpenGl_BVHTreeSelector (frustum culling algorithm).
873   myBVHSelector.SetViewVolume (myCamera);
874   myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height());
875
876   const Handle(OpenGl_ShaderManager)& aManager   = aContext->ShaderManager();
877   if (StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index()) != myLastLightSourceState)
878   {
879     aManager->UpdateLightSourceStateTo (myShadingModel == Graphic3d_TOSM_NONE ? &myNoShadingLight : &myLights);
880     myLastLightSourceState = StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index());
881   }
882
883   // Update matrices if camera has changed.
884   Graphic3d_WorldViewProjState aWVPState = myCamera->WorldViewProjState();
885   if (myWorldViewProjState != aWVPState)
886   {
887     myAccumFrames = 0;
888     myWorldViewProjState = aWVPState;
889   }
890
891   myLocalOrigin.SetCoord (0.0, 0.0, 0.0);
892   aContext->ProjectionState.SetCurrent (myCamera->ProjectionMatrixF());
893   aContext->WorldViewState .SetCurrent (myCamera->OrientationMatrixF());
894   aContext->ApplyProjectionMatrix();
895   aContext->ApplyWorldViewMatrix();
896   if (aManager->ModelWorldState().Index() == 0)
897   {
898     aContext->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
899   }
900
901   // ====================================
902   //      Step 2: Redraw background
903   // ====================================
904
905   // Render background
906   if (!theToDrawImmediate)
907   {
908     drawBackground (myWorkspace);
909   }
910
911 #if !defined(GL_ES_VERSION_2_0)
912   // Switch off lighting by default
913   if (aContext->core11 != NULL)
914   {
915     glDisable(GL_LIGHTING);
916   }
917 #endif
918
919   // =================================
920   //      Step 3: Redraw main plane
921   // =================================
922
923   // Setup face culling
924   GLboolean isCullFace = GL_FALSE;
925   if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
926   {
927     isCullFace = glIsEnabled (GL_CULL_FACE);
928     if (myBackfacing == Graphic3d_TOBM_DISABLE)
929     {
930       glEnable (GL_CULL_FACE);
931       glCullFace (GL_BACK);
932     }
933     else
934       glDisable (GL_CULL_FACE);
935   }
936
937 #if !defined(GL_ES_VERSION_2_0)
938   // if the view is scaled normal vectors are scaled to unit
939   // length for correct displaying of shaded objects
940   const gp_Pnt anAxialScale = myCamera->AxialScale();
941   if (anAxialScale.X() != 1.F ||
942       anAxialScale.Y() != 1.F ||
943       anAxialScale.Z() != 1.F)
944   {
945     aContext->SetGlNormalizeEnabled (Standard_True);
946   }
947   else
948   {
949     aContext->SetGlNormalizeEnabled (Standard_False);
950   }
951
952   // Apply InteriorShadingMethod
953   if (aContext->core11 != NULL)
954   {
955     aContext->core11->glShadeModel (myShadingModel == Graphic3d_TOSM_FACET
956                                  || myShadingModel == Graphic3d_TOSM_NONE ? GL_FLAT : GL_SMOOTH);
957   }
958 #endif
959
960   aManager->SetShadingModel (myShadingModel);
961
962   // Redraw 3d scene
963   if (theProjection == Graphic3d_Camera::Projection_MonoLeftEye)
964   {
965     aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoLeftF());
966     aContext->ApplyProjectionMatrix();
967   }
968   else if (theProjection == Graphic3d_Camera::Projection_MonoRightEye)
969   {
970     aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoRightF());
971     aContext->ApplyProjectionMatrix();
972   }
973
974   myWorkspace->SetEnvironmentTexture (myTextureEnv);
975
976   renderScene (theProjection, theOutputFBO, theOitAccumFbo, theToDrawImmediate);
977
978   myWorkspace->SetEnvironmentTexture (Handle(OpenGl_Texture)());
979
980   // ===============================
981   //      Step 4: Trihedron
982   // ===============================
983
984   // Resetting GL parameters according to the default aspects
985   // in order to synchronize GL state with the graphic driver state
986   // before drawing auxiliary stuff (trihedrons, overlayer)
987   myWorkspace->ResetAppliedAspect();
988
989   // Render trihedron
990   if (!theToDrawImmediate)
991   {
992     renderTrihedron (myWorkspace);
993
994     // Restore face culling
995     if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
996     {
997       if (isCullFace)
998       {
999         glEnable (GL_CULL_FACE);
1000         glCullFace (GL_BACK);
1001       }
1002       else
1003         glDisable (GL_CULL_FACE);
1004     }
1005   }
1006
1007   // reset FFP state for safety
1008   aContext->BindProgram (Handle(OpenGl_ShaderProgram)());
1009   aContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1010
1011   // ==============================================================
1012   //      Step 6: Keep shader manager informed about last View
1013   // ==============================================================
1014
1015   if (!aManager.IsNull())
1016   {
1017     aManager->SetLastView (this);
1018   }
1019 }
1020
1021 // =======================================================================
1022 // function : InvalidateBVHData
1023 // purpose  :
1024 // =======================================================================
1025 void OpenGl_View::InvalidateBVHData (const Graphic3d_ZLayerId theLayerId)
1026 {
1027   myZLayers.InvalidateBVHData (theLayerId);
1028 }
1029
1030 //=======================================================================
1031 //function : renderStructs
1032 //purpose  :
1033 //=======================================================================
1034 void OpenGl_View::renderStructs (Graphic3d_Camera::Projection theProjection,
1035                                  OpenGl_FrameBuffer*          theReadDrawFbo,
1036                                  OpenGl_FrameBuffer*          theOitAccumFbo,
1037                                  const Standard_Boolean       theToDrawImmediate)
1038 {
1039   if ( myZLayers.NbStructures() <= 0 )
1040     return;
1041
1042   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1043   Standard_Boolean toRenderGL = theToDrawImmediate ||
1044     myRenderParams.Method != Graphic3d_RM_RAYTRACING ||
1045     myRaytraceInitStatus == OpenGl_RT_FAIL ||
1046     aCtx->IsFeedback();
1047
1048   if (!toRenderGL)
1049   {
1050     toRenderGL = !initRaytraceResources (aCtx) ||
1051       !updateRaytraceGeometry (OpenGl_GUM_CHECK, myId, aCtx);
1052
1053     toRenderGL |= !myIsRaytraceDataValid; // if no ray-trace data use OpenGL
1054
1055     if (!toRenderGL)
1056     {
1057       const Standard_Integer aSizeX = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeX() : myWindow->Width();
1058       const Standard_Integer aSizeY = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeY() : myWindow->Height();
1059       myOpenGlFBO ->InitLazy (aCtx, aSizeX, aSizeY, myFboColorFormat, myFboDepthFormat, 0);
1060
1061       if (myRaytraceFilter.IsNull())
1062         myRaytraceFilter = new OpenGl_RaytraceFilter;
1063
1064       myRaytraceFilter->SetPrevRenderFilter (myWorkspace->GetRenderFilter());
1065
1066       if (theReadDrawFbo != NULL)
1067         theReadDrawFbo->UnbindBuffer (aCtx);
1068
1069       // Prepare preliminary OpenGL output
1070       if (aCtx->arbFBOBlit != NULL)
1071       {
1072         // Render bottom OSD layer
1073         myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Bottom, theReadDrawFbo, theOitAccumFbo);
1074
1075         myWorkspace->SetRenderFilter (myRaytraceFilter);
1076         {
1077           if (theReadDrawFbo != NULL)
1078           {
1079             theReadDrawFbo->BindDrawBuffer (aCtx);
1080           }
1081           else
1082           {
1083             aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, 0);
1084           }
1085
1086           // Render non-polygonal elements in default layer
1087           myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Default, theReadDrawFbo, theOitAccumFbo);
1088         }
1089         myWorkspace->SetRenderFilter (myRaytraceFilter->PrevRenderFilter());
1090       }
1091
1092       if (theReadDrawFbo != NULL)
1093       {
1094         theReadDrawFbo->BindBuffer (aCtx);
1095       }
1096       else
1097       {
1098         aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, 0);
1099       }
1100
1101       // Reset OpenGl aspects state to default to avoid enabling of
1102       // backface culling which is not supported in ray-tracing.
1103       myWorkspace->ResetAppliedAspect();
1104
1105       // Ray-tracing polygonal primitive arrays
1106       raytrace (aSizeX, aSizeY, theProjection, theReadDrawFbo, aCtx);
1107
1108       // Render upper (top and topmost) OpenGL layers
1109       myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Upper, theReadDrawFbo, theOitAccumFbo);
1110     }
1111   }
1112
1113   // Redraw 3D scene using OpenGL in standard
1114   // mode or in case of ray-tracing failure
1115   if (toRenderGL)
1116   {
1117     myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_All, theReadDrawFbo, theOitAccumFbo);
1118
1119     // Set flag that scene was redrawn by standard pipeline
1120     myWasRedrawnGL = Standard_True;
1121   }
1122 }
1123
1124 //=======================================================================
1125 //function : renderTrihedron
1126 //purpose  :
1127 //=======================================================================
1128 void OpenGl_View::renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace)
1129 {
1130   if (myToShowGradTrihedron)
1131   {
1132     myGraduatedTrihedron.Render (theWorkspace);
1133   }
1134 }
1135
1136 // =======================================================================
1137 // function : Invalidate
1138 // purpose  :
1139 // =======================================================================
1140 void OpenGl_View::Invalidate()
1141 {
1142   myBackBufferRestored = Standard_False;
1143 }
1144
1145 //=======================================================================
1146 //function : renderScene
1147 //purpose  :
1148 //=======================================================================
1149 void OpenGl_View::renderScene (Graphic3d_Camera::Projection theProjection,
1150                                OpenGl_FrameBuffer*          theReadDrawFbo,
1151                                OpenGl_FrameBuffer*          theOitAccumFbo,
1152                                const Standard_Boolean       theToDrawImmediate)
1153 {
1154   const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
1155
1156   // Specify clipping planes in view transformation space
1157   aContext->ChangeClipping().Reset (aContext, myClipPlanes);
1158   if (!myClipPlanes.IsNull()
1159    && !myClipPlanes->IsEmpty())
1160   {
1161     aContext->ShaderManager()->UpdateClippingState();
1162   }
1163
1164   renderStructs (theProjection, theReadDrawFbo, theOitAccumFbo, theToDrawImmediate);
1165   myWorkspace->DisableTexture();
1166
1167   // Apply restored view matrix.
1168   aContext->ApplyWorldViewMatrix();
1169
1170   aContext->ChangeClipping().Reset (aContext, Handle(Graphic3d_SequenceOfHClipPlane)());
1171   if (!myClipPlanes.IsNull()
1172    && !myClipPlanes->IsEmpty())
1173   {
1174     aContext->ShaderManager()->RevertClippingState();
1175   }
1176 }
1177
1178 // =======================================================================
1179 // function : bindDefaultFbo
1180 // purpose  :
1181 // =======================================================================
1182 void OpenGl_View::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
1183 {
1184   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1185   OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
1186                             ?  theCustomFbo
1187                             : (!aCtx->DefaultFrameBuffer().IsNull()
1188                              && aCtx->DefaultFrameBuffer()->IsValid()
1189                               ? aCtx->DefaultFrameBuffer().operator->()
1190                               : NULL);
1191   if (anFbo != NULL)
1192   {
1193     anFbo->BindBuffer (aCtx);
1194     anFbo->SetupViewport (aCtx);
1195   }
1196   else
1197   {
1198   #if !defined(GL_ES_VERSION_2_0)
1199     aCtx->SetReadDrawBuffer (GL_BACK);
1200   #else
1201     if (aCtx->arbFBO != NULL)
1202     {
1203       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1204     }
1205   #endif
1206     const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
1207     aCtx->ResizeViewport (aViewport);
1208   }
1209 }
1210
1211 // =======================================================================
1212 // function : initBlitQuad
1213 // purpose  :
1214 // =======================================================================
1215 OpenGl_VertexBuffer* OpenGl_View::initBlitQuad (const Standard_Boolean theToFlip)
1216 {
1217   OpenGl_VertexBuffer* aVerts = NULL;
1218   if (!theToFlip)
1219   {
1220     aVerts = &myFullScreenQuad;
1221     if (!aVerts->IsValid())
1222     {
1223       OpenGl_Vec4 aQuad[4] =
1224       {
1225         OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
1226         OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 1.0f),
1227         OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
1228         OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 1.0f)
1229       };
1230       aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1231     }
1232   }
1233   else
1234   {
1235     aVerts = &myFullScreenQuadFlip;
1236     if (!aVerts->IsValid())
1237     {
1238       OpenGl_Vec4 aQuad[4] =
1239       {
1240         OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 1.0f),
1241         OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 0.0f),
1242         OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 1.0f),
1243         OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 0.0f)
1244       };
1245       aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1246     }
1247   }
1248   return aVerts;
1249 }
1250
1251 // =======================================================================
1252 // function : blitBuffers
1253 // purpose  :
1254 // =======================================================================
1255 bool OpenGl_View::blitBuffers (OpenGl_FrameBuffer*    theReadFbo,
1256                                OpenGl_FrameBuffer*    theDrawFbo,
1257                                const Standard_Boolean theToFlip)
1258 {
1259   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1260   const Standard_Integer aReadSizeX = theReadFbo != NULL ? theReadFbo->GetVPSizeX() : myWindow->Width();
1261   const Standard_Integer aReadSizeY = theReadFbo != NULL ? theReadFbo->GetVPSizeY() : myWindow->Height();
1262   const Standard_Integer aDrawSizeX = theDrawFbo != NULL ? theDrawFbo->GetVPSizeX() : myWindow->Width();
1263   const Standard_Integer aDrawSizeY = theDrawFbo != NULL ? theDrawFbo->GetVPSizeY() : myWindow->Height();
1264   if (theReadFbo == NULL || aCtx->IsFeedback())
1265   {
1266     return false;
1267   }
1268   else if (theReadFbo == theDrawFbo)
1269   {
1270     return true;
1271   }
1272
1273   // clear destination before blitting
1274   if (theDrawFbo != NULL
1275   &&  theDrawFbo->IsValid())
1276   {
1277     theDrawFbo->BindBuffer (aCtx);
1278   }
1279   else
1280   {
1281     aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1282   }
1283   const Standard_Integer aViewport[4] = { 0, 0, aDrawSizeX, aDrawSizeY };
1284   aCtx->ResizeViewport (aViewport);
1285
1286 #if !defined(GL_ES_VERSION_2_0)
1287   aCtx->core20fwd->glClearDepth  (1.0);
1288 #else
1289   aCtx->core20fwd->glClearDepthf (1.0f);
1290 #endif
1291   aCtx->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1292
1293   if (aCtx->arbFBOBlit != NULL
1294    && theReadFbo->NbSamples() != 0)
1295   {
1296     GLbitfield aCopyMask = 0;
1297     theReadFbo->BindReadBuffer (aCtx);
1298     if (theDrawFbo != NULL
1299      && theDrawFbo->IsValid())
1300     {
1301       theDrawFbo->BindDrawBuffer (aCtx);
1302       if (theDrawFbo->HasColor()
1303        && theReadFbo->HasColor())
1304       {
1305         aCopyMask |= GL_COLOR_BUFFER_BIT;
1306       }
1307       if (theDrawFbo->HasDepth()
1308        && theReadFbo->HasDepth())
1309       {
1310         aCopyMask |= GL_DEPTH_BUFFER_BIT;
1311       }
1312     }
1313     else
1314     {
1315       if (theReadFbo->HasColor())
1316       {
1317         aCopyMask |= GL_COLOR_BUFFER_BIT;
1318       }
1319       if (theReadFbo->HasDepth())
1320       {
1321         aCopyMask |= GL_DEPTH_BUFFER_BIT;
1322       }
1323       aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1324     }
1325
1326     // we don't copy stencil buffer here... does it matter for performance?
1327     aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, aReadSizeX, aReadSizeY,
1328                                          0, 0, aDrawSizeX, aDrawSizeY,
1329                                          aCopyMask, GL_NEAREST);
1330     const int anErr = ::glGetError();
1331     if (anErr != GL_NO_ERROR)
1332     {
1333       // glBlitFramebuffer() might fail in several cases:
1334       // - Both FBOs have MSAA and they are samples number does not match.
1335       //   OCCT checks that this does not happen,
1336       //   however some graphics drivers provide an option for overriding MSAA.
1337       //   In this case window MSAA might be non-zero (and application can not check it)
1338       //   and might not match MSAA of our offscreen FBOs.
1339       // - Pixel formats of FBOs do not match.
1340       //   This also might happen with window has pixel format,
1341       //   e.g. Mesa fails blitting RGBA8 -> RGB8 while other drivers support this conversion.
1342       TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "FBO blitting has failed [Error #" + anErr + "]\n"
1343                                       + "  Please check your graphics driver settings or try updating driver.";
1344       if (theReadFbo->NbSamples() != 0)
1345       {
1346         myToDisableMSAA = true;
1347         aMsg += "\n  MSAA settings should not be overridden by driver!";
1348       }
1349       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1350                          GL_DEBUG_TYPE_ERROR,
1351                          0,
1352                          GL_DEBUG_SEVERITY_HIGH,
1353                          aMsg);
1354     }
1355
1356     if (theDrawFbo != NULL
1357      && theDrawFbo->IsValid())
1358     {
1359       theDrawFbo->BindBuffer (aCtx);
1360     }
1361     else
1362     {
1363       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1364     }
1365   }
1366   else
1367   {
1368     aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1369     aCtx->core20fwd->glDepthMask (GL_TRUE);
1370     aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1371   #if defined(GL_ES_VERSION_2_0)
1372     if (!aCtx->IsGlGreaterEqual (3, 0)
1373      && !aCtx->extFragDepth)
1374     {
1375       aCtx->core20fwd->glDisable (GL_DEPTH_TEST);
1376     }
1377   #endif
1378
1379     myWorkspace->DisableTexture();
1380
1381     const Graphic3d_TypeOfTextureFilter aFilter = (aDrawSizeX == aReadSizeX && aDrawSizeY == aReadSizeY) ? Graphic3d_TOTF_NEAREST : Graphic3d_TOTF_BILINEAR;
1382     const GLint aFilterGl = aFilter == Graphic3d_TOTF_NEAREST ? GL_NEAREST : GL_LINEAR;
1383
1384     OpenGl_VertexBuffer* aVerts = initBlitQuad (theToFlip);
1385     const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1386     if (aVerts->IsValid()
1387      && aManager->BindFboBlitProgram())
1388     {
1389       theReadFbo->ColorTexture()->Bind (aCtx, GL_TEXTURE0 + 0);
1390       if (theReadFbo->ColorTexture()->GetParams()->Filter() != aFilter)
1391       {
1392         theReadFbo->ColorTexture()->GetParams()->SetFilter (aFilter);
1393         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
1394         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
1395       }
1396
1397       theReadFbo->DepthStencilTexture()->Bind (aCtx, GL_TEXTURE0 + 1);
1398       if (theReadFbo->DepthStencilTexture()->GetParams()->Filter() != aFilter)
1399       {
1400         theReadFbo->DepthStencilTexture()->GetParams()->SetFilter (aFilter);
1401         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
1402         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
1403       }
1404
1405       aVerts->BindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1406
1407       aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1408
1409       aVerts->UnbindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1410       theReadFbo->DepthStencilTexture()->Unbind (aCtx, GL_TEXTURE0 + 1);
1411       theReadFbo->ColorTexture()       ->Unbind (aCtx, GL_TEXTURE0 + 0);
1412       aCtx->BindProgram (NULL);
1413     }
1414     else
1415     {
1416       TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1417         + "Error! FBO blitting has failed";
1418       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1419                          GL_DEBUG_TYPE_ERROR,
1420                          0,
1421                          GL_DEBUG_SEVERITY_HIGH,
1422                          aMsg);
1423       myHasFboBlit = Standard_False;
1424       theReadFbo->Release (aCtx.operator->());
1425       return true;
1426     }
1427   }
1428   return true;
1429 }
1430
1431 // =======================================================================
1432 // function : drawStereoPair
1433 // purpose  :
1434 // =======================================================================
1435 void OpenGl_View::drawStereoPair (OpenGl_FrameBuffer* theDrawFbo)
1436 {
1437   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1438   bindDefaultFbo (theDrawFbo);
1439   OpenGl_FrameBuffer* aPair[2] =
1440   {
1441     myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1442     myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1443   };
1444   if (aPair[0] == NULL
1445   ||  aPair[1] == NULL
1446   || !myTransientDrawToFront)
1447   {
1448     aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
1449     aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
1450   }
1451
1452   if (aPair[0] == NULL
1453    || aPair[1] == NULL)
1454   {
1455     return;
1456   }
1457
1458   if (aPair[0]->NbSamples() != 0)
1459   {
1460     // resolve MSAA buffers before drawing
1461     if (!myOpenGlFBO ->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, myFboDepthFormat, 0)
1462      || !myOpenGlFBO2->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, 0, 0))
1463     {
1464       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1465                          GL_DEBUG_TYPE_ERROR,
1466                          0,
1467                          GL_DEBUG_SEVERITY_HIGH,
1468                          "Error! Unable to allocate FBO for blitting stereo pair");
1469       bindDefaultFbo (theDrawFbo);
1470       return;
1471     }
1472
1473     if (!blitBuffers (aPair[0], myOpenGlFBO .operator->(), Standard_False)
1474      || !blitBuffers (aPair[1], myOpenGlFBO2.operator->(), Standard_False))
1475     {
1476       bindDefaultFbo (theDrawFbo);
1477       return;
1478     }
1479
1480     aPair[0] = myOpenGlFBO .operator->();
1481     aPair[1] = myOpenGlFBO2.operator->();
1482     bindDefaultFbo (theDrawFbo);
1483   }
1484
1485   struct
1486   {
1487     Standard_Integer left;
1488     Standard_Integer top;
1489     Standard_Integer right;
1490     Standard_Integer bottom;
1491     Standard_Integer dx() { return right  - left; }
1492     Standard_Integer dy() { return bottom - top; }
1493   } aGeom;
1494
1495   myWindow->PlatformWindow()->Position (aGeom.left, aGeom.top, aGeom.right, aGeom.bottom);
1496
1497   Standard_Boolean toReverse = myRenderParams.ToReverseStereo;
1498   const Standard_Boolean isOddY = (aGeom.top + aGeom.dy()) % 2 == 1;
1499   const Standard_Boolean isOddX =  aGeom.left % 2 == 1;
1500   if (isOddY
1501    && (myRenderParams.StereoMode == Graphic3d_StereoMode_RowInterlaced
1502     || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1503   {
1504     toReverse = !toReverse;
1505   }
1506   if (isOddX
1507    && (myRenderParams.StereoMode == Graphic3d_StereoMode_ColumnInterlaced
1508     || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1509   {
1510     toReverse = !toReverse;
1511   }
1512
1513   if (toReverse)
1514   {
1515     std::swap (aPair[0], aPair[1]);
1516   }
1517
1518   aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1519   aCtx->core20fwd->glDepthMask (GL_TRUE);
1520   aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1521
1522   myWorkspace->DisableTexture();
1523   OpenGl_VertexBuffer* aVerts = initBlitQuad (myToFlipOutput);
1524
1525   const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1526   if (aVerts->IsValid()
1527    && aManager->BindStereoProgram (myRenderParams.StereoMode))
1528   {
1529     if (myRenderParams.StereoMode == Graphic3d_StereoMode_Anaglyph)
1530     {
1531       OpenGl_Mat4 aFilterL, aFilterR;
1532       aFilterL.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1533       aFilterR.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1534       switch (myRenderParams.AnaglyphFilter)
1535       {
1536         case Graphic3d_RenderingParams::Anaglyph_RedCyan_Simple:
1537         {
1538           aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1539           aFilterR.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1540           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1541           break;
1542         }
1543         case Graphic3d_RenderingParams::Anaglyph_RedCyan_Optimized:
1544         {
1545           aFilterL.SetRow (0, Graphic3d_Vec4 ( 0.4154f,      0.4710f,      0.16666667f, 0.0f));
1546           aFilterL.SetRow (1, Graphic3d_Vec4 (-0.0458f,     -0.0484f,     -0.0257f,     0.0f));
1547           aFilterL.SetRow (2, Graphic3d_Vec4 (-0.0547f,     -0.0615f,      0.0128f,     0.0f));
1548           aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f,         0.0f,         0.0f,        0.0f));
1549           aFilterR.SetRow (0, Graphic3d_Vec4 (-0.01090909f, -0.03636364f, -0.00606061f, 0.0f));
1550           aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.37560000f,  0.73333333f,  0.01111111f, 0.0f));
1551           aFilterR.SetRow (2, Graphic3d_Vec4 (-0.06510000f, -0.12870000f,  1.29710000f, 0.0f));
1552           aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f,                0.0f,  0.0f,        0.0f));
1553           break;
1554         }
1555         case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Simple:
1556         {
1557           aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1558           aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1559           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1560           break;
1561         }
1562         case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Optimized:
1563         {
1564           aFilterL.SetRow (0, Graphic3d_Vec4 ( 1.062f, -0.205f,  0.299f, 0.0f));
1565           aFilterL.SetRow (1, Graphic3d_Vec4 (-0.026f,  0.908f,  0.068f, 0.0f));
1566           aFilterL.SetRow (2, Graphic3d_Vec4 (-0.038f, -0.173f,  0.022f, 0.0f));
1567           aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f,    0.0f,    0.0f,   0.0f));
1568           aFilterR.SetRow (0, Graphic3d_Vec4 (-0.016f, -0.123f, -0.017f, 0.0f));
1569           aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.006f,  0.062f, -0.017f, 0.0f));
1570           aFilterR.SetRow (2, Graphic3d_Vec4 ( 0.094f,  0.185f,  0.911f, 0.0f));
1571           aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f,    0.0f,    0.0f,   0.0f));
1572           break;
1573         }
1574         case Graphic3d_RenderingParams::Anaglyph_GreenMagenta_Simple:
1575         {
1576           aFilterR.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1577           aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1578           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1579           break;
1580         }
1581         case Graphic3d_RenderingParams::Anaglyph_UserDefined:
1582         {
1583           aFilterL = myRenderParams.AnaglyphLeft;
1584           aFilterR = myRenderParams.AnaglyphRight;
1585           break;
1586         }
1587       }
1588       aCtx->ActiveProgram()->SetUniform (aCtx, "uMultL", aFilterL);
1589       aCtx->ActiveProgram()->SetUniform (aCtx, "uMultR", aFilterR);
1590     }
1591
1592     aPair[0]->ColorTexture()->Bind (aCtx, GL_TEXTURE0 + 0);
1593     aPair[1]->ColorTexture()->Bind (aCtx, GL_TEXTURE0 + 1);
1594     aVerts->BindVertexAttrib (aCtx, 0);
1595
1596     aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1597
1598     aVerts->UnbindVertexAttrib (aCtx, 0);
1599     aPair[1]->ColorTexture()->Unbind (aCtx, GL_TEXTURE0 + 1);
1600     aPair[0]->ColorTexture()->Unbind (aCtx, GL_TEXTURE0 + 0);
1601   }
1602   else
1603   {
1604     TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1605       + "Error! Anaglyph has failed";
1606     aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1607                        GL_DEBUG_TYPE_ERROR,
1608                        0,
1609                        GL_DEBUG_SEVERITY_HIGH,
1610                        aMsg);
1611   }
1612 }
1613
1614 // =======================================================================
1615 // function : copyBackToFront
1616 // purpose  :
1617 // =======================================================================
1618 bool OpenGl_View::copyBackToFront()
1619 {
1620   myIsImmediateDrawn = Standard_False;
1621 #if !defined(GL_ES_VERSION_2_0)
1622   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1623   if (aCtx->core11 == NULL)
1624   {
1625     return false;
1626   }
1627
1628   OpenGl_Mat4 aProjectMat;
1629   Graphic3d_TransformUtils::Ortho2D (aProjectMat,
1630                                      0.0f, static_cast<GLfloat> (myWindow->Width()),
1631                                      0.0f, static_cast<GLfloat> (myWindow->Height()));
1632
1633   aCtx->WorldViewState.Push();
1634   aCtx->ProjectionState.Push();
1635
1636   aCtx->WorldViewState.SetIdentity();
1637   aCtx->ProjectionState.SetCurrent (aProjectMat);
1638
1639   aCtx->ApplyProjectionMatrix();
1640   aCtx->ApplyWorldViewMatrix();
1641
1642   // synchronize FFP state before copying pixels
1643   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
1644   aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1645   aCtx->DisableFeatures();
1646
1647   switch (aCtx->DrawBuffer())
1648   {
1649     case GL_BACK_LEFT:
1650     {
1651       aCtx->SetReadBuffer (GL_BACK_LEFT);
1652       aCtx->SetDrawBuffer (GL_FRONT_LEFT);
1653       break;
1654     }
1655     case GL_BACK_RIGHT:
1656     {
1657       aCtx->SetReadBuffer (GL_BACK_RIGHT);
1658       aCtx->SetDrawBuffer (GL_FRONT_RIGHT);
1659       break;
1660     }
1661     default:
1662     {
1663       aCtx->SetReadBuffer (GL_BACK);
1664       aCtx->SetDrawBuffer (GL_FRONT);
1665       break;
1666     }
1667   }
1668
1669   aCtx->core11->glRasterPos2i (0, 0);
1670   aCtx->core11->glCopyPixels  (0, 0, myWindow->Width() + 1, myWindow->Height() + 1, GL_COLOR);
1671   //aCtx->core11->glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
1672
1673   aCtx->EnableFeatures();
1674
1675   aCtx->WorldViewState.Pop();
1676   aCtx->ProjectionState.Pop();
1677   aCtx->ApplyProjectionMatrix();
1678
1679   // read/write from front buffer now
1680   aCtx->SetReadBuffer (aCtx->DrawBuffer());
1681   return true;
1682 #else
1683   return false;
1684 #endif
1685 }
1686
1687 // =======================================================================
1688 // function : checkOitCompatibility
1689 // purpose  :
1690 // =======================================================================
1691 Standard_Boolean OpenGl_View::checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
1692                                                      const Standard_Boolean theMSAA)
1693 {
1694   // determine if OIT is supported by current OpenGl context
1695   Standard_Boolean& aToDisableOIT = theMSAA ? myToDisableMSAA : myToDisableOIT;
1696   if (aToDisableOIT)
1697   {
1698     return Standard_False;
1699   }
1700
1701   TCollection_ExtendedString aCompatibilityMsg;
1702   if (theGlContext->hasFloatBuffer     == OpenGl_FeatureNotAvailable
1703    && theGlContext->hasHalfFloatBuffer == OpenGl_FeatureNotAvailable)
1704   {
1705     aCompatibilityMsg += "OpenGL context does not support floating-point RGBA color buffer format.\n";
1706   }
1707   if (theMSAA && theGlContext->hasSampleVariables == OpenGl_FeatureNotAvailable)
1708   {
1709     aCompatibilityMsg += "Current version of GLSL does not support built-in sample variables.\n";
1710   }
1711   if (theGlContext->hasDrawBuffers == OpenGl_FeatureNotAvailable)
1712   {
1713     aCompatibilityMsg += "OpenGL context does not support multiple draw buffers.\n";
1714   }
1715   if (aCompatibilityMsg.IsEmpty())
1716   {
1717     return Standard_True;
1718   }
1719
1720   aCompatibilityMsg += "  Blended order-independent transparency will not be available.\n";
1721   theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1722                           GL_DEBUG_TYPE_ERROR,
1723                           0,
1724                           GL_DEBUG_SEVERITY_HIGH,
1725                           aCompatibilityMsg);
1726
1727   aToDisableOIT = Standard_True;
1728   return Standard_False;
1729 }
1730
1731 // =======================================================================
1732 // function : chooseOitColorConfiguration
1733 // purpose  :
1734 // =======================================================================
1735 bool OpenGl_View::chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
1736                                                const Standard_Integer theConfigIndex,
1737                                                OpenGl_ColorFormats& theFormats)
1738 {
1739   theFormats.Clear();
1740   switch (theConfigIndex)
1741   {
1742     case 0: // choose best applicable color format combination
1743     {
1744       theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1745       theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_R16F    : GL_R32F);
1746       return true;
1747     }
1748     case 1: // choose non-optimal applicable color format combination
1749     {
1750       theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1751       theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1752       return true;
1753     }
1754   }
1755   return false; // color combination does not exist
1756 }