1 // File: OpenGl_Window.cxx
2 // Created: 20 September 2011
3 // Author: Sergey ZERCHANINOV
4 // Copyright: OPEN CASCADE 2011
6 #include <InterfaceGraphic.hxx>
8 #include <OpenGl_Window.hxx>
10 #include <OpenGl_Context.hxx>
11 #include <OpenGl_Display.hxx>
12 #include <OpenGl_ResourceCleaner.hxx>
13 #include <OpenGl_ResourceTexture.hxx>
15 #include <Aspect_GraphicDeviceDefinitionError.hxx>
16 #include <TCollection_AsciiString.hxx>
18 IMPLEMENT_STANDARD_HANDLE(OpenGl_Window,MMgt_TShared)
19 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,MMgt_TShared)
23 static const TEL_COLOUR THE_DEFAULT_BG_COLOR = { { 0.F, 0.F, 0.F, 1.F } };
25 static GLCONTEXT ThePreviousCtx = 0; // to share GL resources
26 #if (!defined(_WIN32) && !defined(__WIN32__))
27 static GLXContext TheDeadGlxCtx; // Context to be destroyed
28 static Display* TheDeadGlxDpy; // Display associated with TheDeadGlxCtx
31 #if (defined(_WIN32) || defined(__WIN32__))
32 static int find_pixel_format (HDC hDC, PIXELFORMATDESCRIPTOR* pfd, const Standard_Boolean dbuff)
34 PIXELFORMATDESCRIPTOR pfd0;
35 memset (&pfd0, 0, sizeof (PIXELFORMATDESCRIPTOR));
36 pfd0.nSize = sizeof (PIXELFORMATDESCRIPTOR);
38 pfd0.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | (dbuff ? PFD_DOUBLEBUFFER : PFD_SUPPORT_GDI);
39 pfd0.iPixelType = PFD_TYPE_RGBA;
40 pfd0.iLayerType = PFD_MAIN_PLANE;
44 const int cBits[] = { 32, 24 };
45 const int dBits[] = { 32, 24, 16 };
48 for (i = 0; i < sizeof(dBits) / sizeof(int); i++)
50 pfd0.cDepthBits = dBits[i];
52 for (j = 0; j < sizeof(cBits) / sizeof(int); j++)
54 pfd0.cColorBits = cBits[j];
55 iPixelFormat = ChoosePixelFormat (hDC, &pfd0);
60 DescribePixelFormat (hDC, iPixelFormat, sizeof (PIXELFORMATDESCRIPTOR), pfd);
61 if (pfd->cColorBits >= cBits[j] && pfd->cDepthBits >= dBits[i])
67 if (j < sizeof(cBits) / sizeof(int))
71 if (iPixelFormat == 0)
77 static Bool WaitForNotify (Display* theDisp, XEvent* theEv, char* theArg)
79 return (theEv->type == MapNotify) && (theEv->xmap.window == (Window )theArg);
85 // =======================================================================
86 // function : OpenGl_Window
88 // =======================================================================
89 OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
90 const CALL_DEF_WINDOW& theCWindow,
91 Aspect_RenderingContext theGContext)
92 : myDisplay (theDisplay),
94 myGContext ((GLCONTEXT )theGContext),
95 myGlContext (new OpenGl_Context()),
96 myOwnGContext (theGContext == 0),
97 #if (defined(_WIN32) || defined(__WIN32__))
99 mySysPalInUse (FALSE),
101 myWidth ((Standard_Integer )theCWindow.dx),
102 myHeight ((Standard_Integer )theCWindow.dy),
103 myBgColor (THE_DEFAULT_BG_COLOR),
104 myDither (theDisplay->Dither()),
105 myBackDither (theDisplay->BackDither())
107 myBgColor.rgb[0] = theCWindow.Background.r;
108 myBgColor.rgb[1] = theCWindow.Background.g;
109 myBgColor.rgb[2] = theCWindow.Background.b;
111 WINDOW aParent = (WINDOW )theCWindow.XWindow;
112 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
114 #if (!defined(_WIN32) && !defined(__WIN32__))
115 XWindowAttributes wattr;
116 XGetWindowAttributes (aDisp, aParent, &wattr);
117 const int scr = DefaultScreen (aDisp);
119 XVisualInfo* aVis = NULL;
121 unsigned long aVisInfoMask = VisualIDMask | VisualScreenMask;
122 XVisualInfo aVisInfo;
123 aVisInfo.visualid = wattr.visual->visualid;
124 aVisInfo.screen = scr;
126 aVis = XGetVisualInfo (aDisp, aVisInfoMask, &aVisInfo, &aNbItems);
135 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: XGetVisualInfo failed.");
145 #if defined(__linux) || defined(Linux)
148 // check Visual for OpenGl context's parameters compability
149 int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, aDepthSize = 0;
151 if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0)
154 if (glXGetConfig (aDisp, aVis, GLX_RGBA, &isRGBA) != 0)
157 if (glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer) != 0)
160 if (glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE, &aDepthSize) != 0)
163 if (!isGl || !aDepthSize || !isRGBA || (isDoubleBuffer ? 1 : 0) != (myDisplay->DBuffer()? 1 : 0))
175 anAttribs[anIter++] = GLX_RGBA;
177 anAttribs[anIter++] = GLX_DEPTH_SIZE;
178 anAttribs[anIter++] = 1;
180 anAttribs[anIter++] = GLX_RED_SIZE;
181 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
183 anAttribs[anIter++] = GLX_GREEN_SIZE;
184 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
186 anAttribs[anIter++] = GLX_BLUE_SIZE;
187 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
189 if (myDisplay->DBuffer())
190 anAttribs[anIter++] = GLX_DOUBLEBUFFER;
192 anAttribs[anIter++] = None;
194 aVis = glXChooseVisual (aDisp, scr, anAttribs);
197 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXChooseVisual failed.");
204 // recover display lists from TheDeadGlxCtx, then destroy it
205 ctx = glXCreateContext (aDisp, aVis, TheDeadGlxCtx, GL_TRUE);
207 OpenGl_ResourceCleaner::GetInstance()->RemoveContext (TheDeadGlxCtx);
208 glXDestroyContext (TheDeadGlxDpy, TheDeadGlxCtx);
212 else if (ThePreviousCtx == 0)
214 ctx = glXCreateContext (aDisp, aVis, NULL, GL_TRUE);
218 // ctx est une copie du previous
219 ctx = glXCreateContext (aDisp, aVis, ThePreviousCtx, GL_TRUE);
224 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXCreateContext failed.");
228 OpenGl_ResourceCleaner::GetInstance()->AppendContext (ctx, true);
230 ThePreviousCtx = ctx;
232 Colormap cmap = XCreateColormap (aDisp, aParent, aVis->visual, AllocNone);
235 color.red = (unsigned short) (myBgColor.rgb[0] * 0xFFFF);
236 color.green = (unsigned short) (myBgColor.rgb[1] * 0xFFFF);
237 color.blue = (unsigned short) (myBgColor.rgb[2] * 0xFFFF);
238 color.flags = DoRed | DoGreen | DoBlue;
239 XAllocColor (aDisp, cmap, &color);
241 XSetWindowAttributes cwa;
243 cwa.event_mask = StructureNotifyMask;
244 cwa.border_pixel = color.pixel;
245 cwa.background_pixel = color.pixel;
247 if (aVis->visualid == wattr.visual->visualid)
253 unsigned long mask = CWBackPixel | CWColormap | CWBorderPixel | CWEventMask;
254 win = XCreateWindow (aDisp, aParent, 0, 0, myWidth, myHeight, 0/*bw*/, aVis->depth, InputOutput, aVis->visual, mask, &cwa);
257 XSetWindowBackground (aDisp, win, cwa.background_pixel);
258 XClearWindow (aDisp, win);
263 XMapWindow (aDisp, win);
264 XIfEvent (aDisp, &anEvent, WaitForNotify, (char* )win);
271 * Le BackDitherProp est utilise pour le clear du background
272 * Pour eviter une difference de couleurs avec la couleur choisie
273 * par l'application (XWindow) il faut desactiver le dithering
274 * au dessus de 8 plans.
276 * Pour le DitherProp:
277 * On cherchera a activer le Dithering que si le Visual a au moins
278 * 8 plans pour le GLX_RED_SIZE. Le test est plus sur car on peut
279 * avoir une profondeur superieure a 12 mais avoir besoin du dithering.
280 * (Carte Impact avec GLX_RED_SIZE a 5 par exemple)
284 glXGetConfig (aDisp, aVis, GLX_RED_SIZE, &value);
287 myDither = (value < 8);
290 myBackDither = (aVis->depth <= 8);
292 XFree ((char* )aVis);
298 myWindowDC = GetDC (aParent);
300 PIXELFORMATDESCRIPTOR pfd;
301 int iPixelFormat = find_pixel_format (myWindowDC, &pfd, myDisplay->DBuffer());
302 if (iPixelFormat == 0)
304 ReleaseDC (aParent, myWindowDC);
307 TCollection_AsciiString msg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
308 msg += (int )GetLastError();
309 Aspect_GraphicDeviceDefinitionError::Raise (msg.ToCString());
313 if (pfd.dwFlags & PFD_NEED_PALETTE)
315 WINDOW_DATA* wd = (WINDOW_DATA* )GetWindowLongPtr (aParent, GWLP_USERDATA);
317 mySysPalInUse = (pfd.dwFlags & PFD_NEED_SYSTEM_PALETTE) ? TRUE : FALSE;
318 InterfaceGraphic_RealizePalette (myWindowDC, wd->hPal, FALSE, mySysPalInUse);
322 myDither = (pfd.cColorBits <= 8);
325 myBackDither = (pfd.cColorBits <= 8);
327 if (!SetPixelFormat (myWindowDC, iPixelFormat, &pfd))
329 ReleaseDC (aParent, myWindowDC);
332 TCollection_AsciiString msg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
333 msg += (int)GetLastError();
334 Aspect_GraphicDeviceDefinitionError::Raise (msg.ToCString());
340 ThePreviousCtx = myGContext;
344 myGContext = wglCreateContext (myWindowDC);
345 if (myGContext == NULL)
347 ReleaseDC (aParent, myWindowDC);
350 TCollection_AsciiString msg ("OpenGl_Window::CreateWindow: wglCreateContext failed. Error code: ");
351 msg += (int )GetLastError();
352 Aspect_GraphicDeviceDefinitionError::Raise (msg.ToCString());
356 Standard_Boolean isShared = Standard_True;
357 if (ThePreviousCtx == NULL)
359 ThePreviousCtx = myGContext;
363 // if we already have some shared context
364 GLCONTEXT shareCtx = OpenGl_ResourceCleaner::GetInstance()->GetSharedContext();
365 if (shareCtx != NULL)
367 // try to share context with one from resource cleaner list
368 isShared = (Standard_Boolean )wglShareLists (shareCtx, myGContext);
372 isShared = (Standard_Boolean )wglShareLists (ThePreviousCtx, myGContext);
373 // add shared ThePreviousCtx to a control list if it's not there
375 OpenGl_ResourceCleaner::GetInstance()->AppendContext (ThePreviousCtx, isShared);
379 // add the context to OpenGl_ResourceCleaner control list
380 OpenGl_ResourceCleaner::GetInstance()->AppendContext (myGContext, isShared);
390 // =======================================================================
391 // function : ~OpenGl_Window
393 // =======================================================================
394 OpenGl_Window::~OpenGl_Window()
396 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
397 if (aDisp == NULL || !myOwnGContext)
400 #if (defined(_WIN32) || defined(__WIN32__))
401 OpenGl_ResourceCleaner::GetInstance()->RemoveContext (myGContext);
403 if (wglGetCurrentContext() != NULL)
404 wglDeleteContext (myGContext);
405 ReleaseDC (myWindow, myWindowDC);
407 if (myDisplay->myMapOfWindows.Size() == 0)
410 // FSXXX sync necessary if non-direct rendering
413 if (ThePreviousCtx == myGContext)
415 ThePreviousCtx = NULL;
416 if (myDisplay->myMapOfWindows.Size() > 0)
418 NCollection_DataMap<Standard_Integer, Handle(OpenGl_Window)>::Iterator it (myDisplay->myMapOfWindows);
419 ThePreviousCtx = it.Value()->myGContext;
422 // if this is the last remaining context, do not destroy it yet, to avoid
423 // losing any shared display lists (fonts...)
426 OpenGl_ResourceCleaner::GetInstance()->RemoveContext(myGContext);
427 glXDestroyContext(aDisp, myGContext);
431 TheDeadGlxCtx = myGContext;
432 TheDeadGlxDpy = aDisp;
437 OpenGl_ResourceCleaner::GetInstance()->RemoveContext (myGContext);
438 glXDestroyContext (aDisp, myGContext);
443 // =======================================================================
444 // function : Activate
446 // =======================================================================
447 Standard_Boolean OpenGl_Window::Activate()
449 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
451 return Standard_False;
453 #if (defined(_WIN32) || defined(__WIN32__))
454 if (!wglMakeCurrent (myWindowDC, myGContext))
456 //GLenum errorcode = glGetError();
457 //const GLubyte *errorstring = gluErrorString(errorcode);
458 //printf("wglMakeCurrent failed: %d %s\n", errorcode, errorstring);
459 return Standard_False;
462 if (!glXMakeCurrent (aDisp, myWindow, myGContext))
464 // if there is no current context it might be impossible to use glGetError correctly
465 //printf("glXMakeCurrent failed!\n");
466 return Standard_False;
470 return Standard_True;
473 // =======================================================================
475 // purpose : call_subr_resize
476 // =======================================================================
477 void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
479 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
483 // If the size is not changed - do nothing
484 if ((myWidth == theCWindow.dx) && (myHeight == theCWindow.dy))
487 myWidth = (Standard_Integer )theCWindow.dx;
488 myHeight = (Standard_Integer )theCWindow.dy;
490 #if (!defined(_WIN32) && !defined(__WIN32__))
491 XResizeWindow (aDisp, myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
492 XSync (aDisp, False);
498 // =======================================================================
499 // function : ReadDepths
500 // purpose : TelReadDepths
501 // =======================================================================
502 void OpenGl_Window::ReadDepths (const Standard_Integer theX, const Standard_Integer theY,
503 const Standard_Integer theWidth, const Standard_Integer theHeight,
506 if (theDepths == NULL || !Activate())
509 glMatrixMode (GL_PROJECTION);
511 gluOrtho2D (0.0, (GLdouble )myWidth, 0.0, (GLdouble )myHeight);
512 glMatrixMode (GL_MODELVIEW);
515 glRasterPos2i (theX, theY);
517 glReadPixels (theX, theY, theWidth, theHeight, GL_DEPTH_COMPONENT, GL_FLOAT, theDepths);
521 // =======================================================================
522 // function : SetBackgroundColor
523 // purpose : call_subr_set_background
524 // =======================================================================
525 void OpenGl_Window::SetBackgroundColor (const Standard_ShortReal theR,
526 const Standard_ShortReal theG,
527 const Standard_ShortReal theB)
529 myBgColor.rgb[0] = theR;
530 myBgColor.rgb[1] = theG;
531 myBgColor.rgb[2] = theB;
534 // =======================================================================
537 // =======================================================================
538 void OpenGl_Window::Init()
543 #if (defined(_WIN32) || defined(__WIN32__))
545 GetClientRect (myWindow, &cr);
546 myWidth = cr.right - cr.left;
547 myHeight = cr.bottom - cr.top;
551 unsigned int aDummyU;
552 unsigned int aNewWidth = 0;
553 unsigned int aNewHeight = 0;
554 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
555 XGetGeometry (aDisp, myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
557 myHeight = aNewHeight;
560 glMatrixMode (GL_MODELVIEW);
561 glViewport (0, 0, myWidth, myHeight);
563 glDisable (GL_SCISSOR_TEST);
564 glDrawBuffer (GL_BACK);
567 // =======================================================================
568 // function : EnablePolygonOffset
569 // purpose : call_subr_enable_polygon_offset
570 // =======================================================================
571 void OpenGl_Window::EnablePolygonOffset() const
573 Standard_ShortReal aFactor, aUnits;
574 myDisplay->PolygonOffset (aFactor, aUnits);
575 glPolygonOffset (aFactor, aUnits);
576 glEnable (GL_POLYGON_OFFSET_FILL);
579 // =======================================================================
580 // function : DisablePolygonOffset
581 // purpose : call_subr_disable_polygon_offset
582 // =======================================================================
583 void OpenGl_Window::DisablePolygonOffset() const
585 glDisable (GL_POLYGON_OFFSET_FILL);
588 // =======================================================================
589 // function : EnableFeatures
591 // =======================================================================
592 void OpenGl_Window::EnableFeatures() const
594 /*glPixelTransferi (GL_MAP_COLOR, GL_TRUE);*/
597 glEnable (GL_DITHER);
599 glDisable (GL_DITHER);
602 // =======================================================================
603 // function : DisableFeatures
605 // =======================================================================
606 void OpenGl_Window::DisableFeatures() const
608 glDisable (GL_DITHER);
609 glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
612 * Disable stuff that's likely to slow down glDrawPixels.
613 * (Omit as much of this as possible, when you know in advance
614 * that the OpenGL state will already be set correctly.)
616 glDisable(GL_ALPHA_TEST);
618 glDisable(GL_DEPTH_TEST);
620 glDisable(GL_LIGHTING);
622 glDisable(GL_LOGIC_OP);
623 glDisable(GL_STENCIL_TEST);
624 glDisable(GL_TEXTURE_1D);
625 glDisable(GL_TEXTURE_2D);
626 glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
627 glPixelTransferi(GL_RED_SCALE, 1);
628 glPixelTransferi(GL_RED_BIAS, 0);
629 glPixelTransferi(GL_GREEN_SCALE, 1);
630 glPixelTransferi(GL_GREEN_BIAS, 0);
631 glPixelTransferi(GL_BLUE_SCALE, 1);
632 glPixelTransferi(GL_BLUE_BIAS, 0);
633 glPixelTransferi(GL_ALPHA_SCALE, 1);
634 glPixelTransferi(GL_ALPHA_BIAS, 0);
637 * Disable extensions that could slow down glDrawPixels.
638 * (Actually, you should check for the presence of the proper
639 * extension before making these calls. I've omitted that
640 * code for simplicity.)
643 #ifdef GL_EXT_convolution
644 glDisable(GL_CONVOLUTION_1D_EXT);
645 glDisable(GL_CONVOLUTION_2D_EXT);
646 glDisable(GL_SEPARABLE_2D_EXT);
649 #ifdef GL_EXT_histogram
650 glDisable(GL_HISTOGRAM_EXT);
651 glDisable(GL_MINMAX_EXT);
654 #ifdef GL_EXT_texture3D
655 glDisable(GL_TEXTURE_3D_EXT);
659 // =======================================================================
660 // function : MakeFrontBufCurrent
661 // purpose : TelMakeFrontBufCurrent
662 // =======================================================================
663 void OpenGl_Window::MakeFrontBufCurrent() const
665 glDrawBuffer (GL_FRONT);
668 // =======================================================================
669 // function : MakeBackBufCurrent
670 // purpose : TelMakeBackBufCurrent
671 // =======================================================================
672 void OpenGl_Window::MakeBackBufCurrent() const
674 glDrawBuffer (GL_BACK);
677 // =======================================================================
678 // function : MakeFrontAndBackBufCurrent
679 // purpose : TelMakeFrontAndBackBufCurrent
680 // =======================================================================
681 void OpenGl_Window::MakeFrontAndBackBufCurrent() const
683 glDrawBuffer (GL_FRONT_AND_BACK);