0024171: Eliminate CLang compiler warning -Wreorder
[occt.git] / src / OpenGl / OpenGl_Window.cxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2012 OPEN CASCADE SAS
4 //
5 // The content of this file is subject to the Open CASCADE Technology Public
6 // License Version 6.5 (the "License"). You may not use the content of this file
7 // except in compliance with the License. Please obtain a copy of the License
8 // at http://www.opencascade.org and read it completely before using this file.
9 //
10 // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
11 // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
12 //
13 // The Original Code and all software distributed under the License is
14 // distributed on an "AS IS" basis, without warranty of any kind, and the
15 // Initial Developer hereby disclaims all such warranties, including without
16 // limitation, any warranties of merchantability, fitness for a particular
17 // purpose or non-infringement. Please see the License for the specific terms
18 // and conditions governing the rights and limitations under the License.
19
20 #include <OpenGl_GlCore11.hxx>
21
22 #include <InterfaceGraphic.hxx>
23
24 #include <OpenGl_Window.hxx>
25
26 #include <OpenGl_Context.hxx>
27 #include <OpenGl_Display.hxx>
28
29 #include <Aspect_GraphicDeviceDefinitionError.hxx>
30 #include <TCollection_AsciiString.hxx>
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(_WIN32)
42
43   // WGL_ARB_create_context_profile
44 #ifndef WGL_CONTEXT_MAJOR_VERSION_ARB
45   #define WGL_CONTEXT_MAJOR_VERSION_ARB           0x2091
46   #define WGL_CONTEXT_MINOR_VERSION_ARB           0x2092
47   #define WGL_CONTEXT_LAYER_PLANE_ARB             0x2093
48   #define WGL_CONTEXT_FLAGS_ARB                   0x2094
49   #define WGL_CONTEXT_PROFILE_MASK_ARB            0x9126
50
51   // WGL_CONTEXT_FLAGS bits
52   #define WGL_CONTEXT_DEBUG_BIT_ARB               0x0001
53   #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB  0x0002
54
55   // WGL_CONTEXT_PROFILE_MASK_ARB bits
56   #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB          0x00000001
57   #define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002
58 #endif // WGL_CONTEXT_MAJOR_VERSION_ARB
59
60   static LRESULT CALLBACK wndProcDummy (HWND theWin, UINT theMsg, WPARAM theParamW, LPARAM theParamL)
61   {
62     return DefWindowProcW (theWin, theMsg, theParamW, theParamL);
63   }
64
65   static int find_pixel_format (HDC                    theDevCtx,
66                                 PIXELFORMATDESCRIPTOR& thePixelFrmt,
67                                 const Standard_Boolean theIsDoubleBuff)
68   {
69     PIXELFORMATDESCRIPTOR aPixelFrmtTmp;
70     memset (&aPixelFrmtTmp, 0, sizeof (PIXELFORMATDESCRIPTOR));
71     aPixelFrmtTmp.nSize      = sizeof (PIXELFORMATDESCRIPTOR);
72     aPixelFrmtTmp.nVersion   = 1;
73     aPixelFrmtTmp.dwFlags    = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | (theIsDoubleBuff ? PFD_DOUBLEBUFFER : PFD_SUPPORT_GDI);
74     aPixelFrmtTmp.iPixelType = PFD_TYPE_RGBA;
75     aPixelFrmtTmp.iLayerType = PFD_MAIN_PLANE;
76
77     const int BUFF_BITS_STENCIL[] = {  8,  1     };
78     const int BUFF_BITS_COLOR[]   = { 32, 24     };
79     const int BUFF_BITS_DEPTH[]   = { 32, 24, 16 };
80
81     int aGoodBits[] = { 0, 0, 0 };
82     int aPixelFrmtIdLast = 0;
83     int aPixelFrmtIdGood = 0;
84     Standard_Size aStencilIter = 0, aColorIter = 0, aDepthIter = 0;
85     for (aStencilIter = 0; aStencilIter < sizeof(BUFF_BITS_STENCIL) / sizeof(int); ++aStencilIter)
86     {
87       aPixelFrmtTmp.cStencilBits = (BYTE)(BUFF_BITS_STENCIL[aStencilIter]);
88       for (aDepthIter = 0; aDepthIter < sizeof(BUFF_BITS_DEPTH) / sizeof(int); ++aDepthIter)
89       {
90         aPixelFrmtTmp.cDepthBits = (BYTE)(BUFF_BITS_DEPTH[aDepthIter]);
91         aPixelFrmtIdGood = 0;
92         for (aColorIter = 0; aColorIter < sizeof(BUFF_BITS_COLOR) / sizeof(int); ++aColorIter)
93         {
94           aPixelFrmtTmp.cColorBits = (BYTE)(BUFF_BITS_COLOR[aColorIter]);
95           aPixelFrmtIdLast = ChoosePixelFormat (theDevCtx, &aPixelFrmtTmp);
96           if (aPixelFrmtIdLast == 0)
97           {
98             continue;
99           }
100
101           thePixelFrmt.cDepthBits   = 0;
102           thePixelFrmt.cColorBits   = 0;
103           thePixelFrmt.cStencilBits = 0;
104           DescribePixelFormat (theDevCtx, aPixelFrmtIdLast, sizeof(PIXELFORMATDESCRIPTOR), &thePixelFrmt);
105           if (thePixelFrmt.cColorBits   >= BUFF_BITS_COLOR[aColorIter]
106            && thePixelFrmt.cDepthBits   >= BUFF_BITS_DEPTH[aDepthIter]
107            && thePixelFrmt.cStencilBits >= BUFF_BITS_STENCIL[aStencilIter])
108           {
109             break;
110           }
111           if (thePixelFrmt.cColorBits > aGoodBits[0])
112           {
113             aGoodBits[0] = thePixelFrmt.cColorBits;
114             aGoodBits[1] = thePixelFrmt.cDepthBits;
115             aGoodBits[2] = thePixelFrmt.cStencilBits;
116             aPixelFrmtIdGood = aPixelFrmtIdLast;
117           }
118           else if (thePixelFrmt.cColorBits == aGoodBits[0])
119           {
120             if (thePixelFrmt.cDepthBits > aGoodBits[1])
121             {
122               aGoodBits[1] = thePixelFrmt.cDepthBits;
123               aGoodBits[2] = thePixelFrmt.cStencilBits;
124               aPixelFrmtIdGood = aPixelFrmtIdLast;
125             }
126             else if (thePixelFrmt.cDepthBits == aGoodBits[1])
127             {
128               if(thePixelFrmt.cStencilBits > aGoodBits[2])
129               {
130                 aGoodBits[2] = thePixelFrmt.cStencilBits;
131                 aPixelFrmtIdGood = aPixelFrmtIdLast;
132               }
133             }
134           }
135         }
136         if (aColorIter < sizeof(BUFF_BITS_COLOR) / sizeof(int))
137         {
138           break;
139         }
140       }
141       if (aDepthIter < sizeof(BUFF_BITS_DEPTH) / sizeof(int))
142       {
143         break;
144       }
145     }
146
147     return (aPixelFrmtIdLast == 0) ? aPixelFrmtIdGood : aPixelFrmtIdLast;
148   }
149 #else
150   static Bool WaitForNotify (Display* theDisp, XEvent* theEv, char* theArg)
151   {
152     return (theEv->type == MapNotify) && (theEv->xmap.window == (Window )theArg);
153   }
154 #endif
155
156 };
157
158 // =======================================================================
159 // function : OpenGl_Window
160 // purpose  :
161 // =======================================================================
162 OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
163                               const CALL_DEF_WINDOW&        theCWindow,
164                               Aspect_RenderingContext       theGContext,
165                               const Handle(OpenGl_Caps)&    theCaps,
166                               const Handle(OpenGl_Context)& theShareCtx)
167 : myDisplay (theDisplay),
168   myGlContext (new OpenGl_Context (theCaps)),
169   myOwnGContext (theGContext == 0),
170 #if defined(_WIN32)
171   mySysPalInUse (FALSE),
172 #endif
173   myWidth ((Standard_Integer )theCWindow.dx),
174   myHeight ((Standard_Integer )theCWindow.dy),
175   myBgColor (THE_DEFAULT_BG_COLOR),
176   myDither (theDisplay->Dither()),
177   myBackDither (theDisplay->BackDither())
178 {
179   myBgColor.rgb[0] = theCWindow.Background.r;
180   myBgColor.rgb[1] = theCWindow.Background.g;
181   myBgColor.rgb[2] = theCWindow.Background.b;
182
183 #if defined(_WIN32)
184   HWND  aWindow   = (HWND )theCWindow.XWindow;
185   HDC   aWindowDC = GetDC (aWindow);
186   HGLRC aGContext = (HGLRC )theGContext;
187
188   PIXELFORMATDESCRIPTOR aPixelFrmt;
189   const int aPixelFrmtId = find_pixel_format (aWindowDC, aPixelFrmt, myDisplay->DBuffer());
190   if (aPixelFrmtId == 0)
191   {
192     ReleaseDC (aWindow, aWindowDC);
193
194     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
195     aMsg += (int )GetLastError();
196     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
197     return;
198   }
199
200   if (aPixelFrmt.dwFlags & PFD_NEED_PALETTE)
201   {
202     WINDOW_DATA* aWndData = (WINDOW_DATA* )GetWindowLongPtr (aWindow, GWLP_USERDATA);
203
204     mySysPalInUse = (aPixelFrmt.dwFlags & PFD_NEED_SYSTEM_PALETTE) ? TRUE : FALSE;
205     InterfaceGraphic_RealizePalette (aWindowDC, aWndData->hPal, FALSE, mySysPalInUse);
206   }
207
208   if (myDither)
209   {
210     myDither = (aPixelFrmt.cColorBits <= 8);
211   }
212
213   if (myBackDither)
214   {
215     myBackDither = (aPixelFrmt.cColorBits <= 8);
216   }
217
218   if (!SetPixelFormat (aWindowDC, aPixelFrmtId, &aPixelFrmt))
219   {
220     ReleaseDC (aWindow, aWindowDC);
221
222     TCollection_AsciiString aMsg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
223     aMsg += (int )GetLastError();
224     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
225     return;
226   }
227
228   HGLRC aSlaveCtx = !theShareCtx.IsNull() ? (HGLRC )theShareCtx->myGContext : NULL;
229   if (aGContext == NULL)
230   {
231     // create temporary context to retrieve advanced context creation procedures
232     HMODULE aModule = GetModuleHandleW(NULL);
233     WNDCLASSW aClass; memset (&aClass, 0, sizeof(aClass));
234     aClass.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
235     aClass.lpfnWndProc   = wndProcDummy;
236     aClass.hInstance     = aModule;
237     aClass.lpszClassName = L"OpenGl_WindowTmp";
238     HWND  aWinTmp     = NULL;
239     HDC   aDevCtxTmp  = NULL;
240     HGLRC aRendCtxTmp = NULL;
241     if (!theCaps->contextDebug
242      || RegisterClassW (&aClass) == 0)
243     {
244       aClass.lpszClassName = NULL;
245     }
246     if (aClass.lpszClassName != NULL)
247     {
248       aWinTmp = CreateWindowExW(WS_EX_TOOLWINDOW | WS_EX_WINDOWEDGE | WS_EX_NOACTIVATE,
249                                 aClass.lpszClassName, L"OpenGl_WindowTmp",
250                                 WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_DISABLED,
251                                 2, 2, 4, 4,
252                                 NULL, NULL, aModule, NULL);
253     }
254     if (aWinTmp != NULL)
255     {
256       aDevCtxTmp = GetDC (aWinTmp);
257       SetPixelFormat (aDevCtxTmp, aPixelFrmtId, &aPixelFrmt);
258       aRendCtxTmp = wglCreateContext (aDevCtxTmp);
259     }
260     if (aRendCtxTmp != NULL)
261     {
262       wglMakeCurrent (aDevCtxTmp, aRendCtxTmp);
263
264       typedef const char* (WINAPI *wglGetExtensionsStringARB_t)(HDC theDeviceContext);
265       typedef HGLRC (WINAPI *wglCreateContextAttribsARB_t)(HDC        theDevCtx,
266                                                            HGLRC      theShareContext,
267                                                            const int* theAttribs);
268       wglGetExtensionsStringARB_t  aGetExtensions = (wglGetExtensionsStringARB_t  )wglGetProcAddress ("wglGetExtensionsStringARB");
269       wglCreateContextAttribsARB_t aCreateCtxProc = (wglCreateContextAttribsARB_t )wglGetProcAddress ("wglCreateContextAttribsARB");
270       const char* aWglExts = aGetExtensions (wglGetCurrentDC());
271       if (aCreateCtxProc != NULL
272        && OpenGl_Context::CheckExtension (aWglExts, "WGL_ARB_create_context_profile"))
273       {
274         // Beware! NVIDIA drivers reject context creation when WGL_CONTEXT_PROFILE_MASK_ARB are specified
275         // but not WGL_CONTEXT_MAJOR_VERSION_ARB/WGL_CONTEXT_MINOR_VERSION_ARB.
276         int aCtxAttribs[] =
277         {
278           //WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
279           //WGL_CONTEXT_MINOR_VERSION_ARB, 2,
280           //WGL_CONTEXT_PROFILE_MASK_ARB,  WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, //WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
281           WGL_CONTEXT_FLAGS_ARB,         theCaps->contextDebug ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
282           0, 0
283         };
284
285         aGContext = aCreateCtxProc (aWindowDC, aSlaveCtx, aCtxAttribs);
286         if (aGContext != NULL)
287         {
288           aSlaveCtx = NULL;
289         }
290       }
291     }
292
293     if (aRendCtxTmp != NULL)
294     {
295       wglDeleteContext (aRendCtxTmp);
296     }
297     if (aDevCtxTmp != NULL)
298     {
299       ReleaseDC (aWinTmp, aDevCtxTmp);
300     }
301     if (aWinTmp != NULL)
302     {
303       DestroyWindow (aWinTmp);
304     }
305     if (aClass.lpszClassName != NULL)
306     {
307       UnregisterClassW (aClass.lpszClassName, aModule);
308     }
309
310     if (aGContext == NULL)
311     {
312       aGContext = wglCreateContext (aWindowDC);
313     }
314     if (aGContext == NULL)
315     {
316       ReleaseDC (aWindow, aWindowDC);
317
318       TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglCreateContext failed. Error code: ");
319       aMsg += (int )GetLastError();
320       Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
321       return;
322     }
323   }
324
325   // all GL context within one OpenGl_GraphicDriver should be shared!
326   if (aSlaveCtx != NULL && wglShareLists (aSlaveCtx, aGContext) != TRUE)
327   {
328     TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglShareLists failed. Error code: ");
329     aMsg += (int )GetLastError();
330     Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
331     return;
332   }
333
334   myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext);
335 #else
336   WINDOW aParent = (WINDOW )theCWindow.XWindow;
337   WINDOW aWindow = 0;
338   DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
339   GLXContext aGContext = (GLXContext )theGContext;
340
341   XWindowAttributes wattr;
342   XGetWindowAttributes (aDisp, aParent, &wattr);
343   const int scr = DefaultScreen (aDisp);
344
345   XVisualInfo* aVis = NULL;
346   {
347     unsigned long aVisInfoMask = VisualIDMask | VisualScreenMask;
348     XVisualInfo aVisInfo;
349     aVisInfo.visualid = wattr.visual->visualid;
350     aVisInfo.screen   = scr;
351     int aNbItems;
352     aVis = XGetVisualInfo (aDisp, aVisInfoMask, &aVisInfo, &aNbItems);
353   }
354
355   if (!myOwnGContext)
356   {
357     if (aVis != NULL)
358     {
359       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: XGetVisualInfo failed.");
360       return;
361     }
362
363     aWindow = aParent;
364   }
365   else
366   {
367   #if defined(__linux) || defined(Linux) || defined(__APPLE__)
368     if (aVis != NULL)
369     {
370       // check Visual for OpenGl context's parameters compability
371       int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, aDepthSize = 0, aStencilSize = 0;
372
373       if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0)
374         isGl = 0;
375
376       if (glXGetConfig (aDisp, aVis, GLX_RGBA, &isRGBA) != 0)
377         isRGBA = 0;
378
379       if (glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer) != 0)
380         isDoubleBuffer = 0;
381
382       if (glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE, &aDepthSize) != 0)
383         aDepthSize = 0;
384
385       if (glXGetConfig (aDisp, aVis, GLX_STENCIL_SIZE, &aStencilSize) != 0)
386         aStencilSize = 0;
387
388       if (!isGl || !aDepthSize || !isRGBA  || (isDoubleBuffer ? 1 : 0) != (myDisplay->DBuffer()? 1 : 0))
389       {
390         XFree (aVis);
391         aVis = NULL;
392       }
393     }
394   #endif
395
396     if (aVis == NULL)
397     {
398       int anIter = 0;
399       int anAttribs[13];
400       anAttribs[anIter++] = GLX_RGBA;
401
402       anAttribs[anIter++] = GLX_DEPTH_SIZE;
403       anAttribs[anIter++] = 1;
404
405       anAttribs[anIter++] = GLX_STENCIL_SIZE;
406       anAttribs[anIter++] = 1;
407
408       anAttribs[anIter++] = GLX_RED_SIZE;
409       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
410
411       anAttribs[anIter++] = GLX_GREEN_SIZE;
412       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
413
414       anAttribs[anIter++] = GLX_BLUE_SIZE;
415       anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
416
417       if (myDisplay->DBuffer())
418         anAttribs[anIter++] = GLX_DOUBLEBUFFER;
419
420       anAttribs[anIter++] = None;
421
422       aVis = glXChooseVisual (aDisp, scr, anAttribs);
423       if (aVis == NULL)
424       {
425         Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXChooseVisual failed.");
426         return;
427       }
428     }
429
430     if (!theShareCtx.IsNull())
431     {
432       // ctx est une copie du previous
433       aGContext = glXCreateContext (aDisp, aVis, (GLXContext )theShareCtx->myGContext, GL_TRUE);
434     }
435     else
436     {
437       aGContext = glXCreateContext (aDisp, aVis, NULL, GL_TRUE);
438     }
439
440     if (!aGContext)
441     {
442       Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXCreateContext failed.");
443       return;
444     }
445
446     Colormap cmap = XCreateColormap (aDisp, aParent, aVis->visual, AllocNone);
447
448     XColor color;
449     color.red   = (unsigned short) (myBgColor.rgb[0] * 0xFFFF);
450     color.green = (unsigned short) (myBgColor.rgb[1] * 0xFFFF);
451     color.blue  = (unsigned short) (myBgColor.rgb[2] * 0xFFFF);
452     color.flags = DoRed | DoGreen | DoBlue;
453     XAllocColor (aDisp, cmap, &color);
454
455     XSetWindowAttributes cwa;
456     cwa.colormap         = cmap;
457     cwa.event_mask       = StructureNotifyMask;
458     cwa.border_pixel     = color.pixel;
459     cwa.background_pixel = color.pixel;
460
461     if (aVis->visualid == wattr.visual->visualid)
462     {
463       aWindow = aParent;
464     }
465     else
466     {
467       unsigned long mask = CWBackPixel | CWColormap | CWBorderPixel | CWEventMask;
468       aWindow = XCreateWindow (aDisp, aParent, 0, 0, myWidth, myHeight, 0/*bw*/, aVis->depth, InputOutput, aVis->visual, mask, &cwa);
469     }
470
471     XSetWindowBackground (aDisp, aWindow, cwa.background_pixel);
472     XClearWindow (aDisp, aWindow);
473
474     if (aWindow != aParent)
475     {
476       XEvent anEvent;
477       XMapWindow (aDisp, aWindow);
478       XIfEvent (aDisp, &anEvent, WaitForNotify, (char* )aWindow);
479     }
480   }
481
482   /*
483   * Le BackDitherProp est utilise pour le clear du background
484   * Pour eviter une difference de couleurs avec la couleur choisie
485   * par l'application (XWindow) il faut desactiver le dithering
486   * au dessus de 8 plans.
487   *
488   * Pour le DitherProp:
489   * On cherchera a activer le Dithering que si le Visual a au moins
490   * 8 plans pour le GLX_RED_SIZE. Le test est plus sur car on peut
491   * avoir une profondeur superieure a 12 mais avoir besoin du dithering.
492   * (Carte Impact avec GLX_RED_SIZE a 5 par exemple)
493   */
494
495   int aValue;
496   glXGetConfig (aDisp, aVis, GLX_RED_SIZE, &aValue);
497
498   if (myDither)
499     myDither = (aValue < 8);
500
501   if (myBackDither)
502     myBackDither = (aVis->depth <= 8);
503
504   XFree ((char* )aVis);
505
506   myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )myDisplay->GetDisplay(), (Aspect_RenderingContext )aGContext);
507 #endif
508   myGlContext->Share (theShareCtx);
509
510   Init();
511 }
512
513 // =======================================================================
514 // function : ~OpenGl_Window
515 // purpose  :
516 // =======================================================================
517 OpenGl_Window::~OpenGl_Window()
518 {
519 #if defined(_WIN32)
520   HWND  aWindow   = (HWND  )myGlContext->myWindow;
521   HDC   aWindowDC = (HDC   )myGlContext->myWindowDC;
522   HGLRC aGContext = (HGLRC )myGlContext->myGContext;
523   myGlContext.Nullify();
524
525   if (myOwnGContext)
526   {
527     if (wglGetCurrentContext() != NULL)
528     {
529       wglDeleteContext (aGContext);
530     }
531     ReleaseDC (aWindow, aWindowDC);
532   }
533 #else
534   GLXDrawable aWindow   = (GLXDrawable )myGlContext->myWindow;
535   Display*    aDisplay  = (Display*    )myGlContext->myDisplay;
536   GLXContext  aGContext = (GLXContext  )myGlContext->myGContext;
537   myGlContext.Nullify();
538
539   if (aDisplay != NULL && myOwnGContext)
540   {
541     // FSXXX sync necessary if non-direct rendering
542     glXWaitGL();
543     glXDestroyContext (aDisplay, aGContext);
544   }
545 #endif
546 }
547
548 #endif // !__APPLE__
549
550 // =======================================================================
551 // function : Activate
552 // purpose  :
553 // =======================================================================
554 Standard_Boolean OpenGl_Window::Activate()
555 {
556   return myGlContext->MakeCurrent();
557 }
558
559 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
560
561 // =======================================================================
562 // function : Resize
563 // purpose  : call_subr_resize
564 // =======================================================================
565 void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
566 {
567   DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
568   if (aDisp == NULL)
569     return;
570
571   // If the size is not changed - do nothing
572   if ((myWidth == theCWindow.dx) && (myHeight == theCWindow.dy))
573     return;
574
575   myWidth  = (Standard_Integer )theCWindow.dx;
576   myHeight = (Standard_Integer )theCWindow.dy;
577
578 #if !defined(_WIN32)
579   XResizeWindow (aDisp, myGlContext->myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
580   XSync (aDisp, False);
581 #endif
582
583   Init();
584 }
585
586 #endif // !__APPLE__
587
588 // =======================================================================
589 // function : ReadDepths
590 // purpose  : TelReadDepths
591 // =======================================================================
592 void OpenGl_Window::ReadDepths (const Standard_Integer theX,     const Standard_Integer theY,
593                                 const Standard_Integer theWidth, const Standard_Integer theHeight,
594                                 float* theDepths)
595 {
596   if (theDepths == NULL || !Activate())
597     return;
598
599   glMatrixMode (GL_PROJECTION);
600   glLoadIdentity();
601   gluOrtho2D (0.0, (GLdouble )myWidth, 0.0, (GLdouble )myHeight);
602   glMatrixMode (GL_MODELVIEW);
603   glLoadIdentity();
604
605   glRasterPos2i (theX, theY);
606   DisableFeatures();
607   glReadPixels (theX, theY, theWidth, theHeight, GL_DEPTH_COMPONENT, GL_FLOAT, theDepths);
608   EnableFeatures();
609 }
610
611 // =======================================================================
612 // function : SetBackgroundColor
613 // purpose  : call_subr_set_background
614 // =======================================================================
615 void OpenGl_Window::SetBackgroundColor (const Standard_ShortReal theR,
616                                         const Standard_ShortReal theG,
617                                         const Standard_ShortReal theB)
618 {
619   myBgColor.rgb[0] = theR;
620   myBgColor.rgb[1] = theG;
621   myBgColor.rgb[2] = theB;
622 }
623
624 #if !defined(__APPLE__) || defined(MACOSX_USE_GLX)
625
626 // =======================================================================
627 // function : Init
628 // purpose  :
629 // =======================================================================
630 void OpenGl_Window::Init()
631 {
632   if (!Activate())
633     return;
634
635 #if defined(_WIN32)
636   RECT cr;
637   GetClientRect ((HWND )myGlContext->myWindow, &cr);
638   myWidth  = cr.right - cr.left;
639   myHeight = cr.bottom - cr.top;
640 #else
641   Window aRootWin;
642   int aDummy;
643   unsigned int aDummyU;
644   unsigned int aNewWidth  = 0;
645   unsigned int aNewHeight = 0;
646   DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
647   XGetGeometry (aDisp, myGlContext->myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
648   myWidth  = aNewWidth;
649   myHeight = aNewHeight;
650 #endif
651
652   glMatrixMode (GL_MODELVIEW);
653   glViewport (0, 0, myWidth, myHeight);
654
655   glDisable (GL_SCISSOR_TEST);
656   glDrawBuffer (GL_BACK);
657 }
658
659 #endif // !__APPLE__
660
661 // =======================================================================
662 // function : EnablePolygonOffset
663 // purpose  : call_subr_enable_polygon_offset
664 // =======================================================================
665 void OpenGl_Window::EnablePolygonOffset() const
666 {
667   Standard_ShortReal aFactor, aUnits;
668   myDisplay->PolygonOffset (aFactor, aUnits);
669   glPolygonOffset (aFactor, aUnits);
670   glEnable (GL_POLYGON_OFFSET_FILL);
671 }
672
673 // =======================================================================
674 // function : DisablePolygonOffset
675 // purpose  : call_subr_disable_polygon_offset
676 // =======================================================================
677 void OpenGl_Window::DisablePolygonOffset() const
678 {
679   glDisable (GL_POLYGON_OFFSET_FILL);
680 }
681
682 // =======================================================================
683 // function : EnableFeatures
684 // purpose  :
685 // =======================================================================
686 void OpenGl_Window::EnableFeatures() const
687 {
688   /*glPixelTransferi (GL_MAP_COLOR, GL_TRUE);*/
689
690   if (myDither)
691     glEnable (GL_DITHER);
692   else
693     glDisable (GL_DITHER);
694 }
695
696 // =======================================================================
697 // function : DisableFeatures
698 // purpose  :
699 // =======================================================================
700 void OpenGl_Window::DisableFeatures() const
701 {
702   glDisable (GL_DITHER);
703   glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
704
705   /*
706   * Disable stuff that's likely to slow down glDrawPixels.
707   * (Omit as much of this as possible, when you know in advance
708   * that the OpenGL state will already be set correctly.)
709   */
710   glDisable(GL_ALPHA_TEST);
711   glDisable(GL_BLEND);
712   glDisable(GL_DEPTH_TEST);
713   glDisable(GL_FOG);
714   glDisable(GL_LIGHTING);
715
716   glDisable(GL_LOGIC_OP);
717   glDisable(GL_STENCIL_TEST);
718   glDisable(GL_TEXTURE_1D);
719   glDisable(GL_TEXTURE_2D);
720   glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
721   glPixelTransferi(GL_RED_SCALE, 1);
722   glPixelTransferi(GL_RED_BIAS, 0);
723   glPixelTransferi(GL_GREEN_SCALE, 1);
724   glPixelTransferi(GL_GREEN_BIAS, 0);
725   glPixelTransferi(GL_BLUE_SCALE, 1);
726   glPixelTransferi(GL_BLUE_BIAS, 0);
727   glPixelTransferi(GL_ALPHA_SCALE, 1);
728   glPixelTransferi(GL_ALPHA_BIAS, 0);
729
730   /*
731   * Disable extensions that could slow down glDrawPixels.
732   * (Actually, you should check for the presence of the proper
733   * extension before making these calls.  I've omitted that
734   * code for simplicity.)
735   */
736
737 #ifdef GL_EXT_convolution
738   glDisable(GL_CONVOLUTION_1D_EXT);
739   glDisable(GL_CONVOLUTION_2D_EXT);
740   glDisable(GL_SEPARABLE_2D_EXT);
741 #endif
742
743 #ifdef GL_EXT_histogram
744   glDisable(GL_HISTOGRAM_EXT);
745   glDisable(GL_MINMAX_EXT);
746 #endif
747
748 #ifdef GL_EXT_texture3D
749   glDisable(GL_TEXTURE_3D_EXT);
750 #endif
751 }
752
753 // =======================================================================
754 // function : MakeFrontBufCurrent
755 // purpose  : TelMakeFrontBufCurrent
756 // =======================================================================
757 void OpenGl_Window::MakeFrontBufCurrent() const
758 {
759   glDrawBuffer (GL_FRONT);
760 }
761
762 // =======================================================================
763 // function : MakeBackBufCurrent
764 // purpose  : TelMakeBackBufCurrent
765 // =======================================================================
766 void OpenGl_Window::MakeBackBufCurrent() const
767 {
768   glDrawBuffer (GL_BACK);
769 }
770
771 // =======================================================================
772 // function : MakeFrontAndBackBufCurrent
773 // purpose  : TelMakeFrontAndBackBufCurrent
774 // =======================================================================
775 void OpenGl_Window::MakeFrontAndBackBufCurrent() const
776 {
777   glDrawBuffer (GL_FRONT_AND_BACK);
778 }
779
780 // =======================================================================
781 // function : GetGContext
782 // purpose  :
783 // =======================================================================
784 GLCONTEXT OpenGl_Window::GetGContext() const
785 {
786   return (GLCONTEXT )myGlContext->myGContext;
787 }