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