0027797: Visualization - consider ZLayer properties while sorting list of picked...
[occt.git] / src / OpenGl / OpenGl_GraphicDriver.cxx
1 // Created on: 2011-10-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2013 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_GraphicDriver.hxx>
17 #include <OpenGl_Context.hxx>
18 #include <OpenGl_Flipper.hxx>
19 #include <OpenGl_GraduatedTrihedron.hxx>
20 #include <OpenGl_Group.hxx>
21 #include <OpenGl_View.hxx>
22 #include <OpenGl_StencilTest.hxx>
23 #include <OpenGl_Text.hxx>
24 #include <OpenGl_Trihedron.hxx>
25 #include <OpenGl_Workspace.hxx>
26
27 #include <Aspect_GraphicDeviceDefinitionError.hxx>
28 #include <Aspect_IdentDefinitionError.hxx>
29 #include <Message_Messenger.hxx>
30 #include <OSD_Environment.hxx>
31 #include <Standard_NotImplemented.hxx>
32
33 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_GraphicDriver,Graphic3d_GraphicDriver)
34
35 #if defined(_WIN32)
36   #include <WNT_Window.hxx>
37 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
38   #include <Cocoa_Window.hxx>
39 #else
40   #include <Xw_Window.hxx>
41 #endif
42
43 #if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
44   #include <X11/Xlib.h> // XOpenDisplay()
45 #endif
46
47 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
48   #include <EGL/egl.h>
49 #endif
50
51 namespace
52 {
53   static const Handle(OpenGl_Context) TheNullGlCtx;
54 }
55
56 // =======================================================================
57 // function : OpenGl_GraphicDriver
58 // purpose  :
59 // =======================================================================
60 OpenGl_GraphicDriver::OpenGl_GraphicDriver (const Handle(Aspect_DisplayConnection)& theDisp,
61                                             const Standard_Boolean                  theToInitialize)
62 : Graphic3d_GraphicDriver (theDisp),
63   myIsOwnContext (Standard_False),
64 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
65   myEglDisplay ((Aspect_Display )EGL_NO_DISPLAY),
66   myEglContext ((Aspect_RenderingContext )EGL_NO_CONTEXT),
67   myEglConfig  (NULL),
68 #endif
69   myCaps           (new OpenGl_Caps()),
70   myMapOfView      (1, NCollection_BaseAllocator::CommonBaseAllocator()),
71   myMapOfStructure (1, NCollection_BaseAllocator::CommonBaseAllocator())
72 {
73 #if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
74   if (myDisplayConnection.IsNull())
75   {
76     //Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_GraphicDriver: cannot connect to X server!");
77     return;
78   }
79
80   Display* aDisplay = myDisplayConnection->GetDisplay();
81   Bool toSync = ::getenv ("CSF_GraphicSync") != NULL
82              || ::getenv ("CALL_SYNCHRO_X")  != NULL;
83   XSynchronize (aDisplay, toSync);
84
85 #if !defined(HAVE_EGL)
86   // does the server know about OpenGL & GLX?
87   int aDummy;
88   if (!XQueryExtension (aDisplay, "GLX", &aDummy, &aDummy, &aDummy))
89   {
90     ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, this system doesn't appear to support OpenGL!", Message_Warning);
91   }
92 #endif
93 #endif
94   if (theToInitialize
95   && !InitContext())
96   {
97     Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_GraphicDriver: default context can not be initialized!");
98   }
99
100   // default layers are always presented in display layer sequence it can not be removed
101   Graphic3d_ZLayerSettings anUnderlaySettings;
102   anUnderlaySettings.Flags = 0;
103   anUnderlaySettings.IsImmediate = false;
104   anUnderlaySettings.UseEnvironmentTexture = false;
105   myLayerIds.Add             (Graphic3d_ZLayerId_BotOSD);
106   myLayerSeq.Append          (Graphic3d_ZLayerId_BotOSD);
107   myMapOfZLayerSettings.Bind (Graphic3d_ZLayerId_BotOSD, anUnderlaySettings);
108
109   Graphic3d_ZLayerSettings aDefSettings;
110   aDefSettings.Flags = Graphic3d_ZLayerDepthTest
111                      | Graphic3d_ZLayerDepthWrite;
112   aDefSettings.IsImmediate = false;
113   myLayerIds.Add             (Graphic3d_ZLayerId_Default);
114   myLayerSeq.Append          (Graphic3d_ZLayerId_Default);
115   myMapOfZLayerSettings.Bind (Graphic3d_ZLayerId_Default, aDefSettings);
116
117   Graphic3d_ZLayerSettings aTopSettings;
118   aTopSettings.Flags = Graphic3d_ZLayerDepthTest
119                      | Graphic3d_ZLayerDepthWrite;
120   aTopSettings.IsImmediate = true;
121   myLayerIds.Add             (Graphic3d_ZLayerId_Top);
122   myLayerSeq.Append          (Graphic3d_ZLayerId_Top);
123   myMapOfZLayerSettings.Bind (Graphic3d_ZLayerId_Top, aTopSettings);
124
125   Graphic3d_ZLayerSettings aTopmostSettings;
126   aTopmostSettings.Flags = Graphic3d_ZLayerDepthTest
127                          | Graphic3d_ZLayerDepthWrite
128                          | Graphic3d_ZLayerDepthClear;
129   aTopmostSettings.IsImmediate = true;
130   myLayerIds.Add             (Graphic3d_ZLayerId_Topmost);
131   myLayerSeq.Append          (Graphic3d_ZLayerId_Topmost);
132   myMapOfZLayerSettings.Bind (Graphic3d_ZLayerId_Topmost, aTopmostSettings);
133
134   Graphic3d_ZLayerSettings anOsdSettings;
135   anOsdSettings.Flags = 0;
136   anOsdSettings.IsImmediate = true;
137   anOsdSettings.UseEnvironmentTexture = false;
138   myLayerIds.Add             (Graphic3d_ZLayerId_TopOSD);
139   myLayerSeq.Append          (Graphic3d_ZLayerId_TopOSD);
140   myMapOfZLayerSettings.Bind (Graphic3d_ZLayerId_TopOSD, anOsdSettings);
141 }
142
143 // =======================================================================
144 // function : ~OpenGl_GraphicDriver
145 // purpose  :
146 // =======================================================================
147 OpenGl_GraphicDriver::~OpenGl_GraphicDriver()
148 {
149   ReleaseContext();
150 }
151
152 // =======================================================================
153 // function : ReleaseContext
154 // purpose  :
155 // =======================================================================
156 void OpenGl_GraphicDriver::ReleaseContext()
157 {
158   Handle(OpenGl_Context) aCtxShared;
159   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
160        aViewIter.More(); aViewIter.Next())
161   {
162     const Handle(OpenGl_View)& aView = aViewIter.ChangeValue();
163     const Handle(OpenGl_Window)& aWindow = aView->GlWindow();
164     if (aWindow.IsNull())
165     {
166       continue;
167     }
168
169     const Handle(OpenGl_Context)& aCtx = aWindow->GetGlContext();
170     if (aCtx->MakeCurrent()
171      && aCtxShared.IsNull())
172     {
173       aCtxShared = aCtx;
174     }
175   }
176
177   if (!aCtxShared.IsNull())
178   {
179     aCtxShared->MakeCurrent();
180   }
181   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
182        aViewIter.More(); aViewIter.Next())
183   {
184     const Handle(OpenGl_View)& aView = aViewIter.ChangeValue();
185     aView->ReleaseGlResources (aCtxShared);
186   }
187
188   for (NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure);
189        aStructIt.More (); aStructIt.Next())
190   {
191     OpenGl_Structure* aStruct = aStructIt.ChangeValue();
192     aStruct->ReleaseGlResources (aCtxShared);
193   }
194   myDeviceLostFlag = myDeviceLostFlag || !myMapOfStructure.IsEmpty();
195
196   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
197        aViewIter.More(); aViewIter.Next())
198   {
199     const Handle(OpenGl_View)& aView = aViewIter.ChangeValue();
200     const Handle(OpenGl_Window)& aWindow = aView->GlWindow();
201     if (aWindow.IsNull())
202     {
203       continue;
204     }
205
206     aWindow->GetGlContext()->forcedRelease();
207   }
208
209 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
210   if (myIsOwnContext)
211   {
212     if (myEglContext != (Aspect_RenderingContext )EGL_NO_CONTEXT)
213     {
214       if (eglMakeCurrent ((EGLDisplay )myEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) != EGL_TRUE)
215       {
216         ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, FAILED to release OpenGL context!", Message_Warning);
217       }
218       eglDestroyContext ((EGLDisplay )myEglDisplay, (EGLContext )myEglContext);
219     }
220
221     if (myEglDisplay != (Aspect_Display )EGL_NO_DISPLAY)
222     {
223       if (eglTerminate ((EGLDisplay )myEglDisplay) != EGL_TRUE)
224       {
225         ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, EGL, eglTerminate FAILED!", Message_Warning);
226       }
227     }
228   }
229
230   myEglDisplay = (Aspect_Display )EGL_NO_DISPLAY;
231   myEglContext = (Aspect_RenderingContext )EGL_NO_CONTEXT;
232   myEglConfig  = NULL;
233 #endif
234   myIsOwnContext = Standard_False;
235 }
236
237 // =======================================================================
238 // function : InitContext
239 // purpose  :
240 // =======================================================================
241 Standard_Boolean OpenGl_GraphicDriver::InitContext()
242 {
243   ReleaseContext();
244 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
245
246 #if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
247   if (myDisplayConnection.IsNull())
248   {
249     return Standard_False;
250   }
251   Display* aDisplay = myDisplayConnection->GetDisplay();
252   myEglDisplay = (Aspect_Display )eglGetDisplay (aDisplay);
253 #else
254   myEglDisplay = (Aspect_Display )eglGetDisplay (EGL_DEFAULT_DISPLAY);
255 #endif
256   if ((EGLDisplay )myEglDisplay == EGL_NO_DISPLAY)
257   {
258     ::Message::DefaultMessenger()->Send ("Error: no EGL display!", Message_Fail);
259     return Standard_False;
260   }
261
262   EGLint aVerMajor = 0; EGLint aVerMinor = 0;
263   if (eglInitialize ((EGLDisplay )myEglDisplay, &aVerMajor, &aVerMinor) != EGL_TRUE)
264   {
265     ::Message::DefaultMessenger()->Send ("Error: EGL display is unavailable!", Message_Fail);
266     return Standard_False;
267   }
268
269   EGLint aConfigAttribs[] =
270   {
271     EGL_RED_SIZE,     8,
272     EGL_GREEN_SIZE,   8,
273     EGL_BLUE_SIZE,    8,
274     EGL_ALPHA_SIZE,   0,
275     EGL_DEPTH_SIZE,   24,
276     EGL_STENCIL_SIZE, 8,
277   #if defined(GL_ES_VERSION_2_0)
278     EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
279   #else
280     EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
281   #endif
282     EGL_NONE
283   };
284
285   EGLint aNbConfigs = 0;
286   if (eglChooseConfig ((EGLDisplay )myEglDisplay, aConfigAttribs, &myEglConfig, 1, &aNbConfigs) != EGL_TRUE
287    || myEglConfig == NULL)
288   {
289     eglGetError();
290     aConfigAttribs[4 * 2 + 1] = 16; // try config with smaller depth buffer
291     if (eglChooseConfig ((EGLDisplay )myEglDisplay, aConfigAttribs, &myEglConfig, 1, &aNbConfigs) != EGL_TRUE
292      || myEglConfig == NULL)
293     {
294       ::Message::DefaultMessenger()->Send ("Error: EGL does not provide compatible configurations!", Message_Fail);
295       return Standard_False;
296     }
297   }
298
299 #if defined(GL_ES_VERSION_2_0)
300   EGLint anEglCtxAttribs[] =
301   {
302     EGL_CONTEXT_CLIENT_VERSION, 2,
303     EGL_NONE
304   };
305   if (eglBindAPI (EGL_OPENGL_ES_API) != EGL_TRUE)
306   {
307     ::Message::DefaultMessenger()->Send ("Error: EGL does not provide OpenGL ES client!", Message_Fail);
308     return Standard_False;
309   }
310 #else
311   EGLint* anEglCtxAttribs = NULL;
312   if (eglBindAPI (EGL_OPENGL_API) != EGL_TRUE)
313   {
314     ::Message::DefaultMessenger()->Send ("Error: EGL does not provide OpenGL client!", Message_Fail);
315     return Standard_False;
316   }
317 #endif
318
319   myEglContext = (Aspect_RenderingContext )eglCreateContext ((EGLDisplay )myEglDisplay, myEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs);
320   if ((EGLContext )myEglContext == EGL_NO_CONTEXT)
321   {
322     ::Message::DefaultMessenger()->Send ("Error: EGL is unable to create OpenGL context!", Message_Fail);
323     return Standard_False;
324   }
325   if (eglMakeCurrent ((EGLDisplay )myEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, (EGLContext )myEglContext) != EGL_TRUE)
326   {
327     ::Message::DefaultMessenger()->Send ("Error: EGL is unable bind OpenGL context!", Message_Fail);
328     return Standard_False;
329   }
330 #endif
331   myIsOwnContext = Standard_True;
332   return Standard_True;
333 }
334
335 #if defined(HAVE_EGL) || defined(__ANDROID__) || defined(__QNX__)
336 // =======================================================================
337 // function : InitEglContext
338 // purpose  :
339 // =======================================================================
340 Standard_Boolean OpenGl_GraphicDriver::InitEglContext (Aspect_Display          theEglDisplay,
341                                                        Aspect_RenderingContext theEglContext,
342                                                        void*                   theEglConfig)
343 {
344   ReleaseContext();
345 #if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
346   if (myDisplayConnection.IsNull())
347   {
348     return Standard_False;
349   }
350 #endif
351
352   if ((EGLDisplay )theEglDisplay == EGL_NO_DISPLAY
353    || (EGLContext )theEglContext == EGL_NO_CONTEXT
354    || theEglConfig == NULL)
355   {
356     return Standard_False;
357   }
358   myEglDisplay = theEglDisplay;
359   myEglContext = theEglContext;
360   myEglConfig  = theEglConfig;
361   return Standard_True;
362 }
363 #endif
364
365 // =======================================================================
366 // function : InquireLightLimit
367 // purpose  :
368 // =======================================================================
369 Standard_Integer OpenGl_GraphicDriver::InquireLightLimit()
370 {
371   return OpenGLMaxLights;
372 }
373
374 // =======================================================================
375 // function : InquireViewLimit
376 // purpose  :
377 // =======================================================================
378 Standard_Integer OpenGl_GraphicDriver::InquireViewLimit()
379 {
380   return 10000;
381 }
382
383 // =======================================================================
384 // function : InquirePlaneLimit
385 // purpose  :
386 // =======================================================================
387 Standard_Integer OpenGl_GraphicDriver::InquirePlaneLimit()
388 {
389   const Handle(OpenGl_Context)& aCtx = GetSharedContext();
390   return aCtx.IsNull() ? aCtx->MaxClipPlanes() : 0;
391 }
392
393 // =======================================================================
394 // function : DefaultTextHeight
395 // purpose  :
396 // =======================================================================
397 Standard_ShortReal OpenGl_GraphicDriver::DefaultTextHeight() const
398 {
399   return 16.;
400 }
401
402 // =======================================================================
403 // function : EnableVBO
404 // purpose  :
405 // =======================================================================
406 void OpenGl_GraphicDriver::EnableVBO (const Standard_Boolean theToTurnOn)
407 {
408   myCaps->vboDisable = !theToTurnOn;
409 }
410
411 // =======================================================================
412 // function : GetSharedContext
413 // purpose  :
414 // =======================================================================
415 const Handle(OpenGl_Context)& OpenGl_GraphicDriver::GetSharedContext() const
416 {
417   if (myMapOfView.IsEmpty())
418   {
419     return TheNullGlCtx;
420   }
421
422   NCollection_Map<Handle(OpenGl_View)>::Iterator anIter (myMapOfView);
423   for (; anIter.More(); anIter.Next())
424   {
425     Handle(OpenGl_Window) aWindow = anIter.Value()->GlWindow();
426     if (aWindow.IsNull())
427     {
428       continue;
429     }
430
431     return aWindow->GetGlContext();
432   }
433
434   return TheNullGlCtx;
435 }
436
437 // =======================================================================
438 // function : MemoryInfo
439 // purpose  :
440 // =======================================================================
441 Standard_Boolean OpenGl_GraphicDriver::MemoryInfo (Standard_Size&           theFreeBytes,
442                                                    TCollection_AsciiString& theInfo) const
443 {
444   // this is extra work (for OpenGl_Context initialization)...
445   OpenGl_Context aGlCtx;
446   if (!aGlCtx.Init())
447   {
448     return Standard_False;
449   }
450   theFreeBytes = aGlCtx.AvailableMemory();
451   theInfo      = aGlCtx.MemoryInfo();
452   return !theInfo.IsEmpty();
453 }
454
455 // =======================================================================
456 // function : SetBuffersNoSwap
457 // purpose  :
458 // =======================================================================
459 void OpenGl_GraphicDriver::SetBuffersNoSwap (const Standard_Boolean theIsNoSwap)
460 {
461   myCaps->buffersNoSwap = theIsNoSwap;
462 }
463
464 // =======================================================================
465 // function : TextSize
466 // purpose  :
467 // =======================================================================
468 void OpenGl_GraphicDriver::TextSize (const Handle(Graphic3d_CView)& theView,
469                                      const Standard_CString         theText,
470                                      const Standard_ShortReal       theHeight,
471                                      Standard_ShortReal&            theWidth,
472                                      Standard_ShortReal&            theAscent,
473                                      Standard_ShortReal&            theDescent) const
474 {
475   const Handle(OpenGl_Context)& aCtx = GetSharedContext();
476   if (aCtx.IsNull())
477   {
478     return;
479   }
480
481   const Standard_ShortReal aHeight = (theHeight < 2.0f) ? DefaultTextHeight() : theHeight;
482   OpenGl_TextParam aTextParam;
483   aTextParam.Height = (int )aHeight;
484   OpenGl_AspectText aTextAspect;
485   aTextAspect.Aspect()->SetSpace (0.3);
486   TCollection_ExtendedString anExtText = theText;
487   NCollection_String aText = (Standard_Utf16Char* )anExtText.ToExtString();
488   OpenGl_Text::StringSize(aCtx, aText, aTextAspect, aTextParam, theView->RenderingParams().Resolution, theWidth, theAscent, theDescent);
489 }
490
491 //=======================================================================
492 //function : addZLayerIndex
493 //purpose  :
494 //=======================================================================
495 void OpenGl_GraphicDriver::addZLayerIndex (const Graphic3d_ZLayerId theLayerId)
496 {
497   // remove index
498   for (TColStd_SequenceOfInteger::Iterator aLayerIt (myLayerSeq); aLayerIt.More(); aLayerIt.Next())
499   {
500     if (aLayerIt.Value() == theLayerId)
501     {
502       myLayerSeq.Remove (aLayerIt);
503       break;
504     }
505   }
506
507   if (myMapOfZLayerSettings.Find (theLayerId).IsImmediate)
508   {
509     myLayerSeq.Append (theLayerId);
510     return;
511   }
512
513   for (TColStd_SequenceOfInteger::Iterator aLayerIt (myLayerSeq); aLayerIt.More(); aLayerIt.Next())
514   {
515     const Graphic3d_ZLayerSettings& aSettings = myMapOfZLayerSettings.Find (aLayerIt.Value());
516     if (aSettings.IsImmediate)
517     {
518       aLayerIt.Previous();
519       if (aLayerIt.More())
520       {
521         myLayerSeq.InsertAfter (aLayerIt, theLayerId);
522         return;
523       }
524
525       // first non-immediate layer
526       myLayerSeq.Prepend (theLayerId);
527       return;
528     }
529   }
530
531   // no immediate layers
532   myLayerSeq.Append (theLayerId);
533 }
534
535 //=======================================================================
536 //function : AddZLayer
537 //purpose  :
538 //=======================================================================
539 void OpenGl_GraphicDriver::AddZLayer (const Graphic3d_ZLayerId theLayerId)
540 {
541   if (theLayerId < 1)
542   {
543     Standard_ASSERT_RAISE (theLayerId > 0,
544                            "OpenGl_GraphicDriver::AddZLayer, "
545                            "negative and zero IDs are reserved");
546   }
547
548   myLayerIds.Add (theLayerId);
549
550   // Default z-layer settings
551   myMapOfZLayerSettings.Bind (theLayerId, Graphic3d_ZLayerSettings());
552   addZLayerIndex (theLayerId);
553
554   // Add layer to all views
555   NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
556   for (; aViewIt.More(); aViewIt.Next())
557   {
558     aViewIt.Value()->AddZLayer (theLayerId);
559   }
560 }
561
562 //=======================================================================
563 //function : RemoveZLayer
564 //purpose  :
565 //=======================================================================
566 void OpenGl_GraphicDriver::RemoveZLayer (const Graphic3d_ZLayerId theLayerId)
567 {
568   Standard_ASSERT_RAISE (theLayerId > 0,
569                          "OpenGl_GraphicDriver::AddZLayer, "
570                          "negative and zero IDs are reserved"
571                          "and can not be removed");
572
573   Standard_ASSERT_RAISE (myLayerIds.Contains (theLayerId),
574                          "OpenGl_GraphicDriver::RemoveZLayer, "
575                          "Layer with theLayerId does not exist");
576
577   // Remove layer from all of the views
578   NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
579   for (; aViewIt.More(); aViewIt.Next())
580   {
581     aViewIt.Value()->RemoveZLayer (theLayerId);
582   }
583
584   // Unset Z layer for all of the structures.
585   NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure);
586   for( ; aStructIt.More (); aStructIt.Next ())
587   {
588     OpenGl_Structure* aStruct = aStructIt.ChangeValue ();
589     if (aStruct->ZLayer() == theLayerId)
590       aStruct->SetZLayer (Graphic3d_ZLayerId_Default);
591   }
592
593   // Remove index
594   for (TColStd_SequenceOfInteger::Iterator aLayerIt (myLayerSeq); aLayerIt.More(); aLayerIt.Next())
595   {
596     if (aLayerIt.Value() == theLayerId)
597     {
598       myLayerSeq.Remove (aLayerIt);
599       break;
600     }
601   }
602
603   myMapOfZLayerSettings.UnBind (theLayerId);
604   myLayerIds.Remove  (theLayerId);
605 }
606
607 //=======================================================================
608 //function : ZLayers
609 //purpose  :
610 //=======================================================================
611 void OpenGl_GraphicDriver::ZLayers (TColStd_SequenceOfInteger& theLayerSeq) const
612 {
613   theLayerSeq.Assign (myLayerSeq);
614 }
615
616 //=======================================================================
617 //function : SetZLayerSettings
618 //purpose  :
619 //=======================================================================
620 void OpenGl_GraphicDriver::SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
621                                               const Graphic3d_ZLayerSettings& theSettings)
622 {
623   // Change Z layer settings in all managed views
624   NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
625   for (; aViewIt.More(); aViewIt.Next())
626   {
627     aViewIt.Value()->SetZLayerSettings (theLayerId, theSettings);
628   }
629
630   Graphic3d_ZLayerSettings* aSettings = myMapOfZLayerSettings.ChangeSeek (theLayerId);
631   if (aSettings != NULL)
632   {
633     const bool isChanged = (aSettings->IsImmediate != theSettings.IsImmediate);
634     *aSettings = theSettings;
635     if (isChanged)
636     {
637       addZLayerIndex (theLayerId);
638     }
639   }
640   else
641   {
642     // abnormal case
643     myMapOfZLayerSettings.Bind (theLayerId, theSettings);
644     addZLayerIndex (theLayerId);
645   }
646 }
647
648 //=======================================================================
649 //function : ZLayerSettings
650 //purpose  :
651 //=======================================================================
652 Graphic3d_ZLayerSettings OpenGl_GraphicDriver::ZLayerSettings (const Graphic3d_ZLayerId theLayerId)
653 {
654   Standard_ASSERT_RAISE (myLayerIds.Contains (theLayerId),
655                          "OpenGl_GraphicDriver::ZLayerSettings, "
656                          "Layer with theLayerId does not exist");
657
658   return myMapOfZLayerSettings.Find (theLayerId);
659 }
660
661 // =======================================================================
662 // function : Structure
663 // purpose  :
664 // =======================================================================
665 Handle(Graphic3d_CStructure) OpenGl_GraphicDriver::CreateStructure (const Handle(Graphic3d_StructureManager)& theManager)
666 {
667   Handle(OpenGl_Structure) aStructure = new OpenGl_Structure (theManager);
668   myMapOfStructure.Bind (aStructure->Id, aStructure.operator->());
669   return aStructure;
670 }
671
672 // =======================================================================
673 // function : Structure
674 // purpose  :
675 // =======================================================================
676 void OpenGl_GraphicDriver::RemoveStructure (Handle(Graphic3d_CStructure)& theCStructure)
677 {
678   OpenGl_Structure* aStructure = NULL;
679   if (!myMapOfStructure.Find (theCStructure->Id, aStructure))
680   {
681     return;
682   }
683
684   myMapOfStructure.UnBind (theCStructure->Id);
685   aStructure->Release (GetSharedContext());
686   theCStructure.Nullify();
687 }
688
689 // =======================================================================
690 // function : View
691 // purpose  :
692 // =======================================================================
693 Handle(Graphic3d_CView) OpenGl_GraphicDriver::CreateView (const Handle(Graphic3d_StructureManager)& theMgr)
694 {
695   Handle(OpenGl_View) aView = new OpenGl_View (theMgr, this, myCaps, myDeviceLostFlag, &myStateCounter);
696
697   myMapOfView.Add (aView);
698
699   for (TColStd_SequenceOfInteger::Iterator aLayerIt (myLayerSeq); aLayerIt.More(); aLayerIt.Next())
700   {
701     const Graphic3d_ZLayerId        aLayerID  = aLayerIt.Value();
702     const Graphic3d_ZLayerSettings& aSettings = myMapOfZLayerSettings.Find (aLayerID);
703     aView->AddZLayer         (aLayerID);
704     aView->SetZLayerSettings (aLayerID, aSettings);
705   }
706
707   return aView;
708 }
709
710 // =======================================================================
711 // function : RemoveView
712 // purpose  :
713 // =======================================================================
714 void OpenGl_GraphicDriver::RemoveView (const Handle(Graphic3d_CView)& theView)
715 {
716   Handle(OpenGl_Context) aCtx = GetSharedContext();
717   Handle(OpenGl_View) aView   = Handle(OpenGl_View)::DownCast (theView);
718   if (aView.IsNull())
719   {
720     return;
721   }
722
723   if (!myMapOfView.Remove (aView))
724   {
725     return;
726   }
727
728   Handle(OpenGl_Window) aWindow = aView->GlWindow();
729   if (!aWindow.IsNull()
730     && aWindow->GetGlContext()->MakeCurrent())
731   {
732     aCtx = aWindow->GetGlContext();
733   }
734   else
735   {
736     // try to hijack another context if any
737     const Handle(OpenGl_Context)& anOtherCtx = GetSharedContext();
738     if (!anOtherCtx.IsNull()
739       && anOtherCtx != aWindow->GetGlContext())
740     {
741       aCtx = anOtherCtx;
742       aCtx->MakeCurrent();
743     }
744   }
745
746   aView->ReleaseGlResources (aCtx);
747   if (myMapOfView.IsEmpty())
748   {
749     // The last view removed but some objects still present.
750     // Release GL resources now without object destruction.
751     for (NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure);
752          aStructIt.More (); aStructIt.Next())
753     {
754       OpenGl_Structure* aStruct = aStructIt.ChangeValue();
755       aStruct->ReleaseGlResources (aCtx);
756     }
757     myDeviceLostFlag = !myMapOfStructure.IsEmpty();
758   }
759 }
760
761 // =======================================================================
762 // function : Window
763 // purpose  :
764 // =======================================================================
765 Handle(OpenGl_Window) OpenGl_GraphicDriver::CreateRenderWindow (const Handle(Aspect_Window)&  theWindow,
766                                                                 const Aspect_RenderingContext theContext)
767 {
768   Handle(OpenGl_Context) aShareCtx = GetSharedContext();
769   Handle(OpenGl_Window) aWindow = new OpenGl_Window (this, theWindow, theContext, myCaps, aShareCtx);
770   return aWindow;
771 }
772
773 //=======================================================================
774 //function : ViewExists
775 //purpose  :
776 //=======================================================================
777 Standard_Boolean OpenGl_GraphicDriver::ViewExists (const Handle(Aspect_Window)& AWindow, Handle(Graphic3d_CView)& theView)
778 {
779   Standard_Boolean isExist = Standard_False;
780
781   // Parse the list of views to find
782   // a view with the specified window
783
784 #if defined(_WIN32)
785   const Handle(WNT_Window) THEWindow = Handle(WNT_Window)::DownCast (AWindow);
786   Aspect_Handle TheSpecifiedWindowId = THEWindow->HWindow ();
787 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
788   const Handle(Cocoa_Window) THEWindow = Handle(Cocoa_Window)::DownCast (AWindow);
789   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
790     UIView* TheSpecifiedWindowId = THEWindow->HView();
791   #else
792     NSView* TheSpecifiedWindowId = THEWindow->HView();
793   #endif
794 #elif defined(__ANDROID__) || defined(__QNX__)
795   (void )AWindow;
796   int TheSpecifiedWindowId = -1;
797 #else
798   const Handle(Xw_Window) THEWindow = Handle(Xw_Window)::DownCast (AWindow);
799   int TheSpecifiedWindowId = int (THEWindow->XWindow ());
800 #endif
801
802   NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
803   for(; aViewIt.More(); aViewIt.Next())
804   {
805     const Handle(OpenGl_View)& aView = aViewIt.Value();
806     if (aView->IsDefined() && aView->IsActive())
807     {
808       const Handle(Aspect_Window) AspectWindow = aView->Window();
809
810 #if defined(_WIN32)
811       const Handle(WNT_Window) theWindow = Handle(WNT_Window)::DownCast (AspectWindow);
812       Aspect_Handle TheWindowIdOfView = theWindow->HWindow ();
813 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
814       const Handle(Cocoa_Window) theWindow = Handle(Cocoa_Window)::DownCast (AspectWindow);
815       #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
816         UIView* TheWindowIdOfView = theWindow->HView();
817       #else
818         NSView* TheWindowIdOfView = theWindow->HView();
819       #endif
820 #elif defined(__ANDROID__) || defined(__QNX__)
821       int TheWindowIdOfView = 0;
822 #else
823       const Handle(Xw_Window) theWindow = Handle(Xw_Window)::DownCast (AspectWindow);
824       int TheWindowIdOfView = int (theWindow->XWindow ());
825 #endif  // WNT
826       // Comparaison on window IDs
827       if (TheWindowIdOfView == TheSpecifiedWindowId)
828       {
829         isExist = Standard_True;
830         theView = aView;
831       }
832     }
833   }
834
835   return isExist;
836 }