0027317: Some visualisation tests failed because of exceptions generated by FP signals.
[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
23 #include <Aspect_GraphicDeviceDefinitionError.hxx>
24 #include <Graphic3d_TransformUtils.hxx>
25 #include <TCollection_AsciiString.hxx>
26 #include <TCollection_ExtendedString.hxx>
27 #include <Graphic3d_GraphicDriver.hxx>
28
29 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,MMgt_TShared)
30
31 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
32   #include <EGL/egl.h>
33 #endif
34
35
36 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
37
38 namespace
39 {
40
41 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
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
124   // GLX_ARB_create_context
125 #ifndef GLX_CONTEXT_MAJOR_VERSION_ARB
126   #define GLX_CONTEXT_DEBUG_BIT_ARB         0x00000001
127   #define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
128   #define GLX_CONTEXT_MAJOR_VERSION_ARB     0x2091
129   #define GLX_CONTEXT_MINOR_VERSION_ARB     0x2092
130   #define GLX_CONTEXT_FLAGS_ARB             0x2094
131
132   // GLX_ARB_create_context_profile
133   #define GLX_CONTEXT_CORE_PROFILE_BIT_ARB  0x00000001
134   #define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
135   #define GLX_CONTEXT_PROFILE_MASK_ARB      0x9126
136 #endif
137
138   //! Dummy XError handler which just skips errors
139   static int xErrorDummyHandler (Display*     /*theDisplay*/,
140                                  XErrorEvent* /*theErrorEvent*/)
141   {
142     return 0;
143   }
144
145   //! Auxiliary method to format list.
146   static void addMsgToList (TCollection_ExtendedString&       theList,
147                             const TCollection_ExtendedString& theMsg)
148   {
149     if (!theList.IsEmpty())
150     {
151       theList += ", ";
152     }
153     theList += theMsg;
154   }
155 #endif
156
157 }
158
159 // =======================================================================
160 // function : OpenGl_Window
161 // purpose  :
162 // =======================================================================
163 OpenGl_Window::OpenGl_Window (const Handle(OpenGl_GraphicDriver)& theDriver,
164                               const Handle(Aspect_Window)&  thePlatformWindow,
165                               Aspect_RenderingContext       theGContext,
166                               const Handle(OpenGl_Caps)&    theCaps,
167                               const Handle(OpenGl_Context)& theShareCtx)
168 : myGlContext (new OpenGl_Context (theCaps)),
169   myOwnGContext (theGContext == 0),
170   myPlatformWindow (thePlatformWindow),
171   mySwapInterval (theCaps->swapInterval)
172 {
173   myPlatformWindow->Size (myWidth, myHeight);
174
175   Standard_Boolean isCoreProfile = Standard_False;
176
177 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
178   EGLDisplay anEglDisplay = (EGLDisplay )theDriver->getRawGlDisplay();
179   EGLContext anEglContext = (EGLContext )theDriver->getRawGlContext();
180   EGLConfig  anEglConfig  = (EGLConfig  )theDriver->getRawGlConfig();
181   if (anEglDisplay == EGL_NO_DISPLAY
182    || anEglContext == EGL_NO_CONTEXT
183    || anEglConfig == NULL)
184   {
185     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL does not provide compatible configurations!");
186     return;
187   }
188
189   EGLSurface anEglSurf = EGL_NO_SURFACE;
190   if (theGContext == (EGLContext )EGL_NO_CONTEXT)
191   {
192     // create new surface
193     anEglSurf = eglCreateWindowSurface (anEglDisplay,
194                                         anEglConfig,
195                                         (EGLNativeWindowType )myPlatformWindow->NativeHandle(),
196                                         NULL);
197     if (anEglSurf == EGL_NO_SURFACE)
198     {
199       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is unable to create surface for window!");
200       return;
201     }
202   }
203   else if (theGContext != anEglContext)
204   {
205     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is used in unsupported combination!");
206     return;
207   }
208   else
209   {
210     anEglSurf = eglGetCurrentSurface(EGL_DRAW);
211     if (anEglSurf == EGL_NO_SURFACE)
212     {
213       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window, EGL is unable to retrieve current surface!");
214       return;
215     }
216   }
217
218   myGlContext->Init ((Aspect_Drawable )anEglSurf, (Aspect_Display )anEglDisplay, (Aspect_RenderingContext )anEglContext, isCoreProfile);
219 #elif defined(_WIN32)
220   (void )theDriver;
221   HWND  aWindow   = (HWND )myPlatformWindow->NativeHandle();
222   HDC   aWindowDC = GetDC (aWindow);
223   HGLRC aGContext = (HGLRC )theGContext;
224
225   PIXELFORMATDESCRIPTOR aPixelFrmt;
226   memset (&aPixelFrmt, 0, sizeof(aPixelFrmt));
227   aPixelFrmt.nSize        = sizeof(PIXELFORMATDESCRIPTOR);
228   aPixelFrmt.nVersion     = 1;
229   aPixelFrmt.dwFlags      = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
230   aPixelFrmt.iPixelType   = PFD_TYPE_RGBA;
231   aPixelFrmt.cColorBits   = 24;
232   aPixelFrmt.cDepthBits   = 24;
233   aPixelFrmt.cStencilBits = 8;
234   aPixelFrmt.iLayerType   = PFD_MAIN_PLANE;
235   if (theCaps->contextStereo)
236   {
237     aPixelFrmt.dwFlags |= PFD_STEREO;
238   }
239
240   int aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
241
242   // in case of failure try without stereo if any
243   const Standard_Boolean hasStereo = aPixelFrmtId != 0 && theCaps->contextStereo;
244   if (aPixelFrmtId == 0 && theCaps->contextStereo)
245   {
246     TCollection_ExtendedString aMsg ("OpenGl_Window::CreateWindow: "
247                                      "ChoosePixelFormat is unable to find stereo supported pixel format. "
248                                      "Choosing similar non stereo format.");
249     myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
250                               GL_DEBUG_TYPE_OTHER,
251                               0, GL_DEBUG_SEVERITY_HIGH, aMsg);
252
253     aPixelFrmt.dwFlags &= ~PFD_STEREO;
254     aPixelFrmtId = ChoosePixelFormat (aWindowDC, &aPixelFrmt);
255   }
256
257   if (aPixelFrmtId == 0)
258   {
259     ReleaseDC (aWindow, aWindowDC);
260
261     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
262     aMsg += (int )GetLastError();
263     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
264     return;
265   }
266
267   DescribePixelFormat (aWindowDC, aPixelFrmtId, sizeof(aPixelFrmt), &aPixelFrmt);
268
269   HGLRC aSlaveCtx = !theShareCtx.IsNull() ? (HGLRC )theShareCtx->myGContext : NULL;
270   if (aGContext == NULL)
271   {
272     // create temporary context to retrieve advanced context creation procedures
273     HMODULE aModule = GetModuleHandleW(NULL);
274     WNDCLASSW aClass; memset (&aClass, 0, sizeof(aClass));
275     aClass.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
276     aClass.lpfnWndProc   = wndProcDummy;
277     aClass.hInstance     = aModule;
278     aClass.lpszClassName = L"OpenGl_WindowTmp";
279     HWND  aWinTmp     = NULL;
280     HDC   aDevCtxTmp  = NULL;
281     HGLRC aRendCtxTmp = NULL;
282     if ((!theCaps->contextDebug && !theCaps->contextNoAccel && theCaps->contextCompatible)
283      || RegisterClassW (&aClass) == 0)
284     {
285       aClass.lpszClassName = NULL;
286     }
287     if (aClass.lpszClassName != NULL)
288     {
289       DWORD anExStyle = WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE;
290     #if (_WIN32_WINNT >= 0x0500)
291       anExStyle |= WS_EX_NOACTIVATE;
292     #endif
293       aWinTmp = CreateWindowExW(anExStyle,
294                                 aClass.lpszClassName, L"OpenGl_WindowTmp",
295                                 WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_DISABLED,
296                                 2, 2, 4, 4,
297                                 NULL, NULL, aModule, NULL);
298     }
299     if (aWinTmp != NULL)
300     {
301       aDevCtxTmp = GetDC (aWinTmp);
302       SetPixelFormat (aDevCtxTmp, aPixelFrmtId, &aPixelFrmt);
303       aRendCtxTmp = wglCreateContext (aDevCtxTmp);
304     }
305
306     typedef BOOL (WINAPI *wglChoosePixelFormatARB_t)(HDC           theDevCtx,
307                                                      const int*    theIntAttribs,
308                                                      const float*  theFloatAttribs,
309                                                      unsigned int  theMaxFormats,
310                                                      int*          theFormatsOut,
311                                                      unsigned int* theNumFormatsOut);
312     typedef HGLRC (WINAPI *wglCreateContextAttribsARB_t)(HDC        theDevCtx,
313                                                          HGLRC      theShareContext,
314                                                          const int* theAttribs);
315     wglChoosePixelFormatARB_t    aChoosePixProc = NULL;
316     wglCreateContextAttribsARB_t aCreateCtxProc = NULL;
317     if (aRendCtxTmp != NULL)
318     {
319       wglMakeCurrent (aDevCtxTmp, aRendCtxTmp);
320
321       typedef const char* (WINAPI *wglGetExtensionsStringARB_t)(HDC theDeviceContext);
322       wglGetExtensionsStringARB_t aGetExtensions = (wglGetExtensionsStringARB_t  )wglGetProcAddress ("wglGetExtensionsStringARB");
323       const char* aWglExts = (aGetExtensions != NULL) ? aGetExtensions (wglGetCurrentDC()) : NULL;
324       if (OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_pixel_format"))
325       {
326         aChoosePixProc = (wglChoosePixelFormatARB_t    )wglGetProcAddress ("wglChoosePixelFormatARB");
327       }
328       if (OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_create_context_profile"))
329       {
330         aCreateCtxProc = (wglCreateContextAttribsARB_t )wglGetProcAddress ("wglCreateContextAttribsARB");
331       }
332     }
333
334     // choose extended pixel format
335     if (aChoosePixProc != NULL)
336     {
337       const int aPixAttribs[] =
338       {
339         WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
340         WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
341         WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
342         WGL_STEREO_ARB,         hasStereo ? GL_TRUE : GL_FALSE,
343         WGL_PIXEL_TYPE_ARB,     WGL_TYPE_RGBA_ARB,
344         //WGL_SAMPLE_BUFFERS_ARB, 1,
345         //WGL_SAMPLES_ARB,        8,
346         WGL_COLOR_BITS_ARB,     24,
347         WGL_DEPTH_BITS_ARB,     24,
348         WGL_STENCIL_BITS_ARB,   8,
349         WGL_ACCELERATION_ARB,   theCaps->contextNoAccel ? WGL_NO_ACCELERATION_ARB : WGL_FULL_ACCELERATION_ARB,
350         0, 0,
351       };
352       unsigned int aFrmtsNb = 0;
353       aChoosePixProc (aWindowDC, aPixAttribs, NULL, 1, &aPixelFrmtId, &aFrmtsNb);
354     }
355
356     // setup pixel format - may be set only once per window
357     if (!SetPixelFormat (aWindowDC, aPixelFrmtId, &aPixelFrmt))
358     {
359       ReleaseDC (aWindow, aWindowDC);
360
361       TCollection_AsciiString aMsg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
362       aMsg += (int )GetLastError();
363       Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
364       return;
365     }
366
367     // create GL context with extra options
368     if (aCreateCtxProc != NULL)
369     {
370       if (!theCaps->contextCompatible)
371       {
372         int aCoreCtxAttribs[] =
373         {
374           WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
375           WGL_CONTEXT_MINOR_VERSION_ARB, 2,
376           WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
377           WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
378           0, 0
379         };
380
381         // Try to create the core profile of highest OpenGL version supported by OCCT
382         // (this will be done automatically by some drivers when requesting 3.2,
383         //  but some will not (e.g. AMD Catalyst) since WGL_ARB_create_context_profile specification allows both implementations).
384         for (int aLowVer4 = 5; aLowVer4 >= 0 && aGContext == NULL; --aLowVer4)
385         {
386           aCoreCtxAttribs[1] = 4;
387           aCoreCtxAttribs[3] = aLowVer4;
388           aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCoreCtxAttribs);
389         }
390         for (int aLowVer3 = 3; aLowVer3 >= 2 && aGContext == NULL; --aLowVer3)
391         {
392           aCoreCtxAttribs[1] = 3;
393           aCoreCtxAttribs[3] = aLowVer3;
394           aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCoreCtxAttribs);
395         }
396         isCoreProfile = aGContext != NULL;
397       }
398
399       if (aGContext == NULL)
400       {
401         int aCtxAttribs[] =
402         {
403           // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified
404           // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB.
405           //WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
406           WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
407           0, 0
408         };
409         isCoreProfile = Standard_False;
410         aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCtxAttribs);
411
412         if (aGContext != NULL
413         && !theCaps->contextCompatible)
414         {
415           TCollection_ExtendedString aMsg("OpenGl_Window::CreateWindow: core profile creation failed.");
416           myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
417         }
418       }
419
420       if (aGContext != NULL)
421       {
422         aSlaveCtx = NULL;
423       }
424     }
425
426     if (aRendCtxTmp != NULL)
427     {
428       wglDeleteContext (aRendCtxTmp);
429     }
430     if (aDevCtxTmp != NULL)
431     {
432       ReleaseDC (aWinTmp, aDevCtxTmp);
433     }
434     if (aWinTmp != NULL)
435     {
436       DestroyWindow (aWinTmp);
437     }
438     if (aClass.lpszClassName != NULL)
439     {
440       UnregisterClassW (aClass.lpszClassName, aModule);
441     }
442
443     if (aGContext == NULL)
444     {
445       // create context using obsolete functionality
446       aGContext = wglCreateContext (aWindowDC);
447     }
448     if (aGContext == NULL)
449     {
450       ReleaseDC (aWindow, aWindowDC);
451
452       TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglCreateContext failed. Error code: ");
453       aMsg += (int )GetLastError();
454       Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
455       return;
456     }
457   }
458
459   // all GL context within one OpenGl_GraphicDriver should be shared!
460   if (aSlaveCtx != NULL && wglShareLists (aSlaveCtx, aGContext) != TRUE)
461   {
462     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglShareLists failed. Error code: ");
463     aMsg += (int )GetLastError();
464     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
465     return;
466   }
467
468   myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext, isCoreProfile);
469 #else
470   Window     aWindow   = (Window )myPlatformWindow->NativeHandle();
471   Display*   aDisp     = theDriver->GetDisplayConnection()->GetDisplay();
472   GLXContext aGContext = (GLXContext )theGContext;
473   GLXContext aSlaveCtx = !theShareCtx.IsNull() ? (GLXContext )theShareCtx->myGContext : NULL;
474
475   XWindowAttributes aWinAttribs;
476   XGetWindowAttributes (aDisp, aWindow, &aWinAttribs);
477   XVisualInfo aVisInfo;
478   aVisInfo.visualid = aWinAttribs.visual->visualid;
479   aVisInfo.screen   = DefaultScreen (aDisp);
480   int aNbItems;
481   XVisualInfo* aVis = XGetVisualInfo (aDisp, VisualIDMask | VisualScreenMask, &aVisInfo, &aNbItems);
482   int isGl = 0;
483   if (aVis == NULL)
484   {
485     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: XGetVisualInfo is unable to choose needed configuration in existing OpenGL context. ");
486     return;
487   }
488   else if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0 || !isGl)
489   {
490     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: window Visual does not support GL rendering!");
491     return;
492   }
493
494   // create new context
495   GLXFBConfig anFBConfig = myPlatformWindow->NativeFBConfig();
496   const char* aGlxExts   = glXQueryExtensionsString (aDisp, aVisInfo.screen);
497   if (myOwnGContext
498    && anFBConfig != NULL
499    && OpenGl_Context::CheckExtension (aGlxExts, "GLX_ARB_create_context_profile"))
500   {
501     // Replace default XError handler to ignore errors.
502     // Warning - this is global for all threads!
503     typedef int (*xerrorhandler_t)(Display* , XErrorEvent* );
504     xerrorhandler_t anOldHandler = XSetErrorHandler(xErrorDummyHandler);
505
506     typedef GLXContext (*glXCreateContextAttribsARB_t)(Display* dpy, GLXFBConfig config,
507                                                        GLXContext share_context, Bool direct,
508                                                        const int* attrib_list);
509     glXCreateContextAttribsARB_t aCreateCtxProc = (glXCreateContextAttribsARB_t )glXGetProcAddress((const GLubyte* )"glXCreateContextAttribsARB");
510     if (!theCaps->contextCompatible)
511     {
512       int aCoreCtxAttribs[] =
513       {
514         GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
515         GLX_CONTEXT_MINOR_VERSION_ARB, 2,
516         GLX_CONTEXT_PROFILE_MASK_ARB,  GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
517         GLX_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? GLX_CONTEXT_DEBUG_BIT_ARB : 0,
518         0, 0
519       };
520
521       // try to create the core profile of highest OpenGL version supported by OCCT
522       for (int aLowVer4 = 5; aLowVer4 >= 0 && aGContext == NULL; --aLowVer4)
523       {
524         aCoreCtxAttribs[1] = 4;
525         aCoreCtxAttribs[3] = aLowVer4;
526         aGContext = aCreateCtxProc (aDisp, anFBConfig, aSlaveCtx, True, aCoreCtxAttribs);
527       }
528       for (int aLowVer3 = 3; aLowVer3 >= 2 && aGContext == NULL; --aLowVer3)
529       {
530         aCoreCtxAttribs[1] = 3;
531         aCoreCtxAttribs[3] = aLowVer3;
532         aGContext = aCreateCtxProc (aDisp, anFBConfig, aSlaveCtx, True, aCoreCtxAttribs);
533       }
534       isCoreProfile = aGContext != NULL;
535     }
536
537     if (aGContext == NULL)
538     {
539       int aCtxAttribs[] =
540       {
541         GLX_CONTEXT_FLAGS_ARB, theCaps->contextDebug ? GLX_CONTEXT_DEBUG_BIT_ARB : 0,
542         0, 0
543       };
544       isCoreProfile = Standard_False;
545       aGContext = aCreateCtxProc (aDisp, anFBConfig, aSlaveCtx, True, aCtxAttribs);
546
547       if (aGContext != NULL
548       && !theCaps->contextCompatible)
549       {
550         TCollection_ExtendedString aMsg("OpenGl_Window::CreateWindow: core profile creation failed.");
551         myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
552       }
553     }
554     XSetErrorHandler(anOldHandler);
555   }
556
557   if (myOwnGContext
558    && aGContext == NULL)
559   {
560     aGContext = glXCreateContext (aDisp, aVis, aSlaveCtx, GL_TRUE);
561     if (aGContext == NULL)
562     {
563       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXCreateContext failed.");
564       return;
565     }
566   }
567
568   // check Visual for OpenGl context's parameters compatibility
569   TCollection_ExtendedString aList;
570   int isDoubleBuffer = 0, isRGBA = 0, isStereo = 0;
571   int aDepthSize = 0, aStencilSize = 0;
572   glXGetConfig (aDisp, aVis, GLX_RGBA,         &isRGBA);
573   glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer);
574   glXGetConfig (aDisp, aVis, GLX_STEREO,       &isStereo);
575   glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE,   &aDepthSize);
576   glXGetConfig (aDisp, aVis, GLX_STENCIL_SIZE, &aStencilSize);
577   if (aDepthSize < 1)      addMsgToList (aList, "no depth buffer");
578   if (aStencilSize < 1)    addMsgToList (aList, "no stencil buffer");
579   if (isRGBA == 0)         addMsgToList (aList, "no RGBA color buffer");
580   if (isDoubleBuffer == 0) addMsgToList (aList, "no Double Buffer");
581   if (theCaps->contextStereo && isStereo == 0)
582   {
583     addMsgToList (aList, "no Quad Buffer");
584   }
585   else if (!theCaps->contextStereo && isStereo == 1)
586   {
587     addMsgToList (aList, "extra Quad Buffer");
588   }
589   if (!aList.IsEmpty())
590   {
591     TCollection_ExtendedString aMsg = TCollection_ExtendedString ("OpenGl_Window::CreateWindow: window Visual is incomplete: ") + aList;
592     myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
593                               GL_DEBUG_TYPE_OTHER,
594                               0, GL_DEBUG_SEVERITY_MEDIUM, aMsg);
595   }
596
597   myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )aDisp, (Aspect_RenderingContext )aGContext, isCoreProfile);
598 #endif
599   myGlContext->Share (theShareCtx);
600   myGlContext->SetSwapInterval (mySwapInterval);
601   Init();
602 }
603
604 // =======================================================================
605 // function : ~OpenGl_Window
606 // purpose  :
607 // =======================================================================
608 OpenGl_Window::~OpenGl_Window()
609 {
610   if (!myOwnGContext
611    ||  myGlContext.IsNull())
612   {
613     myGlContext.Nullify();
614     return;
615   }
616
617   // release "GL" context if it is owned by window
618   // Mesa implementation can fail to destroy GL context if it set for current thread.
619   // It should be safer to unset thread GL context before its destruction.
620 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
621   if ((EGLSurface )myGlContext->myWindow != EGL_NO_SURFACE)
622   {
623     eglDestroySurface ((EGLDisplay )myGlContext->myDisplay,
624                        (EGLSurface )myGlContext->myWindow);
625   }
626 #elif defined(_WIN32)
627   HWND  aWindow          = (HWND  )myGlContext->myWindow;
628   HDC   aWindowDC        = (HDC   )myGlContext->myWindowDC;
629   HGLRC aWindowGContext  = (HGLRC )myGlContext->myGContext;
630   HGLRC aThreadGContext  = wglGetCurrentContext();
631   myGlContext.Nullify();
632
633   if (aThreadGContext != NULL)
634   {
635     if (aThreadGContext == aWindowGContext)
636     {
637       wglMakeCurrent (NULL, NULL);
638     }
639
640     wglDeleteContext (aWindowGContext);
641   }
642   ReleaseDC (aWindow, aWindowDC);
643 #else
644   Display*    aDisplay        = (Display*    )myGlContext->myDisplay;
645   GLXContext  aWindowGContext = (GLXContext  )myGlContext->myGContext;
646   GLXContext  aThreadGContext = glXGetCurrentContext();
647   myGlContext.Nullify();
648
649   if (aDisplay != NULL)
650   {
651     if (aThreadGContext == aWindowGContext)
652     {
653       glXMakeCurrent (aDisplay, None, NULL);
654     }
655
656     // FSXXX sync necessary if non-direct rendering
657     glXWaitGL();
658     glXDestroyContext (aDisplay, aWindowGContext);
659   }
660 #endif
661 }
662
663 #endif // !__APPLE__
664
665 // =======================================================================
666 // function : Activate
667 // purpose  :
668 // =======================================================================
669 Standard_Boolean OpenGl_Window::Activate()
670 {
671   return myGlContext->MakeCurrent();
672 }
673
674 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
675
676 // =======================================================================
677 // function : Resize
678 // purpose  : call_subr_resize
679 // =======================================================================
680 void OpenGl_Window::Resize()
681 {
682 #if !defined(_WIN32) && !defined(HAVE_EGL) && !defined(__ANDROID__) && !defined(__QNX__)
683   Display* aDisp = (Display* )myGlContext->myDisplay;
684   if (aDisp == NULL)
685     return;
686 #endif
687
688   Standard_Integer aWidth  = 0;
689   Standard_Integer aHeight = 0;
690   myPlatformWindow->Size (aWidth, aHeight);
691
692   // If the size is not changed - do nothing
693   if ((myWidth == aWidth) && (myHeight == aHeight))
694     return;
695
696   myWidth  = aWidth;
697   myHeight = aHeight;
698
699 #if !defined(_WIN32) && !defined(HAVE_EGL) && !defined(__ANDROID__) && !defined(__QNX__)
700   XResizeWindow (aDisp, myGlContext->myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
701   XSync (aDisp, False);
702 #endif
703
704   Init();
705 }
706
707 // =======================================================================
708 // function : Init
709 // purpose  :
710 // =======================================================================
711 void OpenGl_Window::Init()
712 {
713   if (!Activate())
714     return;
715
716 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
717   eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_WIDTH,  &myWidth);
718   eglQuerySurface ((EGLDisplay )myGlContext->myDisplay, (EGLSurface )myGlContext->myWindow, EGL_HEIGHT, &myHeight);
719 #elif defined(_WIN32)
720   //
721 #else
722   Window aRootWin;
723   int aDummy;
724   unsigned int aDummyU;
725   unsigned int aNewWidth  = 0;
726   unsigned int aNewHeight = 0;
727   Display* aDisp = (Display* )myGlContext->myDisplay;
728   XGetGeometry (aDisp, myGlContext->myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
729   myWidth  = aNewWidth;
730   myHeight = aNewHeight;
731 #endif
732
733   glDisable (GL_DITHER);
734   glDisable (GL_SCISSOR_TEST);
735   glViewport (0, 0, myWidth, myHeight);
736 #if !defined(GL_ES_VERSION_2_0)
737   glDrawBuffer (GL_BACK);
738   if (myGlContext->core11 != NULL)
739   {
740     glMatrixMode (GL_MODELVIEW);
741   }
742 #endif
743 }
744
745 // =======================================================================
746 // function : SetSwapInterval
747 // purpose  :
748 // =======================================================================
749 void OpenGl_Window::SetSwapInterval()
750 {
751   if (mySwapInterval != myGlContext->caps->swapInterval)
752   {
753     mySwapInterval = myGlContext->caps->swapInterval;
754     myGlContext->SetSwapInterval (mySwapInterval);
755   }
756 }
757
758 #endif // !__APPLE__