Salome HOME
Merge branch 'master' of newgeom:newgeom.git
[modules/shaper.git] / src / XGUI / XGUI_ViewPort.cpp
1 #ifndef WIN32
2 # ifndef GLX_GLXEXT_LEGACY
3 #  define GLX_GLXEXT_LEGACY
4 # endif
5 # include <GL/glx.h>
6 # include <dlfcn.h>
7 #else
8 # include <windows.h>
9 # include <wingdi.h>
10 #endif
11
12 #include "XGUI_ViewPort.h"
13 #include "XGUI_ViewWindow.h"
14 #include "XGUI_Viewer.h"
15 #include "XGUI_Constants.h"
16
17 #include <QPaintEvent>
18 #include <QPainter>
19 #include <QFileInfo>
20
21 #include <V3d_OrthographicView.hxx>
22 #include <V3d_PerspectiveView.hxx>
23 #include <Visual3d_View.hxx>
24
25 #ifdef WIN32
26 #include <WNT_Window.hxx>
27 #else
28 #include <Xw_Window.hxx>
29 #endif
30
31 #include <GL/gl.h>
32
33 static double rx = 0.;
34 static double ry = 0.;
35 static int sx = 0;
36 static int sy = 0;
37 static Standard_Boolean zRotation = Standard_False;
38
39 /*!
40  Create native view window for CasCade view [ static ]
41  */
42 Handle(Aspect_Window) CreateCasWindow(const Handle(V3d_View)& view, WId winId)
43 {
44   Aspect_Handle aWindowHandle = (Aspect_Handle) winId;
45 #ifdef WIN32
46   Handle(WNT_Window) viewWindow = new WNT_Window(aWindowHandle);
47 #else
48   Handle(Aspect_DisplayConnection) aDispConnection = view->Viewer()->Driver()->GetDisplayConnection();
49   Handle(Xw_Window) viewWindow = new Xw_Window( aDispConnection, aWindowHandle );
50 #endif
51   return viewWindow;
52 }
53
54 class OpenGLUtils_FrameBuffer
55 {
56 public:
57   OpenGLUtils_FrameBuffer();
58   ~OpenGLUtils_FrameBuffer();
59
60   bool init(const GLsizei&, const GLsizei&);
61   void release();
62
63   void bind();
64   void unbind();
65
66 private:
67   GLuint textureId;
68   GLuint fboId;
69   GLuint rboId;
70 };
71
72 #ifndef APIENTRY
73 #define APIENTRY
74 #endif
75 #ifndef APIENTRYP
76 #define APIENTRYP APIENTRY *
77 #endif
78
79 #ifndef GL_FRAMEBUFFER_EXT
80 #define GL_FRAMEBUFFER_EXT                0x8D40
81 #endif
82
83 #ifndef GL_RENDERBUFFER_EXT
84 #define GL_RENDERBUFFER_EXT               0x8D41
85 #endif
86
87 #ifndef GL_COLOR_ATTACHMENT0_EXT
88 #define GL_COLOR_ATTACHMENT0_EXT          0x8CE0
89 #endif
90
91 #ifndef GL_DEPTH_ATTACHMENT_EXT
92 #define GL_DEPTH_ATTACHMENT_EXT           0x8D00
93 #endif
94
95 #ifndef GL_FRAMEBUFFER_COMPLETE_EXT
96 #define GL_FRAMEBUFFER_COMPLETE_EXT       0x8CD5
97 #endif
98
99 typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC)(GLsizei n, GLuint *framebuffers);
100 typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC)(GLenum target, GLuint framebuffer);
101 typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)(GLenum target, GLenum attachment,
102                                                           GLenum textarget, GLuint texture,
103                                                           GLint level);
104 typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)(GLenum target);
105 typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC)(GLsizei n, const GLuint *framebuffers);
106 typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC)(GLsizei n, GLuint *renderbuffers);
107 typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC)(GLenum target, GLuint renderbuffer);
108 typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC)(GLenum target, GLenum internalformat,
109                                                          GLsizei width, GLsizei height);
110 typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)(GLenum target, GLenum attachment,
111                                                              GLenum renderbuffertarget,
112                                                              GLuint renderbuffer);
113 typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC)(GLsizei n, const GLuint *renderbuffers);
114
115 static PFNGLGENFRAMEBUFFERSEXTPROC vglGenFramebuffersEXT = NULL;
116 static PFNGLBINDFRAMEBUFFEREXTPROC vglBindFramebufferEXT = NULL;
117 static PFNGLFRAMEBUFFERTEXTURE2DEXTPROC vglFramebufferTexture2DEXT = NULL;
118 static PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC vglCheckFramebufferStatusEXT = NULL;
119 static PFNGLDELETEFRAMEBUFFERSEXTPROC vglDeleteFramebuffersEXT = NULL;
120 static PFNGLGENRENDERBUFFERSEXTPROC vglGenRenderbuffersEXT = NULL;
121 static PFNGLBINDRENDERBUFFEREXTPROC vglBindRenderbufferEXT = NULL;
122 static PFNGLRENDERBUFFERSTORAGEEXTPROC vglRenderbufferStorageEXT = NULL;
123 static PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC vglFramebufferRenderbufferEXT = NULL;
124 static PFNGLDELETERENDERBUFFERSEXTPROC vglDeleteRenderbuffersEXT = NULL;
125
126 #ifndef WIN32
127 #define GL_GetProcAddress( x ) glXGetProcAddressARB( (const GLubyte*)x )
128 #else
129 #define GL_GetProcAddress( x ) wglGetProcAddress( (const LPCSTR)x )
130 #endif
131
132 bool InitializeEXT()
133 {
134   vglGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) GL_GetProcAddress("glGenFramebuffersEXT");
135   vglBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) GL_GetProcAddress("glBindFramebufferEXT");
136   vglFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) GL_GetProcAddress(
137       "glFramebufferTexture2DEXT");
138   vglCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) GL_GetProcAddress(
139       "glCheckFramebufferStatusEXT");
140   vglDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) GL_GetProcAddress(
141       "glDeleteFramebuffersEXT");
142   vglGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC) GL_GetProcAddress(
143       "glGenRenderbuffersEXT");
144   vglBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC) GL_GetProcAddress(
145       "glBindRenderbufferEXT");
146   vglRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC) GL_GetProcAddress(
147       "glRenderbufferStorageEXT");
148   vglFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) GL_GetProcAddress(
149       "glFramebufferRenderbufferEXT");
150   vglDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC) GL_GetProcAddress(
151       "glDeleteRenderbuffersEXT");
152
153   bool ok = vglGenFramebuffersEXT && vglBindFramebufferEXT && vglFramebufferTexture2DEXT
154       && vglCheckFramebufferStatusEXT && vglDeleteFramebuffersEXT && vglGenRenderbuffersEXT
155       && vglBindRenderbufferEXT && vglRenderbufferStorageEXT && vglFramebufferRenderbufferEXT
156       && vglDeleteRenderbuffersEXT;
157
158   return ok;
159 }
160
161 static bool IsEXTInitialized = InitializeEXT();
162
163 OpenGLUtils_FrameBuffer::OpenGLUtils_FrameBuffer()
164     : textureId(0), fboId(0), rboId(0)
165 {
166 }
167
168 OpenGLUtils_FrameBuffer::~OpenGLUtils_FrameBuffer()
169 {
170   release();
171 }
172
173 bool OpenGLUtils_FrameBuffer::init(const GLsizei& xSize, const GLsizei& ySize)
174 {
175   char* ext = (char*) glGetString(GL_EXTENSIONS);
176   if (!IsEXTInitialized || strstr(ext, "GL_EXT_framebuffer_object") == NULL) {
177     qDebug( "Initializing OpenGL FrameBuffer extension failed");
178     return false;
179   }
180
181   // create a texture object
182   glEnable (GL_TEXTURE_2D);
183   glGenTextures(1, &textureId);
184   glBindTexture(GL_TEXTURE_2D, textureId);
185   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
186   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
187   glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, xSize, ySize, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
188   glBindTexture(GL_TEXTURE_2D, 0);
189
190   // create a renderbuffer object to store depth info
191   vglGenRenderbuffersEXT(1, &rboId);
192   vglBindRenderbufferEXT( GL_RENDERBUFFER_EXT, rboId);
193   vglRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, xSize, ySize);
194   vglBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0);
195
196   // create a framebuffer object
197   vglGenFramebuffersEXT(1, &fboId);
198   vglBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fboId);
199
200   // attach the texture to FBO color attachment point
201   vglFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D,
202                              textureId, 0);
203
204   // attach the renderbuffer to depth attachment point
205   vglFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
206   GL_RENDERBUFFER_EXT,
207                                 rboId);
208
209   // check FBO status
210   GLenum status = vglCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT);
211
212   // Unbind FBO
213   vglBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0);
214
215   return status == GL_FRAMEBUFFER_COMPLETE_EXT;
216 }
217
218 void OpenGLUtils_FrameBuffer::release()
219 {
220   if (!IsEXTInitialized)
221     return;
222
223   glDeleteTextures(1, &textureId);
224   textureId = 0;
225
226   vglDeleteFramebuffersEXT(1, &fboId);
227   fboId = 0;
228
229   vglDeleteRenderbuffersEXT(1, &rboId);
230   rboId = 0;
231 }
232
233 void OpenGLUtils_FrameBuffer::bind()
234 {
235   if (!IsEXTInitialized)
236     return;
237
238   vglBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fboId);
239 }
240
241 void OpenGLUtils_FrameBuffer::unbind()
242 {
243   if (!IsEXTInitialized)
244     return;
245
246   vglBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0);
247 }
248
249 //************************************************************************
250 //************************************************************************
251 //************************************************************************
252 XGUI_ViewPort::XGUI_ViewPort(XGUI_ViewWindow* theParent, const Handle(V3d_Viewer)& theViewer,
253                              V3d_TypeOfView theType)
254     : QWidget(theParent), myPaintersRedrawing(false), myScale(1.0), myIsAdvancedZoomingEnabled(
255         false)
256 {
257   setMouseTracking(true);
258   setBackgroundRole(QPalette::NoRole);
259
260   // set focus policy to threat QContextMenuEvent from keyboard  
261   setFocusPolicy(Qt::StrongFocus);
262   setAttribute(Qt::WA_PaintOnScreen);
263   setAttribute(Qt::WA_NoSystemBackground);
264
265   if (theType == V3d_ORTHOGRAPHIC) {
266     myOrthoView = new V3d_OrthographicView(theViewer);
267     myActiveView = myOrthoView;
268     myPerspView = 0;
269   } else {
270     myPerspView = new V3d_PerspectiveView(theViewer);
271     myActiveView = myPerspView;
272   }
273   myActiveView->SetSurfaceDetail(V3d_TEX_ALL);
274 }
275
276 //***********************************************
277 XGUI_ViewPort::~XGUI_ViewPort()
278 {
279 }
280
281 //***********************************************
282 bool XGUI_ViewPort::mapView(const Handle(V3d_View)& theView)
283 {
284   if (!setWindow(theView))
285     return false;
286
287   if (!mapped(theView)) {
288     theView->SetWindow(myWindow);
289     if (theView != activeView())
290       theView->View()->Deactivate();
291   }
292
293   /* create static trihedron (16551: EDF PAL 501) */
294   //OCCViewer_ViewWindow* aVW = dynamic_cast<OCCViewer_ViewWindow*>( parentWidget()->parentWidget()->parentWidget() );
295   //if ( aVW ) {
296   //    OCCViewer_Viewer* aViewModel = dynamic_cast<OCCViewer_Viewer*>( aVW->getViewManager()->getViewModel() );
297   //    if ( aViewModel && aViewModel->isStaticTrihedronDisplayed() ){
298   //theView->ZBufferTriedronSetup();
299   theView->TriedronDisplay(Aspect_TOTP_LEFT_LOWER, Quantity_NOC_WHITE, 0.05, V3d_ZBUFFER);
300   //    }
301   //}
302
303   emit(vpMapped());
304
305   return true;
306 }
307
308 //***********************************************
309 bool XGUI_ViewPort::setWindow(const Handle(V3d_View)& theView)
310 {
311   if (!myWindow.IsNull())
312     return true;
313
314   if (theView.IsNull())
315     return false;
316
317   attachWindow(theView, CreateCasWindow(theView, winId()));
318
319   myWindow = theView->Window();
320   return !myWindow.IsNull();
321 }
322
323 //***********************************************
324 bool XGUI_ViewPort::mapped(const Handle(V3d_View)& theView) const
325 {
326   return (!theView.IsNull() && theView->View()->IsDefined());
327 }
328
329 //***********************************************
330 void XGUI_ViewPort::updateBackground()
331 {
332   if (activeView().IsNull())
333     return;
334   if (!myBackground.isValid())
335     return;
336
337   // VSR: Important note on below code.
338   // In OCCT (in version 6.5.2), things about the background drawing
339   // are not straightforward and not clearly understandable:
340   // - Horizontal gradient is drawn vertically (!), well ok, from top side to bottom one.
341   // - Vertical gradient is drawn horizontally (!), from right side to left one (!!!).
342   // - First and second diagonal gradients are confused.
343   // - Image texture, once set, can not be removed (!).
344   // - Texture image fill mode Aspect_FM_NONE is not taken into account (and means the same
345   //   as Aspect_FM_CENTERED).
346   // - The only way to cancel gradient background (and get back to single colored) is to
347   //   set gradient background style to Aspect_GFM_NONE while passing two colors is also needed
348   //   (see V3d_View::SetBgGradientColors() function).
349   // - Also, it is impossible to draw texture image above the gradiented background (only above
350   //   single-colored).
351   // In OCCT 6.5.3 all above mentioned problems are fixed; so, above comment should be removed as soon
352   // as SALOME is migrated to OCCT 6.5.3. The same concerns #ifdef statements in the below code
353   switch(myBackground.mode()) {
354   case XGUI::ColorBackground: {
355     QColor c = myBackground.color();
356     if (c.isValid()) {
357       // Unset texture should be done here
358       // ...
359       Quantity_Color qCol(c.red() / 255., c.green() / 255., c.blue() / 255., Quantity_TOC_RGB);
360       activeView()->SetBgGradientStyle(Aspect_GFM_NONE); // cancel gradient background
361       activeView()->SetBgImageStyle(Aspect_FM_NONE); // cancel texture background
362       // then change background color
363       activeView()->SetBackgroundColor(qCol);
364       // update viewer
365       activeView()->Update();
366     }
367     break;
368   }
369   case XGUI::SimpleGradientBackground: {
370     QColor c1, c2;
371     int type = myBackground.gradient(c1, c2);
372     if (c1.isValid() && type >= XGUI::HorizontalGradient && type <= XGUI::LastGradient) {
373       // Unset texture should be done here
374       // ...
375       // Get colors and set-up gradiented background
376       if (!c2.isValid())
377         c2 = c1;
378       Quantity_Color qCol1(c1.red() / 255., c1.green() / 255., c1.blue() / 255., Quantity_TOC_RGB);
379       Quantity_Color qCol2(c2.red() / 255., c2.green() / 255., c2.blue() / 255., Quantity_TOC_RGB);
380       activeView()->SetBgImageStyle(Aspect_FM_NONE); // cancel texture background
381       switch(type) {
382       case XGUI::HorizontalGradient:
383         activeView()->SetBgGradientColors(qCol1, qCol2, Aspect_GFM_HOR,
384         Standard_True);
385         break;
386       case XGUI::VerticalGradient:
387         activeView()->SetBgGradientColors(qCol1, qCol2, Aspect_GFM_VER,
388         Standard_True);
389         break;
390       case XGUI::Diagonal1Gradient:
391         activeView()->SetBgGradientColors(qCol1, qCol2, Aspect_GFM_DIAG1,
392         Standard_True);
393         break;
394       case XGUI::Diagonal2Gradient:
395         activeView()->SetBgGradientColors(qCol1, qCol2, Aspect_GFM_DIAG2,
396         Standard_True);
397         break;
398       case XGUI::Corner1Gradient:
399         activeView()->SetBgGradientColors(qCol1, qCol2, Aspect_GFM_CORNER1,
400         Standard_True);
401         break;
402       case XGUI::Corner2Gradient:
403         activeView()->SetBgGradientColors(qCol1, qCol2, Aspect_GFM_CORNER2,
404         Standard_True);
405         break;
406       case XGUI::Corner3Gradient:
407         activeView()->SetBgGradientColors(qCol1, qCol2, Aspect_GFM_CORNER3,
408         Standard_True);
409         break;
410       case XGUI::Corner4Gradient:
411         activeView()->SetBgGradientColors(qCol1, qCol2, Aspect_GFM_CORNER4,
412         Standard_True);
413         break;
414       default:
415         break;
416       }
417     }
418     break;
419   }
420   case XGUI::CustomGradientBackground:
421     // NOT IMPLEMENTED YET
422     break;
423   default:
424     break;
425   }
426   // VSR: In OCCT before v6.5.3 below code can't be used because of very ugly bug - it has been impossible to
427   // clear the background texture image as soon as it was once set to the viewer.
428   if (myBackground.isTextureShown()) {
429     QString fileName;
430     int textureMode = myBackground.texture(fileName);
431     QFileInfo fi(fileName);
432     if (!fileName.isEmpty() && fi.exists()) {
433       // set texture image: file name and fill mode
434       switch(textureMode) {
435       case XGUI::CenterTexture:
436         activeView()->SetBackgroundImage(fi.absoluteFilePath().toLatin1().constData(),
437                                          Aspect_FM_CENTERED);
438         break;
439       case XGUI::TileTexture:
440         activeView()->SetBackgroundImage(fi.absoluteFilePath().toLatin1().constData(),
441                                          Aspect_FM_TILED);
442         break;
443       case XGUI::StretchTexture:
444         activeView()->SetBackgroundImage(fi.absoluteFilePath().toLatin1().constData(),
445                                          Aspect_FM_STRETCH);
446         break;
447       default:
448         break;
449       }
450       activeView()->Update();
451     }
452   }
453 }
454
455 //***********************************************
456 void XGUI_ViewPort::attachWindow(const Handle(V3d_View)& theView,
457                                  const Handle(Aspect_Window)& theWnd)
458 {
459   if (!theView.IsNull()) {
460     theView->SetWindow(theWnd);
461     updateBackground();
462   }
463 }
464
465 //***********************************************
466 void XGUI_ViewPort::paintEvent(QPaintEvent* theEvent)
467 {
468 #ifndef WIN32
469   /* X11 : map before show doesn't work */
470   if ( !mapped( activeView() ) )
471   mapView( activeView() );
472 #endif
473   if (!myWindow.IsNull()) {
474     //QGuiApplication::sync();
475     QRect rc = theEvent->rect();
476     //if ( !myPaintersRedrawing ) {
477     //activeView()->Redraw();
478     activeView()->Redraw(rc.x(), rc.y(), rc.width(), rc.height());
479     emit vpUpdated();
480     //}
481   }
482   //if ( myPaintersRedrawing ) {
483   //    QPainter p( this );
484   //    //emit vpDrawExternal( &p );
485   //    myPaintersRedrawing = false;
486   //}
487 }
488
489 //***********************************************
490 void XGUI_ViewPort::resizeEvent(QResizeEvent*)
491 {
492 #ifdef WIN32
493   /* Win32 : map before first show to avoid flicker */
494   if (!mapped(activeView()))
495     mapView(activeView());
496 #endif
497   //QGuiApplication::sync();
498   if (!activeView().IsNull())
499     activeView()->MustBeResized();
500 }
501
502 //***********************************************
503 QImage XGUI_ViewPort::dumpView(QRect theRect, bool toUpdate)
504 {
505   Handle(V3d_View) view = getView();
506   if (view.IsNull())
507     return QImage();
508
509   int aWidth;
510   int aHeight;
511   if (theRect.isNull()) {
512     aWidth = width();
513     aHeight = height();
514   } else {
515     aWidth = theRect.width();
516     aHeight = theRect.height();
517   }
518   //QApplication::syncX();
519
520   OpenGLUtils_FrameBuffer aFrameBuffer;
521   if (aFrameBuffer.init(aWidth, aHeight)) {
522     QImage anImage(aWidth, aHeight, QImage::Format_RGB32);
523
524     glPushAttrib (GL_VIEWPORT_BIT);
525     glViewport(0, 0, aWidth, aHeight);
526     aFrameBuffer.bind();
527
528     // draw scene
529     if (toUpdate) {
530       if (theRect.isNull())
531         view->Redraw();
532       else
533         view->Redraw(theRect.x(), theRect.y(), theRect.width(), theRect.height());
534     }
535     aFrameBuffer.unbind();
536     glPopAttrib();
537
538     aFrameBuffer.bind();
539     if (theRect.isNull())
540       glReadPixels(0, 0, aWidth, aHeight, GL_RGBA, GL_UNSIGNED_BYTE, anImage.bits());
541     else
542       glReadPixels(theRect.x(), theRect.y(), aWidth, aHeight, GL_RGBA, GL_UNSIGNED_BYTE,
543                    anImage.bits());
544     aFrameBuffer.unbind();
545
546     anImage = anImage.rgbSwapped();
547     anImage = anImage.mirrored();
548     return anImage;
549   }
550   // if frame buffers are unsupported, use old functionality
551   unsigned char* data = new unsigned char[aWidth * aHeight * 4];
552
553   QPoint p;
554   if (theRect.isNull()) {
555     if (toUpdate)
556       view->Redraw();
557     p = mapFromParent(geometry().topLeft());
558   } else {
559     if (toUpdate)
560       view->Redraw(theRect.x(), theRect.y(), theRect.width(), theRect.height());
561     p = theRect.topLeft();
562   }
563   glReadPixels(p.x(), p.y(), aWidth, aHeight, GL_RGBA, GL_UNSIGNED_BYTE, data);
564
565   QImage anImage(data, aWidth, aHeight, QImage::Format_ARGB32);
566   anImage = anImage.mirrored();
567   anImage = anImage.rgbSwapped();
568   return anImage;
569 }
570
571 /*!
572  Inits 'rotation' transformation.
573  */
574 void XGUI_ViewPort::startRotation(int x, int y, int theRotationPointType,
575                                   const gp_Pnt& theSelectedPoint)
576 {
577   if (!activeView().IsNull()) {
578     switch(theRotationPointType) {
579     case XGUI::GRAVITY:
580       activeView()->StartRotation(x, y, 0.45);
581       break;
582     case XGUI::SELECTED:
583       sx = x;
584       sy = y;
585
586       double X, Y;
587       activeView()->Size(X, Y);
588       rx = Standard_Real(activeView()->Convert(X));
589       ry = Standard_Real(activeView()->Convert(Y));
590
591       activeView()->Rotate(0., 0., 0., theSelectedPoint.X(), theSelectedPoint.Y(),
592                            theSelectedPoint.Z(),
593                            Standard_True);
594
595       Quantity_Ratio zRotationThreshold;
596       zRotation = Standard_False;
597       zRotationThreshold = 0.45;
598       if (zRotationThreshold > 0.) {
599         Standard_Real dx = Abs(sx - rx / 2.);
600         Standard_Real dy = Abs(sy - ry / 2.);
601         Standard_Real dd = zRotationThreshold * (rx + ry) / 2.;
602         if (dx > dd || dy > dd)
603           zRotation = Standard_True;
604       }
605       break;
606     default:
607       break;
608     }
609     activeView()->DepthFitAll();
610   }
611 }
612
613 /*!
614  Rotates the viewport. 
615  */
616 void XGUI_ViewPort::rotate(int x, int y, int theRotationPointType, const gp_Pnt& theSelectedPoint)
617 {
618   if (!activeView().IsNull()) {
619     switch(theRotationPointType) {
620     case XGUI::GRAVITY:
621       activeView()->Rotation(x, y);
622       break;
623     case XGUI::SELECTED:
624       double dx, dy, dz;
625       if (zRotation) {
626         dz = atan2(Standard_Real(x) - rx / 2., ry / 2. - Standard_Real(y))
627             - atan2(sx - rx / 2., ry / 2. - sy);
628         dx = dy = 0.;
629       } else {
630         dx = (Standard_Real(x) - sx) * M_PI / rx;
631         dy = (sy - Standard_Real(y)) * M_PI / ry;
632         dz = 0.;
633       }
634
635       activeView()->Rotate(dx, dy, dz, theSelectedPoint.X(), theSelectedPoint.Y(),
636                            theSelectedPoint.Z(),
637                            Standard_False);
638       break;
639     default:
640       break;
641     }
642     emit vpTransformed();
643   }
644   //  setZSize( getZSize() );
645 }
646
647 /*!
648  Resets the viewport after 'rotation'. 
649  */
650 void XGUI_ViewPort::endRotation()
651 {
652   if (!activeView().IsNull()) {
653     activeView()->ZFitAll(1.);
654     activeView()->SetZSize(0.);
655     activeView()->Update();
656     emit vpTransformed();
657   }
658 }
659
660 /*!
661  Inits 'zoom' transformation.
662  */
663 void XGUI_ViewPort::startZoomAtPoint(int x, int y)
664 {
665   if (!activeView().IsNull()/* && isAdvancedZoomingEnabled() */)
666     activeView()->StartZoomAtPoint(x, y);
667 }
668
669 /*!
670  Centers the viewport. 
671  */
672 void XGUI_ViewPort::setCenter(int x, int y)
673 {
674   if (!activeView().IsNull()) {
675     activeView()->Place(x, y, myScale);
676     emit vpTransformed();
677   }
678 }
679
680 /*!
681  Called at 'pan' transformation. 
682  */
683 void XGUI_ViewPort::pan(int dx, int dy)
684 {
685   if (!activeView().IsNull()) {
686     activeView()->Pan(dx, dy, 1.0);
687     emit vpTransformed();
688   }
689 }
690
691 /*!
692  Called at 'window fit' transformation.
693  */
694 void XGUI_ViewPort::fitRect(const QRect& rect)
695 {
696   if (!activeView().IsNull()) {
697     activeView()->WindowFit(rect.left(), rect.top(), rect.right(), rect.bottom());
698     emit vpTransformed();
699   }
700 }
701
702 /*!
703  Called at 'zoom' transformation.
704  */
705 void XGUI_ViewPort::zoom(int x0, int y0, int x, int y)
706 {
707   if (!activeView().IsNull()) {
708     if (isAdvancedZoomingEnabled())
709       activeView()->ZoomAtPoint(x0, y0, x, y);
710     else
711       activeView()->Zoom(x0 + y0, 0, x + y, 0);
712     emit vpTransformed();
713   }
714 }
715
716 /*!
717  Sets the background data
718  */
719 void XGUI_ViewPort::setBackground(const XGUI_ViewBackground& bgData)
720 {
721   if (bgData.isValid()) {
722     myBackground = bgData;
723     updateBackground();
724     emit vpChangeBackground(myBackground);
725   }
726 }
727
728 void XGUI_ViewPort::fitAll(bool theKeepScale, bool theWithZ, bool theUpd)
729 {
730   if ( activeView().IsNull() )
731     return;
732
733   if ( theKeepScale )
734     myScale = activeView()->Scale();
735
736   Standard_Real aMargin = 0.01;
737   activeView()->FitAll( aMargin, theWithZ, theUpd );
738   activeView()->SetZSize(0.);
739   emit vpTransformed( );
740 }
741
742 void XGUI_ViewPort::syncronizeWith( const XGUI_ViewPort* ref )
743 {
744   Handle(V3d_View) refView = ref->getView();
745   Handle(V3d_View) tgtView = getView();
746
747   /*  The following params are copied:
748       - view type( ortho/persp )
749       - position of view point
750       - orientation of high point
751       - position of the eye
752       - projection vector
753       - view center ( 2D )
754       - view twist
755       - view scale
756   */
757
758   /* we'll update after setting all params */
759   tgtView->SetImmediateUpdate( Standard_False );
760
761   /* perspective */
762   if ( refView->Type() == V3d_PERSPECTIVE )
763     tgtView->SetFocale( refView->Focale() );
764
765   /* copy params */
766   Standard_Real x, y, z;
767   refView->At( x, y, z ); tgtView->SetAt( x, y, z );
768   refView->Up( x, y, z ); tgtView->SetUp( x, y, z );
769   refView->Eye( x, y, z ); tgtView->SetEye( x, y, z );
770   refView->Proj( x, y, z ); tgtView->SetProj( x, y, z );
771   refView->Center( x, y ); tgtView->SetCenter( x, y );
772   tgtView->SetScale( refView->Scale() );
773   tgtView->SetTwist( refView->Twist() );
774
775   /* update */
776   tgtView->Update();
777   tgtView->SetImmediateUpdate( Standard_True );
778 }