0025556: Visualization - support stereo pair formats recognized by consumer display...
[occt.git] / src / OpenGl / OpenGl_Window.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_GlCore12.hxx>
17 #include <InterfaceGraphic.hxx>
18
19 #include <OpenGl_Context.hxx>
20 #include <OpenGl_GraphicDriver.hxx>
21 #include <OpenGl_Window.hxx>
22 #include <OpenGl_Utils.hxx>
23
24 #include <Aspect_GraphicDeviceDefinitionError.hxx>
25 #include <TCollection_AsciiString.hxx>
26 #include <TCollection_ExtendedString.hxx>
27
28 #if defined(HAVE_EGL) || defined(__ANDROID__)
29   #include <EGL/egl.h>
30 #endif
31
32 IMPLEMENT_STANDARD_HANDLE(OpenGl_Window,MMgt_TShared)
33 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,MMgt_TShared)
34
35 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
36
37 namespace
38 {
39   static const TEL_COLOUR THE_DEFAULT_BG_COLOR = { { 0.F, 0.F, 0.F, 1.F } };
40
41 #if defined(HAVE_EGL) || defined(__ANDROID__)
42   //
43 #elif defined(_WIN32)
44
45   // WGL_ARB_pixel_format
46 #ifndef WGL_NUMBER_PIXEL_FORMATS_ARB
47   #define WGL_NUMBER_PIXEL_FORMATS_ARB            0x2000
48   #define WGL_DRAW_TO_WINDOW_ARB                  0x2001
49   #define WGL_DRAW_TO_BITMAP_ARB                  0x2002
50   #define WGL_ACCELERATION_ARB                    0x2003
51   #define WGL_NEED_PALETTE_ARB                    0x2004
52   #define WGL_NEED_SYSTEM_PALETTE_ARB             0x2005
53   #define WGL_SWAP_LAYER_BUFFERS_ARB              0x2006
54   #define WGL_SWAP_METHOD_ARB                     0x2007
55   #define WGL_NUMBER_OVERLAYS_ARB                 0x2008
56   #define WGL_NUMBER_UNDERLAYS_ARB                0x2009
57   #define WGL_TRANSPARENT_ARB                     0x200A
58   #define WGL_TRANSPARENT_RED_VALUE_ARB           0x2037
59   #define WGL_TRANSPARENT_GREEN_VALUE_ARB         0x2038
60   #define WGL_TRANSPARENT_BLUE_VALUE_ARB          0x2039
61   #define WGL_TRANSPARENT_ALPHA_VALUE_ARB         0x203A
62   #define WGL_TRANSPARENT_INDEX_VALUE_ARB         0x203B
63   #define WGL_SHARE_DEPTH_ARB                     0x200C
64   #define WGL_SHARE_STENCIL_ARB                   0x200D
65   #define WGL_SHARE_ACCUM_ARB                     0x200E
66   #define WGL_SUPPORT_GDI_ARB                     0x200F
67   #define WGL_SUPPORT_OPENGL_ARB                  0x2010
68   #define WGL_DOUBLE_BUFFER_ARB                   0x2011
69   #define WGL_STEREO_ARB                          0x2012
70   #define WGL_PIXEL_TYPE_ARB                      0x2013
71   #define WGL_COLOR_BITS_ARB                      0x2014
72   #define WGL_RED_BITS_ARB                        0x2015
73   #define WGL_RED_SHIFT_ARB                       0x2016
74   #define WGL_GREEN_BITS_ARB                      0x2017
75   #define WGL_GREEN_SHIFT_ARB                     0x2018
76   #define WGL_BLUE_BITS_ARB                       0x2019
77   #define WGL_BLUE_SHIFT_ARB                      0x201A
78   #define WGL_ALPHA_BITS_ARB                      0x201B
79   #define WGL_ALPHA_SHIFT_ARB                     0x201C
80   #define WGL_ACCUM_BITS_ARB                      0x201D
81   #define WGL_ACCUM_RED_BITS_ARB                  0x201E
82   #define WGL_ACCUM_GREEN_BITS_ARB                0x201F
83   #define WGL_ACCUM_BLUE_BITS_ARB                 0x2020
84   #define WGL_ACCUM_ALPHA_BITS_ARB                0x2021
85   #define WGL_DEPTH_BITS_ARB                      0x2022
86   #define WGL_STENCIL_BITS_ARB                    0x2023
87   #define WGL_AUX_BUFFERS_ARB                     0x2024
88
89   #define WGL_NO_ACCELERATION_ARB                 0x2025
90   #define WGL_GENERIC_ACCELERATION_ARB            0x2026
91   #define WGL_FULL_ACCELERATION_ARB               0x2027
92
93   #define WGL_SWAP_EXCHANGE_ARB                   0x2028
94   #define WGL_SWAP_COPY_ARB                       0x2029
95   #define WGL_SWAP_UNDEFINED_ARB                  0x202A
96
97   #define WGL_TYPE_RGBA_ARB                       0x202B
98   #define WGL_TYPE_COLORINDEX_ARB                 0x202C
99 #endif // WGL_NUMBER_PIXEL_FORMATS_ARB
100
101   // WGL_ARB_create_context_profile
102 #ifndef WGL_CONTEXT_MAJOR_VERSION_ARB
103   #define WGL_CONTEXT_MAJOR_VERSION_ARB           0x2091
104   #define WGL_CONTEXT_MINOR_VERSION_ARB           0x2092
105   #define WGL_CONTEXT_LAYER_PLANE_ARB             0x2093
106   #define WGL_CONTEXT_FLAGS_ARB                   0x2094
107   #define WGL_CONTEXT_PROFILE_MASK_ARB            0x9126
108
109   // WGL_CONTEXT_FLAGS bits
110   #define WGL_CONTEXT_DEBUG_BIT_ARB               0x0001
111   #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB  0x0002
112
113   // WGL_CONTEXT_PROFILE_MASK_ARB bits
114   #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB          0x00000001
115   #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
116 #endif // WGL_CONTEXT_MAJOR_VERSION_ARB
117
118   static LRESULT CALLBACK wndProcDummy (HWND theWin, UINT theMsg, WPARAM theParamW, LPARAM theParamL)
119   {
120     return DefWindowProcW (theWin, theMsg, theParamW, theParamL);
121   }
122 #else
123   static Bool WaitForNotify (Display* theDisp, XEvent* theEv, char* theArg)
124   {
125     return (theEv->type == MapNotify) && (theEv->xmap.window == (Window )theArg);
126   }
127 #endif
128
129 }
130
131 // =======================================================================
132 // function : OpenGl_Window
133 // purpose  :
134 // =======================================================================
135 OpenGl_Window::OpenGl_Window (const Handle(OpenGl_GraphicDriver)& theDriver,
136                               const CALL_DEF_WINDOW&        theCWindow,
137                               Aspect_RenderingContext       theGContext,
138                               const Handle(OpenGl_Caps)&    theCaps,
139                               const Handle(OpenGl_Context)& theShareCtx)
140 : myGlContext (new OpenGl_Context (theCaps)),
141   myOwnGContext (theGContext == 0),
142   myWidth   (theCWindow.dx),
143   myHeight  (theCWindow.dy),
144   myBgColor (THE_DEFAULT_BG_COLOR),
145   mySwapInterval (theCaps->swapInterval)
146 {
147   myBgColor.rgb[0] = theCWindow.Background.r;
148   myBgColor.rgb[1] = theCWindow.Background.g;
149   myBgColor.rgb[2] = theCWindow.Background.b;
150
151   Standard_Boolean isCoreProfile = Standard_False;
152
153 #if defined(HAVE_EGL) || defined(__ANDROID__)
154   EGLDisplay anEglDisplay = (EGLDisplay )theDriver->getRawGlDisplay();
155   EGLContext anEglContext = (EGLContext )theDriver->getRawGlContext();
156   EGLConfig  anEglConfig  = (EGLConfig  )theDriver->getRawGlConfig();
157   if (anEglDisplay == EGL_NO_DISPLAY
158    || anEglContext == EGL_NO_CONTEXT
159    || anEglConfig == NULL)
160   {
161     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL does not provide compatible configurations!");
162     return;
163   }
164
165   EGLSurface anEglSurf = EGL_NO_SURFACE;
166   if (theGContext == (EGLContext )EGL_NO_CONTEXT)
167   {
168     // create new surface
169     anEglSurf = eglCreateWindowSurface (anEglDisplay, anEglConfig, (EGLNativeWindowType )theCWindow.XWindow, NULL);
170     if (anEglSurf == EGL_NO_SURFACE)
171     {
172       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is unable to create surface for window!");
173       return;
174     }
175   }
176   else if (theGContext != anEglContext)
177   {
178     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is used in unsupported combination!");
179     return;
180   }
181   else
182   {
183     anEglSurf = eglGetCurrentSurface(EGL_DRAW);
184     if (anEglSurf == EGL_NO_SURFACE)
185     {
186       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is unable to retrieve current surface!");
187       return;
188     }
189   }
190
191   myGlContext->Init ((Aspect_Drawable )anEglSurf, (Aspect_Display )anEglDisplay, (Aspect_RenderingContext )anEglContext, isCoreProfile);
192 #elif defined(_WIN32)
193   (void )theDriver;
194   HWND  aWindow   = (HWND )theCWindow.XWindow;
195   HDC   aWindowDC = GetDC (aWindow);
196   HGLRC aGContext = (HGLRC )theGContext;
197
198   PIXELFORMATDESCRIPTOR aPixelFrmt;
199   memset (&aPixelFrmt, 0, sizeof(aPixelFrmt));
200   aPixelFrmt.nSize        = sizeof(PIXELFORMATDESCRIPTOR);
201   aPixelFrmt.nVersion     = 1;
202   aPixelFrmt.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
203   aPixelFrmt.iPixelType   = PFD_TYPE_RGBA;
204   aPixelFrmt.cColorBits   = 24;
205   aPixelFrmt.cDepthBits   = 24;
206   aPixelFrmt.cStencilBits = 8;
207   aPixelFrmt.iLayerType   = PFD_MAIN_PLANE;
208   if (theCaps->contextStereo)
209   {
210     aPixelFrmt.dwFlags |= PFD_STEREO;
211   }
212
213   int aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
214
215   // in case of failure try without stereo if any
216   const Standard_Boolean hasStereo = aPixelFrmtId != 0 && theCaps->contextStereo;
217   if (aPixelFrmtId == 0 && theCaps->contextStereo)
218   {
219     TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: "
220                                      "ChoosePixelFormat is unable to find stereo supported pixel format. "
221                                      "Choosing similar non stereo format.");
222     myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
223                               GL_DEBUG_TYPE_OTHER_ARB,
224                               0, GL_DEBUG_SEVERITY_HIGH_ARB, aMsg);
225
226     aPixelFrmt.dwFlags &= ~PFD_STEREO;
227     aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
228   }
229
230   if (aPixelFrmtId == 0)
231   {
232     ReleaseDC (aWindow, aWindowDC);
233
234     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
235     aMsg += (int )GetLastError();
236     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
237     return;
238   }
239
240   DescribePixelFormat (aWindowDC, aPixelFrmtId, sizeof(aPixelFrmt), &aPixelFrmt);
241
242   HGLRC aSlaveCtx = !theShareCtx.IsNull() ? (HGLRC )theShareCtx->myGContext : NULL;
243   if (aGContext == NULL)
244   {
245     // create temporary context to retrieve advanced context creation procedures
246     HMODULE aModule = GetModuleHandleW(NULL);
247     WNDCLASSW aClass; memset (&aClass, 0, sizeof(aClass));
248     aClass.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
249     aClass.lpfnWndProc   = wndProcDummy;
250     aClass.hInstance     = aModule;
251     aClass.lpszClassName = L"OpenGl_WindowTmp";
252     HWND  aWinTmp     = NULL;
253     HDC   aDevCtxTmp  = NULL;
254     HGLRC aRendCtxTmp = NULL;
255     if ((!theCaps->contextDebug && !theCaps->contextNoAccel && theCaps->contextCompatible)
256      || RegisterClassW (&aClass) == 0)
257     {
258       aClass.lpszClassName = NULL;
259     }
260     if (aClass.lpszClassName != NULL)
261     {
262       DWORD anExStyle = WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE;
263     #if (_WIN32_WINNT >= 0x0500)
264       anExStyle |= WS_EX_NOACTIVATE;
265     #endif
266       aWinTmp = CreateWindowExW(anExStyle,
267                                 aClass.lpszClassName, L"OpenGl_WindowTmp",
268                                 WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_DISABLED,
269                                 2, 2, 4, 4,
270                                 NULL, NULL, aModule, NULL);
271     }
272     if (aWinTmp != NULL)
273     {
274       aDevCtxTmp = GetDC (aWinTmp);
275       SetPixelFormat (aDevCtxTmp, aPixelFrmtId, &aPixelFrmt);
276       aRendCtxTmp = wglCreateContext (aDevCtxTmp);
277     }
278
279     typedef BOOL (WINAPI *wglChoosePixelFormatARB_t)(HDC           theDevCtx,
280                                                      const int*    theIntAttribs,
281                                                      const float*  theFloatAttribs,
282                                                      unsigned int  theMaxFormats,
283                                                      int*          theFormatsOut,
284                                                      unsigned int* theNumFormatsOut);
285     typedef HGLRC (WINAPI *wglCreateContextAttribsARB_t)(HDC        theDevCtx,
286                                                          HGLRC      theShareContext,
287                                                          const int* theAttribs);
288     wglChoosePixelFormatARB_t    aChoosePixProc = NULL;
289     wglCreateContextAttribsARB_t aCreateCtxProc = NULL;
290     if (aRendCtxTmp != NULL)
291     {
292       wglMakeCurrent (aDevCtxTmp, aRendCtxTmp);
293
294       typedef const char* (WINAPI *wglGetExtensionsStringARB_t)(HDC theDeviceContext);
295       wglGetExtensionsStringARB_t aGetExtensions = (wglGetExtensionsStringARB_t  )wglGetProcAddress ("wglGetExtensionsStringARB");
296       const char* aWglExts = (aGetExtensions != NULL) ? aGetExtensions (wglGetCurrentDC()) : NULL;
297       if (OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_pixel_format"))
298       {
299         aChoosePixProc = (wglChoosePixelFormatARB_t    )wglGetProcAddress ("wglChoosePixelFormatARB");
300       }
301       if (OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_create_context_profile"))
302       {
303         aCreateCtxProc = (wglCreateContextAttribsARB_t )wglGetProcAddress ("wglCreateContextAttribsARB");
304       }
305     }
306
307     // choose extended pixel format
308     if (aChoosePixProc != NULL)
309     {
310       const int aPixAttribs[] =
311       {
312         WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
313         WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
314         WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
315         WGL_STEREO_ARB,         hasStereo ? GL_TRUE : GL_FALSE,
316         WGL_PIXEL_TYPE_ARB,     WGL_TYPE_RGBA_ARB,
317         //WGL_SAMPLE_BUFFERS_ARB, 1,
318         //WGL_SAMPLES_ARB,        8,
319         WGL_COLOR_BITS_ARB,     24,
320         WGL_DEPTH_BITS_ARB,     24,
321         WGL_STENCIL_BITS_ARB,   8,
322         WGL_ACCELERATION_ARB,   theCaps->contextNoAccel ? WGL_NO_ACCELERATION_ARB : WGL_FULL_ACCELERATION_ARB,
323         0, 0,
324       };
325       unsigned int aFrmtsNb = 0;
326       aChoosePixProc (aWindowDC, aPixAttribs, NULL, 1, &aPixelFrmtId, &aFrmtsNb);
327     }
328
329     // setup pixel format - may be set only once per window
330     if (!SetPixelFormat (aWindowDC, aPixelFrmtId, &aPixelFrmt))
331     {
332       ReleaseDC (aWindow, aWindowDC);
333
334       TCollection_AsciiString aMsg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
335       aMsg += (int )GetLastError();
336       Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
337       return;
338     }
339
340     // create GL context with extra options
341     if (aCreateCtxProc != NULL)
342     {
343       if (!theCaps->contextCompatible)
344       {
345         int aCoreCtxAttribs[] =
346         {
347           WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
348           WGL_CONTEXT_MINOR_VERSION_ARB, 2,
349           WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
350           WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
351           0, 0
352         };
353
354         // Try to create the core profile of highest OpenGL version supported by OCCT
355         // (this will be done automatically by some drivers when requesting 3.2,
356         //  but some will not (e.g. AMD Catalyst) since WGL_ARB_create_context_profile specification allows both implementations).
357         for (int aLowVer4 = 5; aLowVer4 >= 0 && aGContext == NULL; --aLowVer4)
358         {
359           aCoreCtxAttribs[1] = 4;
360           aCoreCtxAttribs[3] = aLowVer4;
361           aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCoreCtxAttribs);
362         }
363         for (int aLowVer3 = 3; aLowVer3 >= 2 && aGContext == NULL; --aLowVer3)
364         {
365           aCoreCtxAttribs[1] = 3;
366           aCoreCtxAttribs[3] = aLowVer3;
367           aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCoreCtxAttribs);
368         }
369         isCoreProfile = aGContext != NULL;
370       }
371
372       if (aGContext == NULL)
373       {
374         int aCtxAttribs[] =
375         {
376           // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified
377           // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB.
378           //WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
379           WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
380           0, 0
381         };
382         isCoreProfile = Standard_False;
383         aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCtxAttribs);
384
385         if (aGContext != NULL
386         && !theCaps->contextCompatible)
387         {
388           TCollection_ExtendedString aMsg("OpenGl_Window::CreateWindow: core profile creation failed.");
389           myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMsg);
390         }
391       }
392
393       if (aGContext != NULL)
394       {
395         aSlaveCtx = NULL;
396       }
397     }
398
399     if (aRendCtxTmp != NULL)
400     {
401       wglDeleteContext (aRendCtxTmp);
402     }
403     if (aDevCtxTmp != NULL)
404     {
405       ReleaseDC (aWinTmp, aDevCtxTmp);
406     }
407     if (aWinTmp != NULL)
408     {
409       DestroyWindow (aWinTmp);
410     }
411     if (aClass.lpszClassName != NULL)
412     {
413       UnregisterClassW (aClass.lpszClassName, aModule);
414     }
415
416     if (aGContext == NULL)
417     {
418       // create context using obsolete functionality
419       aGContext = wglCreateContext (aWindowDC);
420     }
421     if (aGContext == NULL)
422     {
423       ReleaseDC (aWindow, aWindowDC);
424
425       TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglCreateContext failed. Error code: ");
426       aMsg += (int )GetLastError();
427       Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
428       return;
429     }
430   }
431
432   // all GL context within one OpenGl_GraphicDriver should be shared!
433   if (aSlaveCtx != NULL && wglShareLists (aSlaveCtx, aGContext) != TRUE)
434   {
435     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglShareLists failed. Error code: ");
436     aMsg += (int )GetLastError();
437     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
438     return;
439   }
440
441   myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext, isCoreProfile);
442 #else
443   Window aParent = (Window )theCWindow.XWindow;
444   Window aWindow = 0;
445
446   Display*   aDisp     = theDriver->GetDisplayConnection()->GetDisplay();
447   GLXContext aGContext = (GLXContext )theGContext;
448
449   XWindowAttributes wattr;
450   XGetWindowAttributes (aDisp, aParent, &wattr);
451   const int scr = DefaultScreen (aDisp);
452
453   XVisualInfo* aVis = NULL;
454   {
455     unsigned long aVisInfoMask = VisualIDMask | VisualScreenMask;
456     XVisualInfo aVisInfo;
457     aVisInfo.visualid = wattr.visual->visualid;
458     aVisInfo.screen   = scr;
459     int aNbItems;
460     aVis = XGetVisualInfo (aDisp, aVisInfoMask, &aVisInfo, &aNbItems);
461   }
462
463 #if defined(__linux) || defined(Linux) || defined(__APPLE__)
464   if (aVis != NULL)
465   {
466     // check Visual for OpenGl context's parameters compatibility
467     int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, isStereo = 0;
468     int aDepthSize = 0, aStencilSize = 0;
469
470     if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0)
471       isGl = 0;
472
473     if (glXGetConfig (aDisp, aVis, GLX_RGBA, &isRGBA) != 0)
474       isRGBA = 0;
475
476     if (glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer) != 0)
477       isDoubleBuffer = 0;
478
479     if (glXGetConfig (aDisp, aVis, GLX_STEREO, &isStereo) != 0)
480       isStereo = 0;
481
482     if (glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE, &aDepthSize) != 0)
483       aDepthSize = 0;
484
485     if (glXGetConfig (aDisp, aVis, GLX_STENCIL_SIZE, &aStencilSize) != 0)
486       aStencilSize = 0;
487
488     if (!isGl)
489     {
490       XFree (aVis);
491       aVis = NULL;
492       if (myOwnGContext)
493       {
494         TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: window Visual does not support GL rendering!");
495         myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
496                                   GL_DEBUG_TYPE_OTHER_ARB,
497                                   0, GL_DEBUG_SEVERITY_HIGH_ARB, aMsg);
498       }
499     }
500     else
501     {
502       TCollection_ExtendedString aList;
503       if (aDepthSize < 1)
504       {
505         if (!aList.IsEmpty()) aList += ", ";
506         aList += "no depth buffer";
507       }
508       if (aStencilSize < 1)
509       {
510         if (!aList.IsEmpty()) aList += ", ";
511         aList += "no stencil buffer";
512       }
513       if (isRGBA == 0)
514       {
515         if (!aList.IsEmpty()) aList += ", ";
516         aList += "no RGBA color buffer";
517       }
518       if (isDoubleBuffer == 0)
519       {
520         if (!aList.IsEmpty()) aList += ", ";
521         aList += "no Double Buffer";
522       }
523       if (theCaps->contextStereo && isStereo == 0)
524       {
525         if (!aList.IsEmpty()) aList += ", ";
526         aList += "no Quad Buffer";
527       }
528       if (!theCaps->contextStereo && isStereo == 1)
529       {
530         if (!aList.IsEmpty()) aList += ", ";
531         aList += "extra Quad Buffer";
532       }
533       if (!aList.IsEmpty())
534       {
535         TCollection_ExtendedString aMsg = TCollection_ExtendedString ("OpenGl_Window::CreateWindow: window Visual is incomplete: ") + aList;
536         if (myOwnGContext)
537         {
538           XFree (aVis);
539           aVis = NULL;
540         }
541         myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
542                                   GL_DEBUG_TYPE_OTHER_ARB,
543                                   0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMsg);
544       }
545     }
546   }
547 #endif
548
549   if (!myOwnGContext)
550   {
551     if (aVis == NULL)
552     {
553       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: XGetVisualInfo is unable to choose needed configuration in existing OpenGL context. ");
554       return;
555     }
556
557     aWindow = aParent;
558   }
559   else
560   {
561     if (aVis == NULL)
562     {
563       int anIter = 0;
564       int anAttribs[13];
565       anAttribs[anIter++] = GLX_RGBA;
566
567       anAttribs[anIter++] = GLX_DEPTH_SIZE;
568       anAttribs[anIter++] = 1;
569
570       anAttribs[anIter++] = GLX_STENCIL_SIZE;
571       anAttribs[anIter++] = 1;
572
573       anAttribs[anIter++] = GLX_RED_SIZE;
574       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
575
576       anAttribs[anIter++] = GLX_GREEN_SIZE;
577       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
578
579       anAttribs[anIter++] = GLX_BLUE_SIZE;
580       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
581
582       anAttribs[anIter++] = GLX_DOUBLEBUFFER;
583
584       // warning: this flag may be set to None, so it need to be last in anAttribs
585       Standard_Integer aStereoFlagPos = anIter;
586       if (theCaps->contextStereo)
587         anAttribs[anIter++] = GLX_STEREO;
588
589       anAttribs[anIter++] = None;
590
591       aVis = glXChooseVisual (aDisp, scr, anAttribs);
592
593       // in case of failure try without stereo if any
594       if (aVis == NULL && theCaps->contextStereo)
595       {
596         TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: "
597                                          "glXChooseVisual is unable to find stereo supported pixel format. "
598                                          "Choosing similar non stereo format.");
599         myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
600                                   GL_DEBUG_TYPE_OTHER_ARB,
601                                   0, GL_DEBUG_SEVERITY_HIGH_ARB, aMsg);
602
603         anAttribs[aStereoFlagPos] = None;
604         aVis = glXChooseVisual (aDisp, scr, anAttribs);
605       }
606
607       if (aVis == NULL)
608       {
609         Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXChooseVisual failed.");
610         return;
611       }
612       else
613       {
614         TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: child window has been created with better Visual.");
615         myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
616                                   GL_DEBUG_TYPE_OTHER_ARB,
617                                   0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMsg);
618       }
619     }
620
621     if (!theShareCtx.IsNull())
622     {
623       // ctx est une copie du previous
624       aGContext = glXCreateContext (aDisp, aVis, (GLXContext )theShareCtx->myGContext, GL_TRUE);
625     }
626     else
627     {
628       aGContext = glXCreateContext (aDisp, aVis, NULL, GL_TRUE);
629     }
630
631     if (!aGContext)
632     {
633       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXCreateContext failed.");
634       return;
635     }
636
637     Colormap cmap = XCreateColormap (aDisp, aParent, aVis->visual, AllocNone);
638
639     XColor color;
640     color.red   = (unsigned short) (myBgColor.rgb[0] * 0xFFFF);
641     color.green = (unsigned short) (myBgColor.rgb[1] * 0xFFFF);
642     color.blue  = (unsigned short) (myBgColor.rgb[2] * 0xFFFF);
643     color.flags = DoRed | DoGreen | DoBlue;
644     XAllocColor (aDisp, cmap, &color);
645
646     XSetWindowAttributes cwa;
647     cwa.colormap         = cmap;
648     cwa.event_mask       = StructureNotifyMask;
649     cwa.border_pixel     = color.pixel;
650     cwa.background_pixel = color.pixel;
651
652     if (aVis->visualid == wattr.visual->visualid)
653     {
654       aWindow = aParent;
655     }
656     else
657     {
658       unsigned long mask = CWBackPixel | CWColormap | CWBorderPixel | CWEventMask;
659       aWindow = XCreateWindow (aDisp, aParent, 0, 0, myWidth, myHeight, 0/*bw*/, aVis->depth, InputOutput, aVis->visual, mask, &cwa);
660     }
661
662     XSetWindowBackground (aDisp, aWindow, cwa.background_pixel);
663     XClearWindow (aDisp, aWindow);
664
665     if (aWindow != aParent)
666     {
667       XEvent anEvent;
668       XMapWindow (aDisp, aWindow);
669       XIfEvent (aDisp, &anEvent, WaitForNotify, (char* )aWindow);
670     }
671   }
672
673   myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )aDisp, (Aspect_RenderingContext )aGContext, isCoreProfile);
674 #endif
675   myGlContext->Share (theShareCtx);
676   myGlContext->SetSwapInterval (mySwapInterval);
677   Init();
678 }
679
680 // =======================================================================
681 // function : ~OpenGl_Window
682 // purpose  :
683 // =======================================================================
684 OpenGl_Window::~OpenGl_Window()
685 {
686   if (!myOwnGContext
687    ||  myGlContext.IsNull())
688   {
689     myGlContext.Nullify();
690     return;
691   }
692
693   // release "GL" context if it is owned by window
694   // Mesa implementation can fail to destroy GL context if it set for current thread.
695   // It should be safer to unset thread GL context before its destruction.
696 #if defined(HAVE_EGL) || defined(__ANDROID__)
697   if ((EGLSurface )myGlContext->myWindow != EGL_NO_SURFACE)
698   {
699     eglDestroySurface ((EGLDisplay )myGlContext->myDisplay,
700                        (EGLSurface )myGlContext->myWindow);
701   }
702 #elif defined(_WIN32)
703   HWND  aWindow          = (HWND  )myGlContext->myWindow;
704   HDC   aWindowDC        = (HDC   )myGlContext->myWindowDC;
705   HGLRC aWindowGContext  = (HGLRC )myGlContext->myGContext;
706   HGLRC aThreadGContext  = wglGetCurrentContext();
707   myGlContext.Nullify();
708
709   if (aThreadGContext != NULL)
710   {
711     if (aThreadGContext == aWindowGContext)
712     {
713       wglMakeCurrent (NULL, NULL);
714     }
715
716     wglDeleteContext (aWindowGContext);
717   }
718   ReleaseDC (aWindow, aWindowDC);
719 #else
720   Display*    aDisplay        = (Display*    )myGlContext->myDisplay;
721   GLXContext  aWindowGContext = (GLXContext  )myGlContext->myGContext;
722   GLXContext  aThreadGContext = glXGetCurrentContext();
723   myGlContext.Nullify();
724
725   if (aDisplay != NULL)
726   {
727     if (aThreadGContext == aWindowGContext)
728     {
729       glXMakeCurrent (aDisplay, None, NULL);
730     }
731
732     // FSXXX sync necessary if non-direct rendering
733     glXWaitGL();
734     glXDestroyContext (aDisplay, aWindowGContext);
735   }
736 #endif
737 }
738
739 #endif // !__APPLE__
740
741 // =======================================================================
742 // function : Activate
743 // purpose  :
744 // =======================================================================
745 Standard_Boolean OpenGl_Window::Activate()
746 {
747   return myGlContext->MakeCurrent();
748 }
749
750 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
751
752 // =======================================================================
753 // function : Resize
754 // purpose  : call_subr_resize
755 // =======================================================================
756 void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
757 {
758 #if !defined(_WIN32) && !defined(HAVE_EGL) && !defined(__ANDROID__)
759   Display* aDisp = (Display* )myGlContext->myDisplay;
760   if (aDisp == NULL)
761     return;
762 #endif
763
764   // If the size is not changed - do nothing
765   if ((myWidth == theCWindow.dx) && (myHeight == theCWindow.dy))
766     return;
767
768   myWidth  = theCWindow.dx;
769   myHeight = theCWindow.dy;
770
771 #if !defined(_WIN32) && !defined(HAVE_EGL) && !defined(__ANDROID__)
772   XResizeWindow (aDisp, myGlContext->myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
773   XSync (aDisp, False);
774 #endif
775
776   Init();
777 }
778
779 #endif // !__APPLE__
780
781 // =======================================================================
782 // function : ReadDepths
783 // purpose  : TelReadDepths
784 // =======================================================================
785 void OpenGl_Window::ReadDepths (const Standard_Integer theX,     const Standard_Integer theY,
786                                 const Standard_Integer theWidth, const Standard_Integer theHeight,
787                                 float* theDepths)
788 {
789   if (theDepths == NULL || !Activate())
790     return;
791
792   OpenGl_Mat4 aProjectMat;
793   OpenGl_Utils::Ortho2D<Standard_ShortReal> (aProjectMat,
794     0.f, static_cast<GLfloat> (myWidth), 0.f, static_cast<GLfloat> (myHeight));
795
796   myGlContext->WorldViewState.Push();
797   myGlContext->ProjectionState.Push();
798
799   myGlContext->WorldViewState.SetIdentity();
800   myGlContext->ProjectionState.SetCurrent (aProjectMat);
801
802   myGlContext->ApplyProjectionMatrix();
803   myGlContext->ApplyWorldViewMatrix();
804
805 #if !defined(GL_ES_VERSION_2_0)
806   glRasterPos2i (theX, theY);
807   DisableFeatures();
808   glReadPixels (theX, theY, theWidth, theHeight, GL_DEPTH_COMPONENT, GL_FLOAT, theDepths);
809   EnableFeatures();
810 #endif
811
812   myGlContext->WorldViewState.Pop();
813   myGlContext->ProjectionState.Pop();
814
815   myGlContext->ApplyProjectionMatrix();
816 }
817
818 // =======================================================================
819 // function : SetBackgroundColor
820 // purpose  : call_subr_set_background
821 // =======================================================================
822 void OpenGl_Window::SetBackgroundColor (const Standard_ShortReal theR,
823                                         const Standard_ShortReal theG,
824                                         const Standard_ShortReal theB)
825 {
826   myBgColor.rgb[0] = theR;
827   myBgColor.rgb[1] = theG;
828   myBgColor.rgb[2] = theB;
829 }
830
831 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
832
833 // =======================================================================
834 // function : Init
835 // purpose  :
836 // =======================================================================
837 void OpenGl_Window::Init()
838 {
839   if (!Activate())
840     return;
841
842 #if defined(HAVE_EGL) || defined(__ANDROID__)
843   eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_WIDTH,  &myWidth);
844   eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_HEIGHT, &myHeight);
845 #elif defined(_WIN32)
846   RECT cr;
847   GetClientRect ((HWND )myGlContext->myWindow, &cr);
848   myWidth  = cr.right - cr.left;
849   myHeight = cr.bottom - cr.top;
850 #else
851   Window aRootWin;
852   int aDummy;
853   unsigned int aDummyU;
854   unsigned int aNewWidth  = 0;
855   unsigned int aNewHeight = 0;
856   Display* aDisp = (Display* )myGlContext->myDisplay;
857   XGetGeometry (aDisp, myGlContext->myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
858   myWidth  = aNewWidth;
859   myHeight = aNewHeight;
860 #endif
861
862   glDisable (GL_DITHER);
863   glDisable (GL_SCISSOR_TEST);
864   glViewport (0, 0, myWidth, myHeight);
865 #if !defined(GL_ES_VERSION_2_0)
866   glDrawBuffer (GL_BACK);
867   if (myGlContext->core11 != NULL)
868   {
869     glMatrixMode (GL_MODELVIEW);
870   }
871 #endif
872 }
873
874 #endif // !__APPLE__
875
876 // =======================================================================
877 // function : EnableFeatures
878 // purpose  :
879 // =======================================================================
880 void OpenGl_Window::EnableFeatures() const
881 {
882   //
883 }
884
885 // =======================================================================
886 // function : DisableFeatures
887 // purpose  :
888 // =======================================================================
889 void OpenGl_Window::DisableFeatures() const
890 {
891 #if !defined(GL_ES_VERSION_2_0)
892   glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
893 #endif
894
895   /*
896   * Disable stuff that's likely to slow down glDrawPixels.
897   * (Omit as much of this as possible, when you know in advance
898   * that the OpenGL state will already be set correctly.)
899   */
900   glDisable(GL_DITHER);
901   glDisable(GL_BLEND);
902   glDisable(GL_DEPTH_TEST);
903   glDisable(GL_TEXTURE_2D);
904   glDisable(GL_STENCIL_TEST);
905
906 #if !defined(GL_ES_VERSION_2_0)
907   glDisable(GL_LIGHTING);
908   glDisable(GL_ALPHA_TEST);
909   glDisable(GL_FOG);
910   glDisable(GL_LOGIC_OP);
911   glDisable(GL_TEXTURE_1D);
912
913   glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
914   glPixelTransferi(GL_RED_SCALE, 1);
915   glPixelTransferi(GL_RED_BIAS, 0);
916   glPixelTransferi(GL_GREEN_SCALE, 1);
917   glPixelTransferi(GL_GREEN_BIAS, 0);
918   glPixelTransferi(GL_BLUE_SCALE, 1);
919   glPixelTransferi(GL_BLUE_BIAS, 0);
920   glPixelTransferi(GL_ALPHA_SCALE, 1);
921   glPixelTransferi(GL_ALPHA_BIAS, 0);
922
923   /*
924   * Disable extensions that could slow down glDrawPixels.
925   * (Actually, you should check for the presence of the proper
926   * extension before making these calls.  I've omitted that
927   * code for simplicity.)
928   */
929
930   if ((myGlContext->myGlVerMajor >= 1) && (myGlContext->myGlVerMinor >= 2))
931   {
932 #ifdef GL_EXT_convolution
933     if (myGlContext->CheckExtension ("GL_CONVOLUTION_1D_EXT"))
934       glDisable(GL_CONVOLUTION_1D_EXT);
935
936     if (myGlContext->CheckExtension ("GL_CONVOLUTION_2D_EXT"))
937       glDisable(GL_CONVOLUTION_2D_EXT);
938
939     if (myGlContext->CheckExtension ("GL_SEPARABLE_2D_EXT"))
940       glDisable(GL_SEPARABLE_2D_EXT);
941 #endif
942
943 #ifdef GL_EXT_histogram
944     if (myGlContext->CheckExtension ("GL_SEPARABLE_2D_EXT"))
945       glDisable(GL_HISTOGRAM_EXT);
946
947     if (myGlContext->CheckExtension ("GL_MINMAX_EXT"))
948       glDisable(GL_MINMAX_EXT);
949 #endif
950
951 #ifdef GL_EXT_texture3D
952     if (myGlContext->CheckExtension ("GL_TEXTURE_3D_EXT"))
953       glDisable(GL_TEXTURE_3D_EXT);
954 #endif
955   }
956 #endif
957 }