0024070: OpenGL capped object-level clipping planes
[occt.git] / src / OpenGl / OpenGl_Workspace.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_GlCore15.hxx>
21
22 #include <InterfaceGraphic.hxx>
23
24 #include <OpenGl_AspectLine.hxx>
25 #include <OpenGl_AspectFace.hxx>
26 #include <OpenGl_AspectMarker.hxx>
27 #include <OpenGl_AspectText.hxx>
28 #include <OpenGl_Context.hxx>
29 #include <OpenGl_FrameBuffer.hxx>
30 #include <OpenGl_Texture.hxx>
31 #include <OpenGl_Workspace.hxx>
32 #include <OpenGl_Element.hxx>
33
34 #include <Graphic3d_TextureParams.hxx>
35
36 #if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
37   #include <OpenGl_AVIWriter.hxx>
38 #endif
39
40 IMPLEMENT_STANDARD_HANDLE(OpenGl_Workspace,OpenGl_Window)
41 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Workspace,OpenGl_Window)
42
43 namespace
44 {
45   static const TEL_COLOUR myDefaultHighlightColor = { { 1.F, 1.F, 1.F, 1.F } };
46
47   static const OpenGl_AspectLine myDefaultAspectLine;
48   static const OpenGl_AspectFace myDefaultAspectFace;
49   static const OpenGl_AspectMarker myDefaultAspectMarker;
50   static const OpenGl_AspectText myDefaultAspectText;
51
52   static const OpenGl_TextParam myDefaultTextParam =
53   {
54     16, Graphic3d_HTA_LEFT, Graphic3d_VTA_BOTTOM
55   };
56
57   static const OpenGl_Matrix myDefaultMatrix =
58   {
59     {{ 1.0F, 0.0F, 0.0F, 0.0F },
60      { 0.0F, 1.0F, 0.0F, 0.0F },
61      { 0.0F, 0.0F, 1.0F, 0.0F },
62      { 0.0F, 0.0F, 0.0F, 1.0F }}
63   };
64
65 };
66
67 // =======================================================================
68 // function : OpenGl_Workspace
69 // purpose  :
70 // =======================================================================
71 OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_Display)& theDisplay,
72                                     const CALL_DEF_WINDOW&        theCWindow,
73                                     Aspect_RenderingContext       theGContext,
74                                     const Handle(OpenGl_Caps)&    theCaps,
75                                     const Handle(OpenGl_Context)& theShareCtx)
76 : OpenGl_Window (theDisplay, theCWindow, theGContext, theCaps, theShareCtx),
77   NamedStatus (0),
78   HighlightColor (&myDefaultHighlightColor),
79   //
80   myIsTransientOpen (Standard_False),
81   myRetainMode (Standard_False),
82   myTransientDrawToFront (Standard_True),
83   myUseTransparency (Standard_False),
84   myUseZBuffer (Standard_False),
85   myUseDepthTest (Standard_True),
86   myUseGLLight (Standard_True),
87   myBackBufferRestored (Standard_False),
88   //
89   AspectLine_set (&myDefaultAspectLine),
90   AspectLine_applied (NULL),
91   AspectFace_set (&myDefaultAspectFace),
92   AspectFace_applied (NULL),
93   AspectMarker_set (&myDefaultAspectMarker),
94   AspectMarker_applied (NULL),
95   AspectText_set (&myDefaultAspectText),
96   AspectText_applied (NULL),
97   TextParam_set (&myDefaultTextParam),
98   TextParam_applied (NULL),
99   ViewMatrix_applied (&myDefaultMatrix),
100   StructureMatrix_applied (&myDefaultMatrix),
101   PolygonOffset_applied (NULL)
102 {
103   theDisplay->InitAttributes();
104
105   // General initialization of the context
106
107   // Eviter d'avoir les faces mal orientees en noir.
108   // Pourrait etre utiliser pour detecter les problemes d'orientation
109   glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
110
111   // Optimisation pour le Fog et l'antialiasing
112   glHint (GL_FOG_HINT,            GL_FASTEST);
113   glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
114   glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
115   glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
116
117   // Polygon Offset
118   EnablePolygonOffset();
119 }
120
121 // =======================================================================
122 // function : SetImmediateModeDrawToFront
123 // purpose  :
124 // =======================================================================
125 Standard_Boolean OpenGl_Workspace::SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer)
126 {
127   const Standard_Boolean aPrevMode = myTransientDrawToFront;
128   myTransientDrawToFront = theDrawToFrontBuffer;
129   return aPrevMode;
130 }
131
132 // =======================================================================
133 // function : ~OpenGl_Workspace
134 // purpose  :
135 // =======================================================================
136 OpenGl_Workspace::~OpenGl_Workspace()
137 {
138 }
139
140 // =======================================================================
141 // function : Activate
142 // purpose  :
143 // =======================================================================
144 Standard_Boolean OpenGl_Workspace::Activate()
145 {
146   if (!OpenGl_Window::Activate())
147     return Standard_False;
148
149   ViewMatrix_applied      = &myDefaultMatrix;
150   StructureMatrix_applied = &myDefaultMatrix;
151
152   ResetAppliedAspect();
153
154   return Standard_True;
155 }
156
157 // =======================================================================
158 // function : UseTransparency
159 // purpose  : call_togl_transparency
160 // =======================================================================
161 void OpenGl_Workspace::UseTransparency (const Standard_Boolean theFlag)
162 {
163   myUseTransparency = theFlag;
164 }
165
166 //=======================================================================
167 //function : ResetAppliedAspect
168 //purpose  : Sets default values of GL parameters in accordance with default aspects
169 //=======================================================================
170 void OpenGl_Workspace::ResetAppliedAspect()
171 {
172   NamedStatus           = !myTextureBound.IsNull() ? OPENGL_NS_TEXTURE : 0;
173   HighlightColor        = &myDefaultHighlightColor;
174   AspectLine_set        = &myDefaultAspectLine;
175   AspectLine_applied    = NULL;
176   AspectFace_set        = &myDefaultAspectFace;
177   AspectFace_applied    = NULL;
178   AspectMarker_set      = &myDefaultAspectMarker;
179   AspectMarker_applied  = NULL;
180   AspectText_set        = &myDefaultAspectText;
181   AspectText_applied    = NULL;
182   TextParam_set         = &myDefaultTextParam;
183   TextParam_applied     = NULL;
184   PolygonOffset_applied = NULL;
185
186   AspectLine(Standard_True);
187   AspectFace(Standard_True);
188   AspectMarker(Standard_True);
189   AspectText(Standard_True);
190 }
191
192 // =======================================================================
193 // function : DisableTexture
194 // purpose  :
195 // =======================================================================
196 Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
197 {
198   if (myTextureBound.IsNull())
199   {
200     return myTextureBound;
201   }
202
203   // reset texture matrix because some code may expect it is identity
204   GLint aMatrixMode = GL_TEXTURE;
205   glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
206   glMatrixMode (GL_TEXTURE);
207   glLoadIdentity();
208   glMatrixMode (aMatrixMode);
209
210   myTextureBound->Unbind (myGlContext);
211   switch (myTextureBound->GetTarget())
212   {
213     case GL_TEXTURE_1D:
214     {
215       if (myTextureBound->GetParams()->GenMode() != GL_NONE)
216       {
217         glDisable (GL_TEXTURE_GEN_S);
218       }
219       glDisable (GL_TEXTURE_1D);
220       break;
221     }
222     case GL_TEXTURE_2D:
223     {
224       if (myTextureBound->GetParams()->GenMode() != GL_NONE)
225       {
226         glDisable (GL_TEXTURE_GEN_S);
227         glDisable (GL_TEXTURE_GEN_T);
228         if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
229         {
230           glDisable (GL_POINT_SPRITE);
231         }
232       }
233       glDisable (GL_TEXTURE_2D);
234       break;
235     }
236     default: break;
237   }
238
239   Handle(OpenGl_Texture) aPrevTexture = myTextureBound;
240   myTextureBound.Nullify();
241   return aPrevTexture;
242 }
243
244 // =======================================================================
245 // function : setTextureParams
246 // purpose  :
247 // =======================================================================
248 void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&                theTexture,
249                                          const Handle(Graphic3d_TextureParams)& theParams)
250 {
251   const Handle(Graphic3d_TextureParams)& aParams = theParams.IsNull() ? theTexture->GetParams() : theParams;
252   if (aParams.IsNull())
253   {
254     return;
255   }
256
257   GLint aMatrixMode = GL_TEXTURE;
258   glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
259
260   // setup texture matrix
261   glMatrixMode (GL_TEXTURE);
262   glLoadIdentity();
263   const Graphic3d_Vec2& aScale = aParams->Scale();
264   const Graphic3d_Vec2& aTrans = aParams->Translation();
265   glScalef     ( aScale.x(),  aScale.y(), 1.0f);
266   glTranslatef (-aTrans.x(), -aTrans.y(), 0.0f);
267   glRotatef (-aParams->Rotation(), 0.0f, 0.0f, 1.0f);
268
269   // setup generation of texture coordinates
270   switch (aParams->GenMode())
271   {
272     case Graphic3d_TOTM_OBJECT:
273     {
274       glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
275       glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
276       if (theTexture->GetTarget() != GL_TEXTURE_1D)
277       {
278         glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
279         glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
280       }
281       break;
282     }
283     case Graphic3d_TOTM_SPHERE:
284     {
285       glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
286       if (theTexture->GetTarget() != GL_TEXTURE_1D)
287       {
288         glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
289       }
290       break;
291     }
292     case Graphic3d_TOTM_EYE:
293     {
294       glMatrixMode (GL_MODELVIEW);
295       glPushMatrix();
296       glLoadIdentity();
297
298       glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
299       glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
300
301       if (theTexture->GetTarget() != GL_TEXTURE_1D)
302       {
303         glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
304         glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
305       }
306       glPopMatrix();
307       break;
308     }
309     case Graphic3d_TOTM_SPRITE:
310     {
311       if (GetGlContext()->core20 != NULL)
312       {
313         glEnable  (GL_POINT_SPRITE);
314         glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
315         glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
316         GetGlContext()->core15->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
317       }
318       break;
319     }
320     case Graphic3d_TOTM_MANUAL:
321     default: break;
322   }
323
324   // setup lighting
325   if (aParams->GenMode() != Graphic3d_TOTM_SPRITE)
326   {
327     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aParams->IsModulate() ? GL_MODULATE : GL_DECAL);
328   }
329
330   // setup texture filtering and wrapping
331   //if (theTexture->GetParams() != theParams)
332   const GLenum aFilter   = (aParams->Filter() == Graphic3d_TOTF_NEAREST) ? GL_NEAREST : GL_LINEAR;
333   const GLenum aWrapMode = aParams->IsRepeat() ? GL_REPEAT : GL_CLAMP;
334   switch (theTexture->GetTarget())
335   {
336     case GL_TEXTURE_1D:
337     {
338       glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, aFilter);
339       glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, aFilter);
340       glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_WRAP_S,     aWrapMode);
341       break;
342     }
343     case GL_TEXTURE_2D:
344     {
345       GLenum aFilterMin = aFilter;
346       if (theTexture->HasMipmaps())
347       {
348         aFilterMin = GL_NEAREST_MIPMAP_NEAREST;
349         if (aParams->Filter() == Graphic3d_TOTF_BILINEAR)
350         {
351           aFilterMin = GL_LINEAR_MIPMAP_NEAREST;
352         }
353         else if (aParams->Filter() == Graphic3d_TOTF_TRILINEAR)
354         {
355           aFilterMin = GL_LINEAR_MIPMAP_LINEAR;
356         }
357
358         if (myGlContext->extAnis)
359         {
360           // setup degree of anisotropy filter
361           const GLint aMaxDegree = myGlContext->MaxDegreeOfAnisotropy();
362           switch (aParams->AnisoFilter())
363           {
364             case Graphic3d_LOTA_QUALITY:
365             {
366               glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aMaxDegree);
367               break;
368             }
369             case Graphic3d_LOTA_MIDDLE:
370             {
371
372               glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (aMaxDegree <= 4) ? 2 : (aMaxDegree / 2));
373               break;
374             }
375             case Graphic3d_LOTA_FAST:
376             {
377               glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 2);
378               break;
379             }
380             case Graphic3d_LOTA_OFF:
381             default:
382             {
383               glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1);
384               break;
385             }
386           }
387         }
388       }
389       glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterMin);
390       glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilter);
391       glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,     aWrapMode);
392       glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,     aWrapMode);
393       break;
394     }
395     default: break;
396   }
397
398   switch (theTexture->GetTarget())
399   {
400     case GL_TEXTURE_1D:
401     {
402       if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
403       {
404         glEnable (GL_TEXTURE_GEN_S);
405       }
406       glEnable (GL_TEXTURE_1D);
407       break;
408     }
409     case GL_TEXTURE_2D:
410     {
411       if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
412       {
413         glEnable (GL_TEXTURE_GEN_S);
414         glEnable (GL_TEXTURE_GEN_T);
415       }
416       glEnable (GL_TEXTURE_2D);
417       break;
418     }
419     default: break;
420   }
421
422   glMatrixMode (aMatrixMode); // turn back active matrix
423   theTexture->SetParams (aParams);
424 }
425
426 // =======================================================================
427 // function : EnableTexture
428 // purpose  :
429 // =======================================================================
430 Handle(OpenGl_Texture) OpenGl_Workspace::EnableTexture (const Handle(OpenGl_Texture)&          theTexture,
431                                                         const Handle(Graphic3d_TextureParams)& theParams)
432 {
433   if (theTexture.IsNull() || !theTexture->IsValid())
434   {
435     return DisableTexture();
436   }
437
438   if (myTextureBound == theTexture
439    && (theParams.IsNull() || theParams == theTexture->GetParams()))
440   {
441     // already bound
442     return myTextureBound;
443   }
444
445   Handle(OpenGl_Texture) aPrevTexture = DisableTexture();
446   myTextureBound = theTexture;
447   myTextureBound->Bind (myGlContext);
448   setTextureParams (myTextureBound, theParams);
449
450   return aPrevTexture;
451 }
452
453 // =======================================================================
454 // function : Redraw
455 // purpose  :
456 // =======================================================================
457 void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
458                                const Aspect_CLayer2d& theCUnderLayer,
459                                const Aspect_CLayer2d& theCOverLayer)
460 {
461   if (!Activate())
462   {
463     return;
464   }
465
466   // release pending GL resources
467   Handle(OpenGl_Context) aGlCtx = GetGlContext();
468   aGlCtx->ReleaseDelayed();
469
470   // cache render mode state
471   GLint aRendMode = GL_RENDER;
472   glGetIntegerv (GL_RENDER_MODE,  &aRendMode);
473   aGlCtx->SetFeedback (aRendMode == GL_FEEDBACK);
474
475   Tint toSwap = (aRendMode == GL_RENDER); // swap buffers
476   GLint aViewPortBack[4];
477   OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )theCView.ptrFBO;
478   if (aFrameBuffer != NULL)
479   {
480     glGetIntegerv (GL_VIEWPORT, aViewPortBack);
481     aFrameBuffer->SetupViewport();
482     aFrameBuffer->BindBuffer (aGlCtx);
483     toSwap = 0; // no need to swap buffers
484   }
485
486   Redraw1 (theCView, theCUnderLayer, theCOverLayer, toSwap);
487   if (aFrameBuffer == NULL || !myTransientDrawToFront)
488   {
489     RedrawImmediatMode();
490   }
491
492   if (aFrameBuffer != NULL)
493   {
494     aFrameBuffer->UnbindBuffer (aGlCtx);
495     // move back original viewport
496     glViewport (aViewPortBack[0], aViewPortBack[1], aViewPortBack[2], aViewPortBack[3]);
497   }
498
499 #if (defined(_WIN32) || defined(__WIN32__)) && defined(HAVE_VIDEOCAPTURE)
500   if (OpenGl_AVIWriter_AllowWriting (theCView.DefWindow.XWindow))
501   {
502     GLint params[4];
503     glGetIntegerv (GL_VIEWPORT, params);
504     int nWidth  = params[2] & ~0x7;
505     int nHeight = params[3] & ~0x7;
506
507     const int nBitsPerPixel = 24;
508     GLubyte* aDumpData = new GLubyte[nWidth * nHeight * nBitsPerPixel / 8];
509
510     glPixelStorei (GL_PACK_ALIGNMENT, 1);
511     glReadPixels (0, 0, nWidth, nHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, aDumpData);
512     OpenGl_AVIWriter_AVIWriter (aDumpData, nWidth, nHeight, nBitsPerPixel);
513     delete[] aDumpData;
514   }
515 #endif
516
517   // reset render mode state
518   aGlCtx->SetFeedback (Standard_False);
519 }