556d66a7990beabffa3f3db2f232429ccbc07ddb
[occt.git] / src / OpenGl / OpenGl_Workspace.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 <OpenGl_GlCore15.hxx>
17 #include <OpenGl_ArbFBO.hxx>
18
19 #include <InterfaceGraphic.hxx>
20
21 #include <OpenGl_AspectLine.hxx>
22 #include <OpenGl_AspectFace.hxx>
23 #include <OpenGl_AspectMarker.hxx>
24 #include <OpenGl_AspectText.hxx>
25 #include <OpenGl_Context.hxx>
26 #include <OpenGl_Element.hxx>
27 #include <OpenGl_FrameBuffer.hxx>
28 #include <OpenGl_Structure.hxx>
29 #include <OpenGl_Sampler.hxx>
30 #include <OpenGl_ShaderManager.hxx>
31 #include <OpenGl_Texture.hxx>
32 #include <OpenGl_Utils.hxx>
33 #include <OpenGl_View.hxx>
34 #include <OpenGl_Workspace.hxx>
35
36 #include <Graphic3d_TextureParams.hxx>
37
38 #if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
39   #include <OpenGl_AVIWriter.hxx>
40 #endif
41
42 IMPLEMENT_STANDARD_HANDLE(OpenGl_Workspace,OpenGl_Window)
43 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Workspace,OpenGl_Window)
44
45 namespace
46 {
47   static const TEL_COLOUR  THE_WHITE_COLOR = { { 1.0f, 1.0f, 1.0f, 1.0f } };
48   static const OpenGl_Vec4 THE_BLACK_COLOR      (0.0f, 0.0f, 0.0f, 1.0f);
49
50   static const OpenGl_AspectLine myDefaultAspectLine;
51   static const OpenGl_AspectFace myDefaultAspectFace;
52   static const OpenGl_AspectMarker myDefaultAspectMarker;
53   static const OpenGl_AspectText myDefaultAspectText;
54
55   static const OpenGl_TextParam myDefaultTextParam =
56   {
57     16, Graphic3d_HTA_LEFT, Graphic3d_VTA_BOTTOM
58   };
59
60   static const OpenGl_Matrix myDefaultMatrix =
61   {
62     {{ 1.0F, 0.0F, 0.0F, 0.0F },
63      { 0.0F, 1.0F, 0.0F, 0.0F },
64      { 0.0F, 0.0F, 1.0F, 0.0F },
65      { 0.0F, 0.0F, 0.0F, 1.0F }}
66   };
67
68 };
69
70 // =======================================================================
71 // function : Init
72 // purpose  :
73 // =======================================================================
74 void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
75 {
76   // ambient component
77   if (theProp.color_mask & OPENGL_AMBIENT_MASK)
78   {
79     const float* aSrcAmb = theProp.isphysic ? theProp.ambcol.rgb : theProp.matcol.rgb;
80     Ambient = OpenGl_Vec4 (aSrcAmb[0] * theProp.amb,
81                            aSrcAmb[1] * theProp.amb,
82                            aSrcAmb[2] * theProp.amb,
83                            1.0f);
84   }
85   else
86   {
87     Ambient = THE_BLACK_COLOR;
88   }
89
90   // diffusion component
91   if (theProp.color_mask & OPENGL_DIFFUSE_MASK)
92   {
93     const float* aSrcDif = theProp.isphysic ? theProp.difcol.rgb : theProp.matcol.rgb;
94     Diffuse = OpenGl_Vec4 (aSrcDif[0] * theProp.diff,
95                            aSrcDif[1] * theProp.diff,
96                            aSrcDif[2] * theProp.diff,
97                            1.0f);
98   }
99   else
100   {
101     Diffuse = THE_BLACK_COLOR;
102   }
103
104   // specular component
105   if (theProp.color_mask & OPENGL_SPECULAR_MASK)
106   {
107     const float* aSrcSpe = theProp.isphysic ? theProp.speccol.rgb : THE_WHITE_COLOR.rgb;
108     Specular = OpenGl_Vec4 (aSrcSpe[0] * theProp.spec,
109                             aSrcSpe[1] * theProp.spec,
110                             aSrcSpe[2] * theProp.spec,
111                             1.0f);
112   }
113   else
114   {
115     Specular = THE_BLACK_COLOR;
116   }
117
118   // emission component
119   if (theProp.color_mask & OPENGL_EMISSIVE_MASK)
120   {
121     const float* aSrcEms = theProp.isphysic ? theProp.emscol.rgb : theProp.matcol.rgb;
122     Emission = OpenGl_Vec4 (aSrcEms[0] * theProp.emsv,
123                             aSrcEms[1] * theProp.emsv,
124                             aSrcEms[2] * theProp.emsv,
125                             1.0f);
126   }
127   else
128   {
129     Emission = THE_BLACK_COLOR;
130   }
131
132   ChangeShine()        = theProp.shine;
133   ChangeTransparency() = theProp.trans;
134 }
135
136 // =======================================================================
137 // function : OpenGl_Workspace
138 // purpose  :
139 // =======================================================================
140 OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_GraphicDriver)& theDriver,
141                                     const CALL_DEF_WINDOW&        theCWindow,
142                                     Aspect_RenderingContext       theGContext,
143                                     const Handle(OpenGl_Caps)&    theCaps,
144                                     const Handle(OpenGl_Context)& theShareCtx)
145 : OpenGl_Window (theDriver, theCWindow, theGContext, theCaps, theShareCtx),
146   NamedStatus (0),
147   HighlightColor (&THE_WHITE_COLOR),
148   //
149   myComputeInitStatus (OpenGl_RT_NONE),
150   myIsRaytraceDataValid (Standard_False),
151   myIsRaytraceWarnTextures (Standard_False),
152   myViewModificationStatus (0),
153   myLayersModificationStatus (0),
154   //
155   myRaytraceFilter       (new OpenGl_RaytraceFilter()),
156   myToRedrawGL           (Standard_True),
157   myViewId               (-1),
158   myAntiAliasingMode     (3),
159   myTransientDrawToFront (Standard_True),
160   myBackBufferRestored   (Standard_False),
161   myIsImmediateDrawn     (Standard_False),
162   myUseZBuffer (Standard_False),
163   myUseDepthTest (Standard_True),
164   myUseGLLight (Standard_True),
165   myIsCullingEnabled (Standard_False),
166   myFrameCounter (0),
167   //
168   AspectLine_set (&myDefaultAspectLine),
169   AspectLine_applied (NULL),
170   AspectFace_set (&myDefaultAspectFace),
171   AspectFace_applied (NULL),
172   AspectMarker_set (&myDefaultAspectMarker),
173   AspectMarker_applied (NULL),
174   AspectText_set (&myDefaultAspectText),
175   AspectText_applied (NULL),
176   TextParam_set (&myDefaultTextParam),
177   TextParam_applied (NULL),
178   ViewMatrix_applied (&myDefaultMatrix),
179   StructureMatrix_applied (&myDefaultMatrix),
180   myCullingMode (TelCullUndefined),
181   myModelViewMatrix (myDefaultMatrix),
182   PolygonOffset_applied (THE_DEFAULT_POFFSET)
183 {
184   myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
185   myResultFBO = new OpenGl_FrameBuffer();
186
187   if (!myGlContext->GetResource ("OpenGl_LineAttributes", myLineAttribs))
188   {
189     // share and register for release once the resource is no longer used
190     myLineAttribs = new OpenGl_LineAttributes();
191     myGlContext->ShareResource ("OpenGl_LineAttributes", myLineAttribs);
192     myLineAttribs->Init (myGlContext);
193   }
194
195   // General initialization of the context
196
197 #if !defined(GL_ES_VERSION_2_0)
198   if (myGlContext->core11 != NULL)
199   {
200     // Eviter d'avoir les faces mal orientees en noir.
201     // Pourrait etre utiliser pour detecter les problemes d'orientation
202     glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
203
204     // Optimisation pour le Fog et l'antialiasing
205     glHint (GL_FOG_HINT,            GL_FASTEST);
206     glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
207   }
208
209   glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
210   glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
211 #endif
212
213   // AA mode
214   const char* anAaEnv = ::getenv ("CALL_OPENGL_ANTIALIASING_MODE");
215   if (anAaEnv != NULL)
216   {
217     int v;
218     if (sscanf (anAaEnv, "%d", &v) > 0) myAntiAliasingMode = v;
219   }
220 }
221
222 // =======================================================================
223 // function : SetImmediateModeDrawToFront
224 // purpose  :
225 // =======================================================================
226 Standard_Boolean OpenGl_Workspace::SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer)
227 {
228   const Standard_Boolean aPrevMode = myTransientDrawToFront;
229   myTransientDrawToFront = theDrawToFrontBuffer;
230   return aPrevMode;
231 }
232
233 // =======================================================================
234 // function : ~OpenGl_Workspace
235 // purpose  :
236 // =======================================================================
237 OpenGl_Workspace::~OpenGl_Workspace()
238 {
239   if (!myLineAttribs.IsNull())
240   {
241     myLineAttribs.Nullify();
242     myGlContext->ReleaseResource ("OpenGl_LineAttributes", Standard_True);
243   }
244
245   if (!myResultFBO.IsNull())
246   {
247     myResultFBO->Release (myGlContext.operator->());
248     myResultFBO.Nullify();
249   }
250   if (myFullScreenQuad.IsValid())
251   {
252     myFullScreenQuad.Release (myGlContext.operator->());
253   }
254
255   ReleaseRaytraceResources();
256 }
257
258 // =======================================================================
259 // function : Activate
260 // purpose  :
261 // =======================================================================
262 Standard_Boolean OpenGl_Workspace::Activate()
263 {
264   if (!OpenGl_Window::Activate())
265     return Standard_False;
266
267   ViewMatrix_applied      = &myDefaultMatrix;
268   StructureMatrix_applied = &myDefaultMatrix;
269
270   ResetAppliedAspect();
271
272   return Standard_True;
273 }
274
275 //=======================================================================
276 //function : ResetAppliedAspect
277 //purpose  : Sets default values of GL parameters in accordance with default aspects
278 //=======================================================================
279 void OpenGl_Workspace::ResetAppliedAspect()
280 {
281   myGlContext->BindDefaultVao();
282
283   NamedStatus           = !myTextureBound.IsNull() ? OPENGL_NS_TEXTURE : 0;
284   HighlightColor        = &THE_WHITE_COLOR;
285   AspectLine_set        = &myDefaultAspectLine;
286   AspectLine_applied    = NULL;
287   AspectFace_set        = &myDefaultAspectFace;
288   AspectFace_applied    = NULL;
289   AspectMarker_set      = &myDefaultAspectMarker;
290   AspectMarker_applied  = NULL;
291   AspectText_set        = &myDefaultAspectText;
292   AspectText_applied    = NULL;
293   TextParam_set         = &myDefaultTextParam;
294   TextParam_applied     = NULL;
295   PolygonOffset_applied = THE_DEFAULT_POFFSET;
296   myCullingMode         = TelCullUndefined;
297
298   AspectLine(Standard_True);
299   AspectFace(Standard_True);
300   AspectMarker(Standard_True);
301   AspectText(Standard_True);
302 }
303
304 // =======================================================================
305 // function : DisableTexture
306 // purpose  :
307 // =======================================================================
308 Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
309 {
310   if (myTextureBound.IsNull())
311   {
312     return myTextureBound;
313   }
314
315   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
316   if (!aSampler.IsNull())
317   {
318     aSampler->Unbind (*myGlContext);
319   }
320
321 #if !defined(GL_ES_VERSION_2_0)
322   // reset texture matrix because some code may expect it is identity
323   if (myGlContext->core11 != NULL)
324   {
325     GLint aMatrixMode = GL_TEXTURE;
326     glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
327     glMatrixMode (GL_TEXTURE);
328     glLoadIdentity();
329     glMatrixMode (aMatrixMode);
330   }
331 #endif
332
333   myTextureBound->Unbind (myGlContext);
334   switch (myTextureBound->GetTarget())
335   {
336   #if !defined(GL_ES_VERSION_2_0)
337     case GL_TEXTURE_1D:
338     {
339       if (myGlContext->core11 != NULL)
340       {
341         if (myTextureBound->GetParams()->GenMode() != GL_NONE)
342         {
343           glDisable (GL_TEXTURE_GEN_S);
344         }
345         glDisable (GL_TEXTURE_1D);
346       }
347       break;
348     }
349   #endif
350     case GL_TEXTURE_2D:
351     {
352     #if !defined(GL_ES_VERSION_2_0)
353       if (myGlContext->core11 != NULL)
354       {
355         if (myTextureBound->GetParams()->GenMode() != GL_NONE)
356         {
357           glDisable (GL_TEXTURE_GEN_S);
358           glDisable (GL_TEXTURE_GEN_T);
359           if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
360           {
361             glDisable (GL_POINT_SPRITE);
362           }
363         }
364         glDisable (GL_TEXTURE_2D);
365       }
366     #endif
367       break;
368     }
369     default: break;
370   }
371
372   Handle(OpenGl_Texture) aPrevTexture = myTextureBound;
373   myTextureBound.Nullify();
374   return aPrevTexture;
375 }
376
377 // =======================================================================
378 // function : setTextureParams
379 // purpose  :
380 // =======================================================================
381 void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&                theTexture,
382                                          const Handle(Graphic3d_TextureParams)& theParams)
383 {
384   const Handle(Graphic3d_TextureParams)& aParams = theParams.IsNull() ? theTexture->GetParams() : theParams;
385   if (aParams.IsNull())
386   {
387     return;
388   }
389
390 #if !defined(GL_ES_VERSION_2_0)
391   GLint aMatrixMode = GL_TEXTURE;
392   if (myGlContext->core11 != NULL)
393   {
394     glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
395
396     // setup texture matrix
397     glMatrixMode (GL_TEXTURE);
398     OpenGl_Mat4 aTextureMat;
399     const Graphic3d_Vec2& aScale = aParams->Scale();
400     const Graphic3d_Vec2& aTrans = aParams->Translation();
401     OpenGl_Utils::Scale     (aTextureMat,  aScale.x(),  aScale.y(), 1.0f);
402     OpenGl_Utils::Translate (aTextureMat, -aTrans.x(), -aTrans.y(), 0.0f);
403     OpenGl_Utils::Rotate    (aTextureMat, -aParams->Rotation(), 0.0f, 0.0f, 1.0f);
404     glLoadMatrixf (aTextureMat);
405
406     GLint anEnvMode = GL_MODULATE; // lighting mode
407     if (!aParams->IsModulate())
408     {
409       anEnvMode = GL_DECAL;
410       if (theTexture->GetFormat() == GL_ALPHA
411        || theTexture->GetFormat() == GL_LUMINANCE)
412       {
413         anEnvMode = GL_REPLACE;
414       }
415     }
416
417     // setup generation of texture coordinates
418     switch (aParams->GenMode())
419     {
420       case Graphic3d_TOTM_OBJECT:
421       {
422         glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
423         glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
424         if (theTexture->GetTarget() != GL_TEXTURE_1D)
425         {
426           glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
427           glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
428         }
429         break;
430       }
431       case Graphic3d_TOTM_SPHERE:
432       {
433         glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
434         if (theTexture->GetTarget() != GL_TEXTURE_1D)
435         {
436           glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
437         }
438         break;
439       }
440       case Graphic3d_TOTM_EYE:
441       {
442         myGlContext->WorldViewState.Push();
443
444         myGlContext->WorldViewState.SetIdentity();
445         myGlContext->ApplyWorldViewMatrix();
446
447         glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
448         glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
449
450         if (theTexture->GetTarget() != GL_TEXTURE_1D)
451         {
452           glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
453           glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
454         }
455
456         myGlContext->WorldViewState.Pop();
457
458         break;
459       }
460       case Graphic3d_TOTM_SPRITE:
461       {
462         if (GetGlContext()->core20fwd != NULL)
463         {
464           glEnable  (GL_POINT_SPRITE);
465           glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
466           anEnvMode = GL_REPLACE;
467           GetGlContext()->core15->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
468         }
469         break;
470       }
471       case Graphic3d_TOTM_MANUAL:
472       default: break;
473     }
474
475     // setup lighting
476     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, anEnvMode);
477   }
478 #endif
479
480   // get active sampler object to override default texture parameters
481   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
482
483   // setup texture filtering and wrapping
484   //if (theTexture->GetParams() != theParams)
485   const GLenum aFilter   = (aParams->Filter() == Graphic3d_TOTF_NEAREST) ? GL_NEAREST : GL_LINEAR;
486   const GLenum aWrapMode = aParams->IsRepeat() ? GL_REPEAT : myGlContext->TextureWrapClamp();
487   switch (theTexture->GetTarget())
488   {
489   #if !defined(GL_ES_VERSION_2_0)
490     case GL_TEXTURE_1D:
491     {
492       if (aSampler.IsNull() || !aSampler->IsValid())
493       {
494         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, aFilter);
495         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, aFilter);
496         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_WRAP_S,     aWrapMode);
497       }
498       else
499       {
500         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
501         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilter);
502         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
503       }
504
505       break;
506     }
507   #endif
508     case GL_TEXTURE_2D:
509     {
510       GLenum aFilterMin = aFilter;
511       if (theTexture->HasMipmaps())
512       {
513         aFilterMin = GL_NEAREST_MIPMAP_NEAREST;
514         if (aParams->Filter() == Graphic3d_TOTF_BILINEAR)
515         {
516           aFilterMin = GL_LINEAR_MIPMAP_NEAREST;
517         }
518         else if (aParams->Filter() == Graphic3d_TOTF_TRILINEAR)
519         {
520           aFilterMin = GL_LINEAR_MIPMAP_LINEAR;
521         }
522
523         if (myGlContext->extAnis)
524         {
525           // setup degree of anisotropy filter
526           const GLint aMaxDegree = myGlContext->MaxDegreeOfAnisotropy();
527           GLint aDegree;
528           switch (aParams->AnisoFilter())
529           {
530             case Graphic3d_LOTA_QUALITY:
531             {
532               aDegree = aMaxDegree;
533               break;
534             }
535             case Graphic3d_LOTA_MIDDLE:
536             {
537               aDegree = (aMaxDegree <= 4) ? 2 : (aMaxDegree / 2);
538               break;
539             }
540             case Graphic3d_LOTA_FAST:
541             {
542               aDegree = 2;
543               break;
544             }
545             case Graphic3d_LOTA_OFF:
546             default:
547             {
548               aDegree = 1;
549               break;
550             }
551           }
552
553           if (aSampler.IsNull() || !aSampler->IsValid())
554           {
555             glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
556           }
557           else
558           {
559             aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
560           }
561         }
562       }
563
564       if (aSampler.IsNull() || !aSampler->IsValid())
565       {
566         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterMin);
567         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilter);
568         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,     aWrapMode);
569         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,     aWrapMode);
570       }
571       else
572       {
573         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilterMin);
574         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
575         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
576         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_T,     aWrapMode);
577       }
578
579       break;
580     }
581     default: break;
582   }
583
584   switch (theTexture->GetTarget())
585   {
586   #if !defined(GL_ES_VERSION_2_0)
587     case GL_TEXTURE_1D:
588     {
589       if (myGlContext->core11 != NULL)
590       {
591         if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
592         {
593           glEnable (GL_TEXTURE_GEN_S);
594         }
595         glEnable (GL_TEXTURE_1D);
596       }
597       break;
598     }
599   #endif
600     case GL_TEXTURE_2D:
601     {
602     #if !defined(GL_ES_VERSION_2_0)
603       if (myGlContext->core11 != NULL)
604       {
605         if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
606         {
607           glEnable (GL_TEXTURE_GEN_S);
608           glEnable (GL_TEXTURE_GEN_T);
609         }
610         glEnable (GL_TEXTURE_2D);
611       }
612     #endif
613       break;
614     }
615     default: break;
616   }
617
618 #if !defined(GL_ES_VERSION_2_0)
619   if (myGlContext->core11 != NULL)
620   {
621     glMatrixMode (aMatrixMode); // turn back active matrix
622   }
623 #endif
624   theTexture->SetParams (aParams);
625 }
626
627 // =======================================================================
628 // function : EnableTexture
629 // purpose  :
630 // =======================================================================
631 Handle(OpenGl_Texture) OpenGl_Workspace::EnableTexture (const Handle(OpenGl_Texture)&          theTexture,
632                                                         const Handle(Graphic3d_TextureParams)& theParams)
633 {
634   if (theTexture.IsNull() || !theTexture->IsValid())
635   {
636     return DisableTexture();
637   }
638
639   if (myTextureBound == theTexture
640    && (theParams.IsNull() || theParams == theTexture->GetParams()))
641   {
642     // already bound
643     return myTextureBound;
644   }
645
646   Handle(OpenGl_Texture) aPrevTexture = DisableTexture();
647   myTextureBound = theTexture;
648   myTextureBound->Bind (myGlContext);
649   setTextureParams (myTextureBound, theParams);
650
651   // If custom sampler object is available it will be
652   // used for overriding default texture parameters
653   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
654
655   if (!aSampler.IsNull() && aSampler->IsValid())
656   {
657     aSampler->Bind (*myGlContext);
658   }
659
660   return aPrevTexture;
661 }
662
663 // =======================================================================
664 // function : Redraw
665 // purpose  :
666 // =======================================================================
667 void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
668                                const Aspect_CLayer2d& theCUnderLayer,
669                                const Aspect_CLayer2d& theCOverLayer)
670 {
671   if (!Activate())
672   {
673     return;
674   }
675
676   ++myFrameCounter;
677   myIsCullingEnabled = theCView.IsCullingEnabled;
678
679   // release pending GL resources
680   Handle(OpenGl_Context) aGlCtx = GetGlContext();
681   aGlCtx->ReleaseDelayed();
682
683   // fetch OpenGl context state
684   aGlCtx->FetchState();
685
686   Tint toSwap = (aGlCtx->IsRender() && !aGlCtx->caps->buffersNoSwap) ? 1 : 0; // swap buffers
687   OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )theCView.ptrFBO;
688   if (aFrameBuffer != NULL)
689   {
690     aFrameBuffer->SetupViewport (aGlCtx);
691     toSwap = 0; // no need to swap buffers
692   }
693   else
694   {
695     aGlCtx->core11fwd->glViewport (0, 0, myWidth, myHeight);
696   }
697
698   Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWidth;
699   Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myHeight;
700
701   if (myResultFBO->GetVPSizeX() != aSizeX
702    || myResultFBO->GetVPSizeY() != aSizeY)
703   {
704     // prepare FBOs containing main scene
705     // for further blitting and rendering immediate presentations on top
706     if (aGlCtx->core20fwd != NULL)
707     {
708       myResultFBO->Init (aGlCtx, aSizeX, aSizeY);
709     }
710   }
711   if (myResultFBO->IsValid())
712   {
713     myResultFBO->SetupViewport (aGlCtx);
714   }
715
716   const Standard_Boolean isImmediate = myView->HasImmediateStructures()
717                                     || myResultFBO->IsValid();
718
719   myToRedrawGL = Standard_True;
720   if (theCView.RenderParams.Method == Graphic3d_RM_RAYTRACING
721    && myComputeInitStatus != OpenGl_RT_FAIL)
722   {
723     if (UpdateRaytraceGeometry (OpenGl_GUM_CHECK) && myIsRaytraceDataValid)
724     {
725       myToRedrawGL = Standard_False;
726
727       // Only non-raytracable structures should be rendered in OpenGL mode.
728       Handle(OpenGl_RenderFilter) aRenderFilter = GetRenderFilter();
729       myRaytraceFilter->SetPrevRenderFilter (aRenderFilter);
730       SetRenderFilter (myRaytraceFilter);
731
732       if (myOpenGlFBO.IsNull())
733       {
734         myOpenGlFBO = new OpenGl_FrameBuffer();
735       }
736       if (myOpenGlFBO->GetVPSizeX() != aSizeX
737        || myOpenGlFBO->GetVPSizeY() != aSizeY)
738       {
739         myOpenGlFBO->Init (aGlCtx, aSizeX, aSizeY);
740       }
741
742       // OverLayer and UnderLayer shouldn't be drawn by OpenGL.
743       // They will be drawn during ray-tracing.
744       Aspect_CLayer2d anEmptyCLayer;
745       anEmptyCLayer.ptrLayer = NULL;
746
747       myOpenGlFBO->BindBuffer (aGlCtx);
748       redraw1 (theCView, anEmptyCLayer, anEmptyCLayer, 0);
749       myOpenGlFBO->UnbindBuffer (aGlCtx);
750
751       Raytrace (theCView, aSizeX, aSizeY, isImmediate ? 0 : toSwap,
752                 theCOverLayer, theCUnderLayer,
753                 myResultFBO->IsValid() ? myResultFBO.operator->() : aFrameBuffer);
754
755       if (isImmediate)
756       {
757         RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True, aFrameBuffer);
758       }
759
760       SetRenderFilter (aRenderFilter);
761
762       theCView.WasRedrawnGL = Standard_False;
763     }
764   }
765
766   if (myToRedrawGL)
767   {
768     // draw entire frame using normal OpenGL pipeline
769     if (myResultFBO->IsValid())
770     {
771       myResultFBO->BindBuffer (aGlCtx);
772     }
773     else if (aFrameBuffer != NULL)
774     {
775       aFrameBuffer->BindBuffer (aGlCtx);
776     }
777
778     redraw1 (theCView, theCUnderLayer, theCOverLayer, isImmediate ? 0 : toSwap);
779     if (isImmediate)
780     {
781       RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True, aFrameBuffer);
782     }
783
784     theCView.WasRedrawnGL = Standard_True;
785   }
786
787   if (aFrameBuffer != NULL)
788   {
789     aFrameBuffer->UnbindBuffer (aGlCtx);
790     // move back original viewport
791     aGlCtx->core11fwd->glViewport (0, 0, myWidth, myHeight);
792   }
793
794 #if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
795   if (OpenGl_AVIWriter_AllowWriting (theCView.DefWindow.XWindow))
796   {
797     GLint params[4];
798     glGetIntegerv (GL_VIEWPORT, params);
799     int nWidth  = params[2] & ~0x7;
800     int nHeight = params[3] & ~0x7;
801
802     const int nBitsPerPixel = 24;
803     GLubyte* aDumpData = new GLubyte[nWidth * nHeight * nBitsPerPixel / 8];
804
805     glPixelStorei (GL_PACK_ALIGNMENT, 1);
806     glReadPixels (0, 0, nWidth, nHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, aDumpData);
807     OpenGl_AVIWriter_AVIWriter (aDumpData, nWidth, nHeight, nBitsPerPixel);
808     delete[] aDumpData;
809   }
810 #endif
811
812   // reset render mode state
813   aGlCtx->FetchState();
814 }
815
816 // =======================================================================
817 // function : redraw1
818 // purpose  :
819 // =======================================================================
820 void OpenGl_Workspace::redraw1 (const Graphic3d_CView& theCView,
821                                 const Aspect_CLayer2d& theCUnderLayer,
822                                 const Aspect_CLayer2d& theCOverLayer,
823                                 const int              theToSwap)
824 {
825   if (myView.IsNull())
826   {
827     return;
828   }
829
830   // request reset of material
831   NamedStatus |= OPENGL_NS_RESMAT;
832
833   GLbitfield toClear = GL_COLOR_BUFFER_BIT;
834   if (myUseZBuffer)
835   {
836     glDepthFunc (GL_LEQUAL);
837     glDepthMask (GL_TRUE);
838     if (myUseDepthTest)
839     {
840       glEnable (GL_DEPTH_TEST);
841     }
842     else
843     {
844       glDisable (GL_DEPTH_TEST);
845     }
846
847   #if !defined(GL_ES_VERSION_2_0)
848     glClearDepth (1.0);
849   #else
850     glClearDepthf (1.0f);
851   #endif
852     toClear |= GL_DEPTH_BUFFER_BIT;
853   }
854   else
855   {
856     glDisable (GL_DEPTH_TEST);
857   }
858
859   if (!ToRedrawGL())
860   {
861     // set background to black
862     glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
863     toClear |= GL_DEPTH_BUFFER_BIT; //
864   }
865   else
866   {
867     if (NamedStatus & OPENGL_NS_WHITEBACK)
868     {
869         // set background to white
870       glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
871       toClear |= GL_DEPTH_BUFFER_BIT;
872     }
873     else
874     {
875       glClearColor (myBgColor.rgb[0], myBgColor.rgb[1], myBgColor.rgb[2], 0.0f);
876     }
877   }
878   glClear (toClear);
879
880   Handle(OpenGl_Workspace) aWS (this);
881   myView->Render (myPrintContext, aWS, theCView, theCUnderLayer, theCOverLayer, Standard_False);
882
883   // swap the buffers
884   if (theToSwap)
885   {
886     GetGlContext()->SwapBuffers();
887     myBackBufferRestored = Standard_False;
888     myIsImmediateDrawn   = Standard_False;
889   }
890   else
891   {
892     glFlush(); //
893     myBackBufferRestored = Standard_True;//
894     myIsImmediateDrawn   = Standard_False;//
895   }
896 }
897
898 // =======================================================================
899 // function : copyBackToFront
900 // purpose  :
901 // =======================================================================
902 void OpenGl_Workspace::copyBackToFront()
903 {
904 #if !defined(GL_ES_VERSION_2_0)
905
906   OpenGl_Mat4 aProjectMat;
907   OpenGl_Utils::Ortho2D<Standard_ShortReal> (aProjectMat,
908     0.f, static_cast<GLfloat> (myWidth), 0.f, static_cast<GLfloat> (myHeight));
909
910   myGlContext->WorldViewState.Push();
911   myGlContext->ProjectionState.Push();
912
913   myGlContext->WorldViewState.SetIdentity();
914   myGlContext->ProjectionState.SetCurrent (aProjectMat);
915
916   myGlContext->ApplyProjectionMatrix();
917   myGlContext->ApplyWorldViewMatrix();
918
919   DisableFeatures();
920
921   glDrawBuffer (GL_FRONT);
922   glReadBuffer (GL_BACK);
923
924   glRasterPos2i (0, 0);
925   glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_COLOR);
926   //glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
927
928   EnableFeatures();
929
930   myGlContext->WorldViewState.Pop();
931   myGlContext->ProjectionState.Pop();
932   myGlContext->ApplyProjectionMatrix();
933   glDrawBuffer (GL_BACK);
934
935 #endif
936   myIsImmediateDrawn = Standard_False;
937 }
938
939 // =======================================================================
940 // function : DisplayCallback
941 // purpose  :
942 // =======================================================================
943 void OpenGl_Workspace::DisplayCallback (const Graphic3d_CView& theCView,
944                                         Standard_Integer       theReason)
945 {
946   if (theCView.GDisplayCB == NULL)
947   {
948     return;
949   }
950
951   Aspect_GraphicCallbackStruct aCallData;
952   aCallData.reason    = theReason;
953   aCallData.glContext = myGlContext;
954   aCallData.wsID      = theCView.WsId;
955   aCallData.viewID    = theCView.ViewId;
956   aCallData.IsCoreProfile = (myGlContext->core11 == NULL);
957   theCView.GDisplayCB (theCView.DefWindow.XWindow, theCView.GClientData, &aCallData);
958 }
959
960 // =======================================================================
961 // function : RedrawImmediate
962 // purpose  :
963 // =======================================================================
964 void OpenGl_Workspace::RedrawImmediate (const Graphic3d_CView& theCView,
965                                         const Aspect_CLayer2d& theCUnderLayer,
966                                         const Aspect_CLayer2d& theCOverLayer,
967                                         const Standard_Boolean theToForce,
968                                         OpenGl_FrameBuffer*    theTargetFBO)
969 {
970   if (!Activate())
971   {
972     return;
973   }
974
975   GLboolean isDoubleBuffer = GL_FALSE;
976 #if !defined(GL_ES_VERSION_2_0)
977   glGetBooleanv (GL_DOUBLEBUFFER, &isDoubleBuffer);
978 #endif
979   if (!myView->HasImmediateStructures()
980    && !myResultFBO->IsValid())
981   {
982     if (theToForce
983      || !myIsImmediateDrawn)
984     {
985       myIsImmediateDrawn = Standard_False;
986       return;
987     }
988
989     if (myBackBufferRestored
990      && isDoubleBuffer)
991     {
992       copyBackToFront();
993       glFlush();
994     }
995     else
996     {
997       Redraw (theCView, theCUnderLayer, theCOverLayer);
998     }
999     return;
1000   }
1001
1002   if (myResultFBO->IsValid()
1003    && myGlContext->IsRender())
1004   {
1005     if (!myBackBufferRestored)
1006     {
1007       Redraw (theCView, theCUnderLayer, theCOverLayer);
1008       return;
1009     }
1010
1011     // clear destination before blitting
1012     if (theTargetFBO != NULL)
1013     {
1014       theTargetFBO->BindBuffer (myGlContext);
1015     }
1016     else
1017     {
1018       myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1019     }
1020   #if !defined(GL_ES_VERSION_2_0)
1021     myGlContext->core20fwd->glClearDepth  (1.0);
1022   #else
1023     myGlContext->core20fwd->glClearDepthf (1.0f);
1024   #endif
1025     myGlContext->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1026
1027   /*#if !defined(GL_ES_VERSION_2_0)
1028     if (myGlContext->arbFBOBlit != NULL)
1029     {
1030       myResultFBO->BindReadBuffer (myGlContext);
1031       if (theTargetFBO != NULL)
1032       {
1033         theTargetFBO->BindDrawBuffer (myGlContext);
1034       }
1035       else
1036       {
1037         myGlContext->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1038       }
1039       // we don't copy stencil buffer here... does it matter for performance?
1040       myGlContext->arbFBOBlit->glBlitFramebuffer (0, 0, myResultFBO->GetVPSizeX(), myResultFBO->GetVPSizeY(),
1041                                                   0, 0, myResultFBO->GetVPSizeX(), myResultFBO->GetVPSizeY(),
1042                                                   GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
1043
1044       if (theTargetFBO != NULL)
1045       {
1046         theTargetFBO->BindBuffer (myGlContext);
1047       }
1048       else
1049       {
1050         myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1051       }
1052     }
1053     else
1054   #endif*/
1055     {
1056       myGlContext->core20fwd->glDepthFunc (GL_ALWAYS);
1057       myGlContext->core20fwd->glDepthMask (GL_TRUE);
1058       myGlContext->core20fwd->glEnable (GL_DEPTH_TEST);
1059
1060       DisableTexture();
1061       if (!myFullScreenQuad.IsValid())
1062       {
1063         OpenGl_Vec4 aQuad[4] =
1064         {
1065           OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
1066           OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 1.0f),
1067           OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
1068           OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 1.0f)
1069         };
1070         myFullScreenQuad.Init (myGlContext, 4, 4, aQuad[0].GetData());
1071       }
1072
1073       const Handle(OpenGl_ShaderManager)& aManager = myGlContext->ShaderManager();
1074       if (myFullScreenQuad.IsValid()
1075        && aManager->BindFboBlitProgram())
1076       {
1077         myResultFBO->ColorTexture()       ->Bind   (myGlContext, GL_TEXTURE0 + 0);
1078         myResultFBO->DepthStencilTexture()->Bind   (myGlContext, GL_TEXTURE0 + 1);
1079         myFullScreenQuad.BindVertexAttrib (myGlContext, 0);
1080
1081         myGlContext->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1082
1083         myFullScreenQuad.UnbindVertexAttrib (myGlContext, 0);
1084         myResultFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + 1);
1085         myResultFBO->ColorTexture()       ->Unbind (myGlContext, GL_TEXTURE0 + 0);
1086       }
1087     }
1088   }
1089   else if (isDoubleBuffer && myTransientDrawToFront)
1090   {
1091     if (!myBackBufferRestored)
1092     {
1093       Redraw (theCView, theCUnderLayer, theCOverLayer);
1094       return;
1095     }
1096     copyBackToFront();
1097     MakeFrontBufCurrent();
1098   }
1099   else
1100   {
1101     myBackBufferRestored = Standard_False;
1102   }
1103   myIsImmediateDrawn = Standard_True;
1104
1105   Handle(OpenGl_Workspace) aWS (this);
1106
1107   if (myUseZBuffer)
1108   {
1109     glDepthFunc (GL_LEQUAL);
1110     glDepthMask (GL_TRUE);
1111     if (myUseDepthTest)
1112     {
1113       glEnable (GL_DEPTH_TEST);
1114     }
1115     else
1116     {
1117       glDisable (GL_DEPTH_TEST);
1118     }
1119
1120   #if !defined(GL_ES_VERSION_2_0)
1121     glClearDepth (1.0);
1122   #else
1123     glClearDepthf (1.0f);
1124   #endif
1125   }
1126   else
1127   {
1128     glDisable (GL_DEPTH_TEST);
1129   }
1130
1131   myView->Render (myPrintContext, aWS, theCView, theCUnderLayer, theCOverLayer, Standard_True);
1132   if (!myView->ImmediateStructures().IsEmpty())
1133   {
1134     glDisable (GL_DEPTH_TEST);
1135   }
1136   for (OpenGl_SequenceOfStructure::Iterator anIter (myView->ImmediateStructures());
1137        anIter.More(); anIter.Next())
1138   {
1139     const OpenGl_Structure* aStructure = anIter.Value();
1140     if (!aStructure->IsVisible())
1141     {
1142       continue;
1143     }
1144
1145     aStructure->Render (aWS);
1146   }
1147
1148   if (myResultFBO->IsValid())
1149   {
1150     if (theTargetFBO == NULL
1151     &&  myGlContext->IsRender()
1152     && !myGlContext->caps->buffersNoSwap)
1153     {
1154       myGlContext->SwapBuffers();
1155     }
1156   }
1157   else if (isDoubleBuffer && myTransientDrawToFront)
1158   {
1159     glFlush();
1160     MakeBackBufCurrent();
1161   }
1162 }