1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2012 OPEN CASCADE SAS
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.
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.
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.
21 #include <InterfaceGraphic.hxx>
23 #include <OpenGl_Window.hxx>
25 #include <OpenGl_Context.hxx>
26 #include <OpenGl_Display.hxx>
28 #include <Aspect_GraphicDeviceDefinitionError.hxx>
29 #include <TCollection_AsciiString.hxx>
31 #include <GL/glu.h> // gluOrtho2D()
33 IMPLEMENT_STANDARD_HANDLE(OpenGl_Window,MMgt_TShared)
34 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,MMgt_TShared)
38 static const TEL_COLOUR THE_DEFAULT_BG_COLOR = { { 0.F, 0.F, 0.F, 1.F } };
40 #if (defined(_WIN32) || defined(__WIN32__))
41 static int find_pixel_format (HDC theDevCtx,
42 PIXELFORMATDESCRIPTOR& thePixelFrmt,
43 const Standard_Boolean theIsDoubleBuff)
45 PIXELFORMATDESCRIPTOR aPixelFrmtTmp;
46 memset (&aPixelFrmtTmp, 0, sizeof (PIXELFORMATDESCRIPTOR));
47 aPixelFrmtTmp.nSize = sizeof (PIXELFORMATDESCRIPTOR);
48 aPixelFrmtTmp.nVersion = 1;
49 aPixelFrmtTmp.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | (theIsDoubleBuff ? PFD_DOUBLEBUFFER : PFD_SUPPORT_GDI);
50 aPixelFrmtTmp.iPixelType = PFD_TYPE_RGBA;
51 aPixelFrmtTmp.iLayerType = PFD_MAIN_PLANE;
53 const int BUFF_BITS_STENCIL[] = { 8, 1 };
54 const int BUFF_BITS_COLOR[] = { 32, 24 };
55 const int BUFF_BITS_DEPTH[] = { 32, 24, 16 };
57 int aGoodBits[] = { 0, 0, 0 };
58 int aPixelFrmtIdLast = 0;
59 int aPixelFrmtIdGood = 0;
60 Standard_Size aStencilIter = 0, aColorIter = 0, aDepthIter = 0;
61 for (aStencilIter = 0; aStencilIter < sizeof(BUFF_BITS_STENCIL) / sizeof(int); ++aStencilIter)
63 aPixelFrmtTmp.cStencilBits = BUFF_BITS_STENCIL[aStencilIter];
64 for (aDepthIter = 0; aDepthIter < sizeof(BUFF_BITS_DEPTH) / sizeof(int); ++aDepthIter)
66 aPixelFrmtTmp.cDepthBits = BUFF_BITS_DEPTH[aDepthIter];
68 for (aColorIter = 0; aColorIter < sizeof(BUFF_BITS_COLOR) / sizeof(int); ++aColorIter)
70 aPixelFrmtTmp.cColorBits = BUFF_BITS_COLOR[aColorIter];
71 aPixelFrmtIdLast = ChoosePixelFormat (theDevCtx, &aPixelFrmtTmp);
72 if (aPixelFrmtIdLast == 0)
77 thePixelFrmt.cDepthBits = 0;
78 thePixelFrmt.cColorBits = 0;
79 thePixelFrmt.cStencilBits = 0;
80 DescribePixelFormat (theDevCtx, aPixelFrmtIdLast, sizeof(PIXELFORMATDESCRIPTOR), &thePixelFrmt);
81 if (thePixelFrmt.cColorBits >= BUFF_BITS_COLOR[aColorIter]
82 && thePixelFrmt.cDepthBits >= BUFF_BITS_DEPTH[aDepthIter]
83 && thePixelFrmt.cStencilBits >= BUFF_BITS_STENCIL[aStencilIter])
87 if (thePixelFrmt.cColorBits > aGoodBits[0])
89 aGoodBits[0] = thePixelFrmt.cColorBits;
90 aGoodBits[1] = thePixelFrmt.cDepthBits;
91 aGoodBits[2] = thePixelFrmt.cStencilBits;
92 aPixelFrmtIdGood = aPixelFrmtIdLast;
94 else if (thePixelFrmt.cColorBits == aGoodBits[0])
96 if (thePixelFrmt.cDepthBits > aGoodBits[1])
98 aGoodBits[1] = thePixelFrmt.cDepthBits;
99 aGoodBits[2] = thePixelFrmt.cStencilBits;
100 aPixelFrmtIdGood = aPixelFrmtIdLast;
102 else if (thePixelFrmt.cDepthBits == aGoodBits[1])
104 if(thePixelFrmt.cStencilBits > aGoodBits[2])
106 aGoodBits[2] = thePixelFrmt.cStencilBits;
107 aPixelFrmtIdGood = aPixelFrmtIdLast;
112 if (aColorIter < sizeof(BUFF_BITS_COLOR) / sizeof(int))
117 if (aDepthIter < sizeof(BUFF_BITS_DEPTH) / sizeof(int))
123 return (aPixelFrmtIdLast == 0) ? aPixelFrmtIdGood : aPixelFrmtIdLast;
126 static Bool WaitForNotify (Display* theDisp, XEvent* theEv, char* theArg)
128 return (theEv->type == MapNotify) && (theEv->xmap.window == (Window )theArg);
134 // =======================================================================
135 // function : OpenGl_Window
137 // =======================================================================
138 OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
139 const CALL_DEF_WINDOW& theCWindow,
140 Aspect_RenderingContext theGContext,
141 const Handle(OpenGl_Context)& theShareCtx)
142 : myDisplay (theDisplay),
143 myGlContext (new OpenGl_Context()),
144 myOwnGContext (theGContext == 0),
145 #if (defined(_WIN32) || defined(__WIN32__))
146 mySysPalInUse (FALSE),
148 myWidth ((Standard_Integer )theCWindow.dx),
149 myHeight ((Standard_Integer )theCWindow.dy),
150 myBgColor (THE_DEFAULT_BG_COLOR),
151 myDither (theDisplay->Dither()),
152 myBackDither (theDisplay->BackDither())
154 myBgColor.rgb[0] = theCWindow.Background.r;
155 myBgColor.rgb[1] = theCWindow.Background.g;
156 myBgColor.rgb[2] = theCWindow.Background.b;
158 #if (defined(_WIN32) || defined(__WIN32__))
159 HWND aWindow = (HWND )theCWindow.XWindow;
160 HDC aWindowDC = GetDC (aWindow);
161 HGLRC aGContext = (HGLRC )theGContext;
163 PIXELFORMATDESCRIPTOR aPixelFrmt;
164 const int aPixelFrmtId = find_pixel_format (aWindowDC, aPixelFrmt, myDisplay->DBuffer());
165 if (aPixelFrmtId == 0)
167 ReleaseDC (aWindow, aWindowDC);
169 TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
170 aMsg += (int )GetLastError();
171 Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
175 if (aPixelFrmt.dwFlags & PFD_NEED_PALETTE)
177 WINDOW_DATA* aWndData = (WINDOW_DATA* )GetWindowLongPtr (aWindow, GWLP_USERDATA);
179 mySysPalInUse = (aPixelFrmt.dwFlags & PFD_NEED_SYSTEM_PALETTE) ? TRUE : FALSE;
180 InterfaceGraphic_RealizePalette (aWindowDC, aWndData->hPal, FALSE, mySysPalInUse);
185 myDither = (aPixelFrmt.cColorBits <= 8);
190 myBackDither = (aPixelFrmt.cColorBits <= 8);
193 if (!SetPixelFormat (aWindowDC, aPixelFrmtId, &aPixelFrmt))
195 ReleaseDC (aWindow, aWindowDC);
197 TCollection_AsciiString aMsg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
198 aMsg += (int )GetLastError();
199 Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
203 if (aGContext == NULL)
205 aGContext = wglCreateContext (aWindowDC);
206 if (aGContext == NULL)
208 ReleaseDC (aWindow, aWindowDC);
210 TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglCreateContext failed. Error code: ");
211 aMsg += (int )GetLastError();
212 Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
217 // all GL context within one OpenGl_GraphicDriver should be shared!
218 if (!theShareCtx.IsNull() && wglShareLists ((HGLRC )theShareCtx->myGContext, aGContext) != TRUE)
220 TCollection_AsciiString aMsg ("OpenGl_Window::CreateWindow: wglShareLists failed. Error code: ");
221 aMsg += (int )GetLastError();
222 Aspect_GraphicDeviceDefinitionError::Raise (aMsg.ToCString());
226 myGlContext->Init ((Aspect_Handle )aWindow, (Aspect_Handle )aWindowDC, (Aspect_RenderingContext )aGContext);
228 WINDOW aParent = (WINDOW )theCWindow.XWindow;
230 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
231 GLXContext aGContext = (GLXContext )theGContext;
233 XWindowAttributes wattr;
234 XGetWindowAttributes (aDisp, aParent, &wattr);
235 const int scr = DefaultScreen (aDisp);
237 XVisualInfo* aVis = NULL;
239 unsigned long aVisInfoMask = VisualIDMask | VisualScreenMask;
240 XVisualInfo aVisInfo;
241 aVisInfo.visualid = wattr.visual->visualid;
242 aVisInfo.screen = scr;
244 aVis = XGetVisualInfo (aDisp, aVisInfoMask, &aVisInfo, &aNbItems);
251 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: XGetVisualInfo failed.");
259 #if defined(__linux) || defined(Linux) || defined(__APPLE__)
262 // check Visual for OpenGl context's parameters compability
263 int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, aDepthSize = 0, aStencilSize = 0;
265 if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0)
268 if (glXGetConfig (aDisp, aVis, GLX_RGBA, &isRGBA) != 0)
271 if (glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer) != 0)
274 if (glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE, &aDepthSize) != 0)
277 if (glXGetConfig (aDisp, aVis, GLX_STENCIL_SIZE, &aStencilSize) != 0)
280 if (!isGl || !aDepthSize || !isRGBA || (isDoubleBuffer ? 1 : 0) != (myDisplay->DBuffer()? 1 : 0))
292 anAttribs[anIter++] = GLX_RGBA;
294 anAttribs[anIter++] = GLX_DEPTH_SIZE;
295 anAttribs[anIter++] = 1;
297 anAttribs[anIter++] = GLX_STENCIL_SIZE;
298 anAttribs[anIter++] = 1;
300 anAttribs[anIter++] = GLX_RED_SIZE;
301 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
303 anAttribs[anIter++] = GLX_GREEN_SIZE;
304 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
306 anAttribs[anIter++] = GLX_BLUE_SIZE;
307 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
309 if (myDisplay->DBuffer())
310 anAttribs[anIter++] = GLX_DOUBLEBUFFER;
312 anAttribs[anIter++] = None;
314 aVis = glXChooseVisual (aDisp, scr, anAttribs);
317 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXChooseVisual failed.");
322 if (!theShareCtx.IsNull())
324 // ctx est une copie du previous
325 aGContext = glXCreateContext (aDisp, aVis, (GLXContext )theShareCtx->myGContext, GL_TRUE);
329 aGContext = glXCreateContext (aDisp, aVis, NULL, GL_TRUE);
334 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXCreateContext failed.");
338 Colormap cmap = XCreateColormap (aDisp, aParent, aVis->visual, AllocNone);
341 color.red = (unsigned short) (myBgColor.rgb[0] * 0xFFFF);
342 color.green = (unsigned short) (myBgColor.rgb[1] * 0xFFFF);
343 color.blue = (unsigned short) (myBgColor.rgb[2] * 0xFFFF);
344 color.flags = DoRed | DoGreen | DoBlue;
345 XAllocColor (aDisp, cmap, &color);
347 XSetWindowAttributes cwa;
349 cwa.event_mask = StructureNotifyMask;
350 cwa.border_pixel = color.pixel;
351 cwa.background_pixel = color.pixel;
353 if (aVis->visualid == wattr.visual->visualid)
359 unsigned long mask = CWBackPixel | CWColormap | CWBorderPixel | CWEventMask;
360 aWindow = XCreateWindow (aDisp, aParent, 0, 0, myWidth, myHeight, 0/*bw*/, aVis->depth, InputOutput, aVis->visual, mask, &cwa);
363 XSetWindowBackground (aDisp, aWindow, cwa.background_pixel);
364 XClearWindow (aDisp, aWindow);
366 if (aWindow != aParent)
369 XMapWindow (aDisp, aWindow);
370 XIfEvent (aDisp, &anEvent, WaitForNotify, (char* )aWindow);
375 * Le BackDitherProp est utilise pour le clear du background
376 * Pour eviter une difference de couleurs avec la couleur choisie
377 * par l'application (XWindow) il faut desactiver le dithering
378 * au dessus de 8 plans.
380 * Pour le DitherProp:
381 * On cherchera a activer le Dithering que si le Visual a au moins
382 * 8 plans pour le GLX_RED_SIZE. Le test est plus sur car on peut
383 * avoir une profondeur superieure a 12 mais avoir besoin du dithering.
384 * (Carte Impact avec GLX_RED_SIZE a 5 par exemple)
388 glXGetConfig (aDisp, aVis, GLX_RED_SIZE, &aValue);
391 myDither = (aValue < 8);
394 myBackDither = (aVis->depth <= 8);
396 XFree ((char* )aVis);
398 myGlContext->Init ((Aspect_Drawable )aWindow, (Aspect_Display )myDisplay->GetDisplay(), (Aspect_RenderingContext )aGContext);
400 myGlContext->Share (theShareCtx);
405 // =======================================================================
406 // function : ~OpenGl_Window
408 // =======================================================================
409 OpenGl_Window::~OpenGl_Window()
411 #if (defined(_WIN32) || defined(__WIN32__))
412 HWND aWindow = (HWND )myGlContext->myWindow;
413 HDC aWindowDC = (HDC )myGlContext->myWindowDC;
414 HGLRC aGContext = (HGLRC )myGlContext->myGContext;
415 myGlContext.Nullify();
419 if (wglGetCurrentContext() != NULL)
421 wglDeleteContext (aGContext);
423 ReleaseDC (aWindow, aWindowDC);
426 GLXDrawable aWindow = (GLXDrawable )myGlContext->myWindow;
427 Display* aDisplay = (Display* )myGlContext->myDisplay;
428 GLXContext aGContext = (GLXContext )myGlContext->myGContext;
429 myGlContext.Nullify();
431 if (aDisplay != NULL && myOwnGContext)
433 // FSXXX sync necessary if non-direct rendering
435 glXDestroyContext (aDisplay, aGContext);
440 // =======================================================================
441 // function : Activate
443 // =======================================================================
444 Standard_Boolean OpenGl_Window::Activate()
446 return myGlContext->MakeCurrent();
449 // =======================================================================
451 // purpose : call_subr_resize
452 // =======================================================================
453 void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
455 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
459 // If the size is not changed - do nothing
460 if ((myWidth == theCWindow.dx) && (myHeight == theCWindow.dy))
463 myWidth = (Standard_Integer )theCWindow.dx;
464 myHeight = (Standard_Integer )theCWindow.dy;
466 #if (!defined(_WIN32) && !defined(__WIN32__))
467 XResizeWindow (aDisp, myGlContext->myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
468 XSync (aDisp, False);
474 // =======================================================================
475 // function : ReadDepths
476 // purpose : TelReadDepths
477 // =======================================================================
478 void OpenGl_Window::ReadDepths (const Standard_Integer theX, const Standard_Integer theY,
479 const Standard_Integer theWidth, const Standard_Integer theHeight,
482 if (theDepths == NULL || !Activate())
485 glMatrixMode (GL_PROJECTION);
487 gluOrtho2D (0.0, (GLdouble )myWidth, 0.0, (GLdouble )myHeight);
488 glMatrixMode (GL_MODELVIEW);
491 glRasterPos2i (theX, theY);
493 glReadPixels (theX, theY, theWidth, theHeight, GL_DEPTH_COMPONENT, GL_FLOAT, theDepths);
497 // =======================================================================
498 // function : SetBackgroundColor
499 // purpose : call_subr_set_background
500 // =======================================================================
501 void OpenGl_Window::SetBackgroundColor (const Standard_ShortReal theR,
502 const Standard_ShortReal theG,
503 const Standard_ShortReal theB)
505 myBgColor.rgb[0] = theR;
506 myBgColor.rgb[1] = theG;
507 myBgColor.rgb[2] = theB;
510 // =======================================================================
513 // =======================================================================
514 void OpenGl_Window::Init()
519 #if (defined(_WIN32) || defined(__WIN32__))
521 GetClientRect ((HWND )myGlContext->myWindow, &cr);
522 myWidth = cr.right - cr.left;
523 myHeight = cr.bottom - cr.top;
527 unsigned int aDummyU;
528 unsigned int aNewWidth = 0;
529 unsigned int aNewHeight = 0;
530 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
531 XGetGeometry (aDisp, myGlContext->myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
533 myHeight = aNewHeight;
536 glMatrixMode (GL_MODELVIEW);
537 glViewport (0, 0, myWidth, myHeight);
539 glDisable (GL_SCISSOR_TEST);
540 glDrawBuffer (GL_BACK);
543 // =======================================================================
544 // function : EnablePolygonOffset
545 // purpose : call_subr_enable_polygon_offset
546 // =======================================================================
547 void OpenGl_Window::EnablePolygonOffset() const
549 Standard_ShortReal aFactor, aUnits;
550 myDisplay->PolygonOffset (aFactor, aUnits);
551 glPolygonOffset (aFactor, aUnits);
552 glEnable (GL_POLYGON_OFFSET_FILL);
555 // =======================================================================
556 // function : DisablePolygonOffset
557 // purpose : call_subr_disable_polygon_offset
558 // =======================================================================
559 void OpenGl_Window::DisablePolygonOffset() const
561 glDisable (GL_POLYGON_OFFSET_FILL);
564 // =======================================================================
565 // function : EnableFeatures
567 // =======================================================================
568 void OpenGl_Window::EnableFeatures() const
570 /*glPixelTransferi (GL_MAP_COLOR, GL_TRUE);*/
573 glEnable (GL_DITHER);
575 glDisable (GL_DITHER);
578 // =======================================================================
579 // function : DisableFeatures
581 // =======================================================================
582 void OpenGl_Window::DisableFeatures() const
584 glDisable (GL_DITHER);
585 glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
588 * Disable stuff that's likely to slow down glDrawPixels.
589 * (Omit as much of this as possible, when you know in advance
590 * that the OpenGL state will already be set correctly.)
592 glDisable(GL_ALPHA_TEST);
594 glDisable(GL_DEPTH_TEST);
596 glDisable(GL_LIGHTING);
598 glDisable(GL_LOGIC_OP);
599 glDisable(GL_STENCIL_TEST);
600 glDisable(GL_TEXTURE_1D);
601 glDisable(GL_TEXTURE_2D);
602 glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
603 glPixelTransferi(GL_RED_SCALE, 1);
604 glPixelTransferi(GL_RED_BIAS, 0);
605 glPixelTransferi(GL_GREEN_SCALE, 1);
606 glPixelTransferi(GL_GREEN_BIAS, 0);
607 glPixelTransferi(GL_BLUE_SCALE, 1);
608 glPixelTransferi(GL_BLUE_BIAS, 0);
609 glPixelTransferi(GL_ALPHA_SCALE, 1);
610 glPixelTransferi(GL_ALPHA_BIAS, 0);
613 * Disable extensions that could slow down glDrawPixels.
614 * (Actually, you should check for the presence of the proper
615 * extension before making these calls. I've omitted that
616 * code for simplicity.)
619 #ifdef GL_EXT_convolution
620 glDisable(GL_CONVOLUTION_1D_EXT);
621 glDisable(GL_CONVOLUTION_2D_EXT);
622 glDisable(GL_SEPARABLE_2D_EXT);
625 #ifdef GL_EXT_histogram
626 glDisable(GL_HISTOGRAM_EXT);
627 glDisable(GL_MINMAX_EXT);
630 #ifdef GL_EXT_texture3D
631 glDisable(GL_TEXTURE_3D_EXT);
635 // =======================================================================
636 // function : MakeFrontBufCurrent
637 // purpose : TelMakeFrontBufCurrent
638 // =======================================================================
639 void OpenGl_Window::MakeFrontBufCurrent() const
641 glDrawBuffer (GL_FRONT);
644 // =======================================================================
645 // function : MakeBackBufCurrent
646 // purpose : TelMakeBackBufCurrent
647 // =======================================================================
648 void OpenGl_Window::MakeBackBufCurrent() const
650 glDrawBuffer (GL_BACK);
653 // =======================================================================
654 // function : MakeFrontAndBackBufCurrent
655 // purpose : TelMakeFrontAndBackBufCurrent
656 // =======================================================================
657 void OpenGl_Window::MakeFrontAndBackBufCurrent() const
659 glDrawBuffer (GL_FRONT_AND_BACK);
662 // =======================================================================
663 // function : GetGContext
665 // =======================================================================
666 GLCONTEXT OpenGl_Window::GetGContext() const
668 return (GLCONTEXT )myGlContext->myGContext;