Salome HOME
Copyrights update 2015.
[modules/gui.git] / src / OCCViewer / OCCViewer_ViewModel.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 #include "OCCViewer_ViewModel.h"
24 #include "OCCViewer_ViewWindow.h"
25 #include "OCCViewer_ViewFrame.h"
26 #include "OCCViewer_VService.h"
27 #include "OCCViewer_ViewPort3d.h"
28 #include "OCCViewer_ClippingDlg.h"
29 #include "OCCViewer_Utilities.h"
30
31 #include "SUIT_ViewWindow.h"
32 #include "SUIT_ViewManager.h"
33 #include "SUIT_Desktop.h"
34 #include "SUIT_Session.h"
35 #include "SUIT_ResourceMgr.h"
36
37 #include "ViewerData_AISShape.hxx"
38
39 #include <Basics_OCCTVersion.hxx>
40
41 #include "QtxActionToolMgr.h"
42 #include "QtxBackgroundTool.h"
43
44 #include <QPainter>
45 #include <QApplication>
46 #include <QColorDialog>
47 #include <QFileDialog>
48 #include <QPalette>
49 #include <QKeyEvent>
50 #include <QMenu>
51 #include <QMouseEvent>
52 #include <QToolBar>
53 #include <QDesktopWidget>
54
55 #include <AIS_Axis.hxx>
56 #include <AIS_Drawer.hxx>
57 #include <AIS_ListOfInteractive.hxx>
58 #include <AIS_ListIteratorOfListOfInteractive.hxx>
59
60 #include <Graphic3d_Texture2Dmanual.hxx>
61 #include <Graphic3d_MaterialAspect.hxx>
62 #include <Graphic3d_TextureParams.hxx>
63
64 #include <Geom_Axis2Placement.hxx>
65 #include <Prs3d_Drawer.hxx>
66 #include <Prs3d_DatumAspect.hxx>
67 #include <Prs3d_LineAspect.hxx>
68 #include <Prs3d_TextAspect.hxx>
69
70 #include <Visual3d_View.hxx>
71
72 /*!
73   Get data for supported background modes: gradient types, identifiers and supported image formats
74 */
75 QString OCCViewer_Viewer::backgroundData( QStringList& gradList, QIntList& idList, QIntList& txtList )
76 {
77   gradList << tr("GT_HORIZONTALGRADIENT")    << tr("GT_VERTICALGRADIENT")       <<
78               tr("GT_FIRSTDIAGONALGRADIENT") << tr("GT_SECONDDIAGONALGRADIENT") <<
79               tr("GT_FIRSTCORNERGRADIENT")   << tr("GT_SECONDCORNERGRADIENT")   <<
80               tr("GT_THIRDCORNERGRADIENT")   << tr("GT_FORTHCORNERGRADIENT");
81   idList   << HorizontalGradient             << VerticalGradient  <<
82               Diagonal1Gradient              << Diagonal2Gradient <<
83               Corner1Gradient                << Corner2Gradient   <<
84               Corner3Gradient                << Corner4Gradient;
85   txtList  << Qtx::CenterTexture << Qtx::TileTexture << Qtx::StretchTexture;
86   return tr("BG_IMAGE_FILES");
87 }
88
89 /*!
90   Constructor
91   \param DisplayTrihedron - is trihedron displayed
92 */
93 OCCViewer_Viewer::OCCViewer_Viewer( bool DisplayTrihedron)
94 : SUIT_ViewModel(),
95   myBackgrounds(4, Qtx::BackgroundData( Qt::black )),
96   myIsRelative(true),
97   myTopLayerId( 0 ),
98   myTrihedronSize(100),
99   myClippingDlg (NULL)
100 {
101   // init CasCade viewers
102   myV3dViewer = OCCViewer_VService::CreateViewer( TCollection_ExtendedString("Viewer3d").ToExtString() );
103   //myV3dViewer->Init(); // to avoid creation of the useless perspective view (see OCCT issue 0024267)
104   myV3dViewer->SetDefaultLights();
105
106   // init selector
107   myAISContext = new AIS_InteractiveContext( myV3dViewer );
108   myAISContext->SelectionColor( Quantity_NOC_WHITE );
109   
110   // display isoline on planar faces (box for ex.)
111   myAISContext->IsoOnPlane( true );
112   
113   /* create trihedron */
114   if ( DisplayTrihedron )
115   {
116     Handle(Geom_Axis2Placement) anAxis = new Geom_Axis2Placement(gp::XOY());
117     myTrihedron = new AIS_Trihedron(anAxis);
118     myTrihedron->SetInfiniteState( Standard_True );
119
120     Quantity_Color Col(193/255., 205/255., 193/255., Quantity_TOC_RGB);
121     //myTrihedron->SetColor( Col );
122     myTrihedron->SetArrowColor( Col.Name() );
123     myTrihedron->SetSize(100);
124     Handle(AIS_Drawer) drawer = myTrihedron->Attributes();
125     if (drawer->HasDatumAspect()) {
126       Handle(Prs3d_DatumAspect) daspect = drawer->DatumAspect();
127       daspect->FirstAxisAspect()->SetColor(Quantity_Color(1.0, 0.0, 0.0, Quantity_TOC_RGB));
128       daspect->SecondAxisAspect()->SetColor(Quantity_Color(0.0, 1.0, 0.0, Quantity_TOC_RGB));
129       daspect->ThirdAxisAspect()->SetColor(Quantity_Color(0.0, 0.0, 1.0, Quantity_TOC_RGB));
130     }
131   }
132
133   // set interaction style to standard
134   myInteractionStyle = 0;
135
136   // set zooming style to standard
137   myZoomingStyle = 0;
138
139   // preselection
140   myPreselectionEnabled = true;
141
142   // selection
143   mySelectionEnabled = true;
144   myMultiSelectionEnabled = true;
145
146   //set clipping color and texture to standard
147   myClippingColor = QColor( 50, 50, 50 );
148   myDefaultTextureUsed = true;
149   myClippingTexture = QString();
150   myTextureModulated = true;
151   myClippingTextureScale = 1.0;
152
153 }
154
155 /*!
156   Destructor
157 */
158 OCCViewer_Viewer::~OCCViewer_Viewer() 
159 {
160   myAISContext.Nullify();
161   myV3dViewer.Nullify();
162 }
163
164 /*!
165   [obsolete]
166   \return background color of viewer
167 */
168 QColor OCCViewer_Viewer::backgroundColor() const
169 {
170   return backgroundColor(0);
171 }
172
173 /*!
174   \return background data of viewer
175 */
176 Qtx::BackgroundData OCCViewer_Viewer::background() const
177 {
178   return background(0);
179 }
180
181 /*!
182   Sets background color [obsolete]
183   \param c - new background color
184 */
185 void OCCViewer_Viewer::setBackgroundColor( const QColor& c )
186 {
187   setBackgroundColor( 0, c );
188 }
189
190 /*!
191   Sets background data
192   \param d - new background data
193 */
194 void OCCViewer_Viewer::setBackground( const Qtx::BackgroundData& theBackground )
195 {
196   setBackground( 0, theBackground );
197 }
198
199 /*!
200   Start initialization of view window
201   \param view - view window to be initialized
202 */
203 void OCCViewer_Viewer::initView( OCCViewer_ViewWindow* view )
204 {
205   if ( view ) {
206     view->initLayout();
207     view->initSketchers();
208     view->setInteractionStyle( interactionStyle() );
209     view->setZoomingStyle( zoomingStyle() );
210     view->enablePreselection( isPreselectionEnabled() );
211     view->enableSelection( isSelectionEnabled() );
212     
213     OCCViewer_ViewPort3d* vp3d = view->getViewPort();
214     if ( vp3d )
215     {
216       vp3d->getView()->SetSurfaceDetail(V3d_TEX_ALL);
217       // connect signal from viewport
218       connect(vp3d, SIGNAL(vpClosed(OCCViewer_ViewPort3d*)), this, SLOT(onViewClosed(OCCViewer_ViewPort3d*)));
219       connect(vp3d, SIGNAL(vpMapped(OCCViewer_ViewPort3d*)), this, SLOT(onViewMapped(OCCViewer_ViewPort3d*)));
220     }
221   }
222 }
223
224 /*!
225   Creates new view window
226   \param theDesktop - main window of application
227 */
228 SUIT_ViewWindow* OCCViewer_Viewer::createView( SUIT_Desktop* theDesktop )
229 {
230   // create view frame
231   OCCViewer_ViewFrame* view = new OCCViewer_ViewFrame(theDesktop, this);
232   // get main view window (created by view frame)
233   OCCViewer_ViewWindow* vw = view->getView(OCCViewer_ViewFrame::MAIN_VIEW);
234   // initialize main view window
235   initView( vw );
236   // set default background for view window
237   vw->setBackground( background(0) ); // 0 means MAIN_VIEW (other views are not yet created here)
238
239   return view;
240 }
241
242 /*!
243   Sets new view manager
244   \param theViewManager - new view manager
245 */
246 void OCCViewer_Viewer::setViewManager(SUIT_ViewManager* theViewManager)
247 {
248   SUIT_ViewModel::setViewManager(theViewManager);
249   if (theViewManager) {
250     connect(theViewManager, SIGNAL(mousePress(SUIT_ViewWindow*, QMouseEvent*)), 
251             this, SLOT(onMousePress(SUIT_ViewWindow*, QMouseEvent*)));
252
253     connect(theViewManager, SIGNAL(mouseMove(SUIT_ViewWindow*, QMouseEvent*)), 
254             this, SLOT(onMouseMove(SUIT_ViewWindow*, QMouseEvent*)));
255
256     connect(theViewManager, SIGNAL(mouseRelease(SUIT_ViewWindow*, QMouseEvent*)), 
257             this, SLOT(onMouseRelease(SUIT_ViewWindow*, QMouseEvent*)));
258
259     connect(theViewManager, SIGNAL(keyPress(SUIT_ViewWindow*, QKeyEvent*)), 
260             this, SLOT(onKeyPress(SUIT_ViewWindow*, QKeyEvent*)));
261   }
262 }
263
264 /*!
265   SLOT: called on mouse button press, stores current mouse position as start point for transformations
266 */
267 void OCCViewer_Viewer::onMousePress(SUIT_ViewWindow* theWindow, QMouseEvent* theEvent)
268 {
269   myStartPnt.setX(theEvent->x()); myStartPnt.setY(theEvent->y());
270 }
271
272 /*!
273   SLOT: called on mouse move, processes transformation or hilighting
274 */
275 void OCCViewer_Viewer::onMouseMove(SUIT_ViewWindow* theWindow, QMouseEvent* theEvent)
276 {
277   if (!mySelectionEnabled) return;
278   if (!theWindow->inherits("OCCViewer_ViewWindow")) return;
279
280   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*) theWindow;
281
282   myCurPnt.setX(theEvent->x()); myCurPnt.setY(theEvent->y());
283
284   if ( isSelectionEnabled() && isPreselectionEnabled() ) {
285     if (aView->getViewPort()->isBusy()) {
286       QCoreApplication::processEvents();
287       return; // Check that the ViewPort initialization completed
288                                                 // To Prevent call move event if the View port is not initialized
289                                                 // IPAL 20883
290     }
291     Handle(V3d_View) aView3d = aView->getViewPort()->getView();
292     if ( !aView3d.IsNull() ) {
293       myAISContext->MoveTo(theEvent->x(), theEvent->y(), aView3d);
294     }
295   }
296 }
297
298
299 /*!
300   SLOT: called on mouse button release, finishes transformation or selection
301 */
302 void OCCViewer_Viewer::onMouseRelease(SUIT_ViewWindow* theWindow, QMouseEvent* theEvent)
303 {
304   if (!mySelectionEnabled) return;
305   if (theEvent->button() != Qt::LeftButton) return;
306   if (!theWindow->inherits("OCCViewer_ViewWindow")) return;
307
308   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*) theWindow;
309   if (!aView )
310     return;
311
312   myEndPnt.setX(theEvent->x()); myEndPnt.setY(theEvent->y());
313   bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
314   
315   if (!aHasShift) {
316     myAISContext->ClearCurrents( false );
317     emit deselection();
318   }
319
320   if (myStartPnt == myEndPnt)
321   {
322     if ( !isPreselectionEnabled() ) {
323       Handle(V3d_View) aView3d = aView->getViewPort()->getView();
324       if ( !aView3d.IsNull() ) {
325         myAISContext->MoveTo(myEndPnt.x(), myEndPnt.y(), aView3d);
326       }
327     }
328
329     if (aHasShift && myMultiSelectionEnabled)
330       myAISContext->ShiftSelect();
331     else
332       myAISContext->Select();
333   }
334   else
335   {
336     if (aHasShift && myMultiSelectionEnabled)
337       myAISContext->ShiftSelect(myStartPnt.x(), myStartPnt.y(),
338                                 myEndPnt.x(), myEndPnt.y(),
339                                 aView->getViewPort()->getView(), Standard_False );
340     else
341       myAISContext->Select(myStartPnt.x(), myStartPnt.y(),
342                            myEndPnt.x(), myEndPnt.y(),
343                            aView->getViewPort()->getView(), Standard_False );
344
345     int Nb = myAISContext->NbSelected();
346     if( Nb>1 && !myMultiSelectionEnabled )
347     {
348         myAISContext->InitSelected();
349         Handle( SelectMgr_EntityOwner ) anOwner = myAISContext->SelectedOwner();
350         if( !anOwner.IsNull() )
351         {
352             myAISContext->ClearSelected( Standard_False );
353             myAISContext->AddOrRemoveSelected( anOwner, Standard_False );
354         }
355     }
356
357     myAISContext->UpdateCurrentViewer();
358   }
359   emit selectionChanged();
360 }
361
362 /*!
363   SLOT: called on key press, processes selection in "key free" interaction style
364 */
365 void OCCViewer_Viewer::onKeyPress(SUIT_ViewWindow* theWindow, QKeyEvent* theEvent)
366 {
367   if (!mySelectionEnabled) return;
368
369   OCCViewer_ViewWindow* aView = qobject_cast<OCCViewer_ViewWindow*>( theWindow );
370   if ( !aView ) return;
371
372   bool aHasShift = (theEvent->modifiers() & Qt::ShiftModifier);
373
374   switch ( theEvent->key() ) {
375   case  Qt::Key_S:
376     if (!aHasShift) {
377       myAISContext->ClearCurrents( false );
378       emit deselection();
379     }
380
381     if ( !isPreselectionEnabled() ) {
382       Handle(V3d_View) aView3d = aView->getViewPort()->getView();
383       if ( !aView3d.IsNull() ) {
384         myAISContext->MoveTo(myCurPnt.x(), myCurPnt.y(), aView3d);
385       }
386     }
387
388     if (aHasShift && myMultiSelectionEnabled)
389       myAISContext->ShiftSelect();
390     else
391       myAISContext->Select();
392
393     emit selectionChanged();
394
395     break;
396   case  Qt::Key_N:
397     if ( isPreselectionEnabled() ) {
398       if ( getAISContext()->HasOpenedContext() )
399         getAISContext()->HilightNextDetected( aView->getViewPort()->getView() );
400     }
401     break;
402   case  Qt::Key_P:
403     if ( isPreselectionEnabled() ) {
404       if ( getAISContext()->HasOpenedContext() )
405         getAISContext()->HilightPreviousDetected( aView->getViewPort()->getView() );
406     }
407     break;
408   default:
409     break;
410   }
411 }
412
413 void OCCViewer_Viewer::onViewClosed(OCCViewer_ViewPort3d*)
414 {
415   Standard_Integer aViewsNb = 0;
416   for ( myV3dViewer->InitActiveViews(); myV3dViewer->MoreActiveViews(); myV3dViewer->NextActiveViews())
417     ++aViewsNb;
418   if ( aViewsNb < 2 ) {
419     //clean up presentations before last view is closed
420     myAISContext->RemoveAll(Standard_False);
421   }
422 }
423
424 void OCCViewer_Viewer::onViewMapped(OCCViewer_ViewPort3d* viewPort)
425 {
426   setTrihedronShown( true );
427   bool showStaticTrihedron = true;
428   SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
429   if ( resMgr ) showStaticTrihedron = resMgr->booleanValue( "3DViewer", "show_static_trihedron", true );
430   viewPort->showStaticTrihedron( showStaticTrihedron );
431 }
432
433 int OCCViewer_Viewer::getTopLayerId()
434 {
435   if ( myTopLayerId == 0 && !myAISContext->CurrentViewer().IsNull() )    
436     myAISContext->CurrentViewer()->AddZLayer( myTopLayerId );
437
438   return myTopLayerId;
439 }
440
441 /*!
442   \return interaction style
443 */
444 int OCCViewer_Viewer::interactionStyle() const
445 {
446   return myInteractionStyle;
447 }
448
449 /*!
450   Sets interaction style: 0 - standard, 1 - keyboard free interaction
451   \param theStyle - new interaction style
452 */
453 void OCCViewer_Viewer::setInteractionStyle( const int theStyle )
454 {
455   myInteractionStyle = theStyle;
456   //!! To be done for view windows
457   if ( !myViewManager )
458     return;
459
460   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
461   for ( int i = 0; i < (int)wins.count(); i++ )
462   {
463     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
464     if ( win )
465       win->setInteractionStyle( theStyle );
466   }
467 }
468
469 /*!
470   \return zooming style
471 */
472 int OCCViewer_Viewer::zoomingStyle() const
473 {
474   return myZoomingStyle;
475 }
476
477 /*!
478   Sets zooming style: 0 - standard, 1 - advanced (at cursor)
479   \param theStyle - new zooming style
480 */
481 void OCCViewer_Viewer::setZoomingStyle( const int theStyle )
482 {
483   myZoomingStyle = theStyle;
484   //!! To be done for view windows
485   if ( !myViewManager )
486     return;
487
488   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
489   for ( int i = 0; i < (int)wins.count(); i++ )
490   {
491     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
492     if ( win )
493       win->setZoomingStyle( theStyle );
494   }
495 }
496
497 /*!
498   \return true if preselection is enabled
499 */
500 bool OCCViewer_Viewer::isPreselectionEnabled() const 
501
502   return myPreselectionEnabled; 
503 }
504
505 /*!
506   Enables/disables preselection
507   \param isEnabled - new status
508 */
509 void OCCViewer_Viewer::enablePreselection(bool isEnabled)
510 {
511   myPreselectionEnabled = isEnabled;
512
513   if ( !myViewManager )
514     return;
515
516   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
517   for ( int i = 0; i < (int)wins.count(); i++ )
518   {
519     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
520     if ( win ) {
521       win->enablePreselection( isEnabled );
522     }
523   }
524 }
525
526 /*!
527   \return true if selection is enabled
528 */
529 bool OCCViewer_Viewer::isSelectionEnabled() const 
530
531   return mySelectionEnabled; 
532 }
533
534 /*!
535   Enables/disables selection
536   \param isEnabled - new status
537 */
538 void OCCViewer_Viewer::enableSelection(bool isEnabled)
539 {
540   mySelectionEnabled = isEnabled;
541
542   //!! To be done for view windows
543   if ( !myViewManager )
544     return;
545
546   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
547   for ( int i = 0; i < (int)wins.count(); i++ )
548   {
549     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
550     if ( win ) {
551       win->updateEnabledDrawMode();
552       win->enableSelection( isEnabled );
553     }
554   }
555
556   
557   //clear current selection in the viewer
558   if(!isEnabled) {
559     myAISContext->ClearSelected( Standard_True );
560   }
561
562 }
563
564 /*!
565   Sets multiselection enabled status
566   \param isEnabled - new status
567 */
568 void OCCViewer_Viewer::enableMultiselection(bool isEnable)
569 {
570   myMultiSelectionEnabled = isEnable;
571   //!! To be done for view windows
572   if ( !myViewManager )
573     return;
574
575   QVector<SUIT_ViewWindow*> wins = myViewManager->getViews();
576   for ( int i = 0; i < (int)wins.count(); i++ )
577   {
578     OCCViewer_ViewWindow* win = ::qobject_cast<OCCViewer_ViewWindow*>( wins.at( i ) );
579     if ( win )
580       win->updateEnabledDrawMode();
581   }
582 }
583
584 /*!
585   Sets a color of the clipped region
586   \param theColor - a new color of the clipped region
587 */
588 void OCCViewer_Viewer::setClippingColor( const QColor& theColor )
589 {
590   myClippingColor = theColor;
591
592   if( myInternalClipPlanes.IsEmpty() )
593     return;
594
595   Graphic3d_MaterialAspect aMaterialAspect = Graphic3d_MaterialAspect();
596   aMaterialAspect.SetColor( Quantity_Color( theColor.redF(), theColor.greenF(),
597                                             theColor.blueF(), Quantity_TOC_RGB ) );
598
599   for( int i = 1; i <= myInternalClipPlanes.Size(); i++ )
600     myInternalClipPlanes.Value(i)->SetCappingMaterial( aMaterialAspect );
601
602   update();
603 }
604
605 /*!
606   \return clipping color
607 */
608 QColor OCCViewer_Viewer::clippingColor() const
609 {
610   return myClippingColor;
611 }
612
613 // initialize a texture for clipped region
614 Handle(Graphic3d_Texture2Dmanual) initClippingTexture( const bool isDefault, const QString& theTexture,
615                                                        const bool isModulate, const double theScale )
616 {
617   QString aTextureFile = isDefault ? ":images/hatch.png" : theTexture;
618   QPixmap px( aTextureFile );
619   const Handle(Image_PixMap) aPixmap = OCCViewer_Utilities::imageToPixmap( px.toImage() );
620   Handle(Graphic3d_Texture2Dmanual) aTexture = new Graphic3d_Texture2Dmanual( aPixmap );
621   if( aTexture->IsDone() ) {
622     aTexture->EnableRepeat();
623     isModulate ? aTexture->EnableModulate() : aTexture->DisableModulate();
624     aTexture->GetParams()->SetScale( Graphic3d_Vec2( 1/( theScale*100 ), -1 / ( theScale*100 ) ) );
625   }
626   return aTexture;
627 }
628
629 /*!
630   Sets default texture parameters
631   \param isDefault - use/non-use default texture
632   \param theTexture - new texture of the clipped region
633   \param isModulate - enable/disable texture modulate mode
634   \param theScale - scale factor.
635 */
636 void OCCViewer_Viewer::setClippingTextureParams( const bool isDefault, const QString& theTexture,
637                                                  const bool isModulate, const double theScale )
638 {
639   myDefaultTextureUsed = isDefault;
640   myClippingTexture = theTexture;
641   myTextureModulated = isModulate;
642   myClippingTextureScale = theScale;
643
644   if( myInternalClipPlanes.IsEmpty() )
645     return;
646
647   Handle(Graphic3d_Texture2Dmanual) aTexture =
648     initClippingTexture( myDefaultTextureUsed, myClippingTexture,
649                          myTextureModulated, myClippingTextureScale );
650
651   for( int i = 1; i <= myInternalClipPlanes.Size(); i++ )
652     myInternalClipPlanes.Value(i)->SetCappingTexture( aTexture );
653
654   update();
655 }
656
657 /*!
658   \return true if default texture is used
659 */
660 bool OCCViewer_Viewer::isDefaultTextureUsed() const
661 {
662   return myDefaultTextureUsed;
663 }
664
665 /*!
666   \return clipping texture
667 */
668 QString OCCViewer_Viewer::clippingTexture() const
669 {
670   return myClippingTexture;
671 }
672
673 /*!
674   \return true if texture is modulated
675 */
676 bool OCCViewer_Viewer::isTextureModulated() const
677 {
678   return myTextureModulated;
679 }
680
681 /*!
682   \return scale factor of texture
683 */
684 double OCCViewer_Viewer::clippingTextureScale() const
685 {
686   return myClippingTextureScale;
687 }
688
689 /*!
690   Builds popup for occ viewer
691 */
692 void OCCViewer_Viewer::contextMenuPopup(QMenu* thePopup)
693 {
694   thePopup->addAction( tr( "MEN_DUMP_VIEW" ), this, SLOT( onDumpView() ) );
695   thePopup->addAction( tr( "MEN_CHANGE_BACKGROUND" ), this, SLOT( onChangeBackground() ) );
696
697   thePopup->addSeparator();
698
699   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
700
701   //Support of several toolbars in the popup menu
702   QList<QToolBar*> lst = qFindChildren<QToolBar*>( aView );
703   QList<QToolBar*>::const_iterator it = lst.begin(), last = lst.end();
704   for ( ; it!=last; it++ ) {
705     if ( (*it)->parentWidget()->isVisible() )
706       thePopup->addAction( (*it)->toggleViewAction() );
707   }
708 }
709
710 /*!
711   SLOT: called on dump view operation is activated, stores scene to raster file
712 */
713 void OCCViewer_Viewer::onDumpView()
714 {
715   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
716   if ( aView )
717     aView->onDumpView();
718 }
719
720 /*!
721   SLOT: called if background color is to be changed changed, passes new color to view port
722 */
723 void OCCViewer_Viewer::onChangeBackground()
724 {
725   OCCViewer_ViewWindow* aView = dynamic_cast<OCCViewer_ViewWindow*>(myViewManager->getActiveView());
726   if ( !aView )
727     return;
728
729   // get supported gradient types
730   QStringList gradList;
731   QIntList    idList, txtList;
732   QString     formats = backgroundData( gradList, idList, txtList );
733
734   // invoke dialog box
735   Qtx::BackgroundData bgData = QtxBackgroundDialog::getBackground( aView->background(),  // initial background
736                                                                    aView,                // parent for dialog box
737                                                                    txtList,              // allowed texture modes
738                                                                    true,                 // enable solid color mode
739                                                                    true,                 // enable gradient mode
740                                                                    false,                // disable custom gradient mode
741                                                                    !txtList.isEmpty(),   // enable/disable texture mode
742                                                                    gradList,             // gradient names
743                                                                    idList,               // gradient identifiers
744                                                                    formats );            // image formats
745
746   // set chosen background data to the viewer
747   if ( bgData.isValid() )
748     aView->setBackground( bgData );
749 }
750
751 /*!
752   Updates OCC 3D viewer
753 */
754 void OCCViewer_Viewer::update()
755 {
756   if (!myV3dViewer.IsNull())
757     myV3dViewer->Update();
758
759   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
760   if ( aView )
761     aView->updateGravityCoords();
762 }
763
764 /*!
765   \return objects selected in 3D viewer
766   \param theList - list to be filled with selected objects
767 */
768 void OCCViewer_Viewer::getSelectedObjects(AIS_ListOfInteractive& theList)
769 {
770   theList.Clear();
771   for (myAISContext->InitSelected(); myAISContext->MoreSelected(); myAISContext->NextSelected())
772     theList.Append(myAISContext->SelectedInteractive());
773 }
774
775 /*!
776   Selects objects in 3D viewer. Other selected objects are left as selected
777   \param theList - list objects to be selected
778 */
779 void OCCViewer_Viewer::setObjectsSelected(const AIS_ListOfInteractive& theList)
780 {
781   AIS_ListIteratorOfListOfInteractive aIt;
782   for (aIt.Initialize(theList); aIt.More(); aIt.Next())
783     myAISContext->AddOrRemoveSelected(aIt.Value(), false);
784   myAISContext->UpdateCurrentViewer();
785 }
786
787 /*!
788   Auxiliary method to emit signal selectionChanged()
789 */
790 void OCCViewer_Viewer::performSelectionChanged()
791 {
792     emit selectionChanged();
793 }
794
795 /*!
796   Hilights/unhilights object in viewer
797   \param obj - object to be updated
798   \param hilight - if it is true, object will be hilighted, otherwise it will be unhilighted
799   \param update - update current viewer
800 */
801 bool OCCViewer_Viewer::highlight( const Handle(AIS_InteractiveObject)& obj,
802                                   bool hilight, bool update )
803 {
804   bool isInLocal = myAISContext->HasOpenedContext();
805   if( !obj.IsNull() )
806     if( !isInLocal )
807     {
808       if ( hilight && !myAISContext->IsSelected( obj ) )
809         myAISContext->AddOrRemoveCurrentObject( obj, false );
810       else if ( !hilight && myAISContext->IsSelected( obj ) )
811         myAISContext->AddOrRemoveCurrentObject( obj, false );
812     }
813
814   if ( update )
815     myV3dViewer->Redraw();
816     
817   return false;
818 }
819
820 /*!
821   Unhilights all objects in viewer
822   \param updateviewer - update current viewer
823 */
824 bool OCCViewer_Viewer::unHighlightAll( bool updateviewer, bool unselect )
825 {
826   if ( myAISContext->HasOpenedContext() ) {
827     if ( unselect ) {
828       myAISContext->ClearSelected( updateviewer );
829     } else {
830       myAISContext->UnhilightSelected( updateviewer );
831     }
832   } else {
833     if ( unselect ) {
834       myAISContext->ClearCurrents( updateviewer );
835     } else {
836       myAISContext->UnhilightCurrents( updateviewer );
837     }
838   }
839
840   return false;
841 }
842
843 /*!
844   \return true if object is in viewer or in collector
845   \param obj - object to be checked
846   \param onlyInViewer - search object only in viewer (so object must be displayed)
847 */
848 bool OCCViewer_Viewer::isInViewer( const Handle(AIS_InteractiveObject)& obj,
849                                    bool onlyInViewer )
850 {
851   AIS_ListOfInteractive List;
852   myAISContext->DisplayedObjects(List);
853
854   AIS_ListIteratorOfListOfInteractive ite(List);
855   for ( ; ite.More(); ite.Next() )
856     if( ite.Value()==obj )
857       return true;
858
859   return false;
860 }
861
862 /*!
863   \return true if object is displayed in viewer
864   \param obj - object to be checked
865 */
866 bool OCCViewer_Viewer::isVisible( const Handle(AIS_InteractiveObject)& obj )
867 {
868   return myAISContext->IsDisplayed( obj );
869 }
870
871 /*!
872   Sets color of object
873   \param obj - object to be updated
874   \param color - new color
875   \param update - update current viewer
876 */
877 void OCCViewer_Viewer::setColor( const Handle(AIS_InteractiveObject)& obj,
878                                  const QColor& color,
879                                  bool update )
880 {
881   if( !obj.IsNull() )
882   {
883     Quantity_Color CSFColor = Quantity_Color ( color.red() / 255.,
884                                                color.green() / 255.,
885                                                color.blue() / 255.,
886                                                Quantity_TOC_RGB );
887     obj->SetColor( CSFColor );
888   }
889
890   if( update )
891     myV3dViewer->Update();
892 }
893
894 /*!
895   Changes display mode of object
896   \param obj - object to be processed
897   \param mode - new display mode
898   \param update - update current viewer
899 */
900 void OCCViewer_Viewer::switchRepresentation( const Handle(AIS_InteractiveObject)& obj,
901                                              int mode, bool update )
902 {
903   myAISContext->SetDisplayMode( obj, (Standard_Integer)mode, update );
904   if( update )
905     myV3dViewer->Update();
906 }
907
908 /*!
909   Changes transparency of object
910   \param obj - object to be processed
911   \param trans - new transparency
912   \param update - update current viewer
913 */
914 void OCCViewer_Viewer::setTransparency( const Handle(AIS_InteractiveObject)& obj,
915                                         float trans, bool update )
916 {
917   myAISContext->SetTransparency( obj, trans, false );
918   myAISContext->Redisplay( obj, Standard_False, Standard_True );
919   if( update )
920     myV3dViewer->Update();
921 }
922
923 /*!
924   Changes visibility of trihedron to opposite
925 */
926 void OCCViewer_Viewer::toggleTrihedron()
927 {
928   setTrihedronShown( !isTrihedronVisible() );
929 }
930
931 /*!
932   \return true if trihedron is visible
933 */
934 bool OCCViewer_Viewer::isTrihedronVisible() const
935 {
936   return !myTrihedron.IsNull() && !myAISContext.IsNull() && myAISContext->IsDisplayed( myTrihedron );
937 }
938
939 /*!
940   Sets visibility state of trihedron
941   \param on - new state
942 */
943
944 void OCCViewer_Viewer::setTrihedronShown( const bool on )
945 {
946   if ( myTrihedron.IsNull() )
947     return;
948
949   if ( on ) {
950     myAISContext->Display( myTrihedron );
951     myAISContext->Deactivate(myTrihedron);
952   }
953   else {
954     myAISContext->Erase( myTrihedron );
955   }
956 }
957
958 /*!
959   \return trihedron size
960 */
961 double OCCViewer_Viewer::trihedronSize() const
962 {
963   double sz = 0;
964   if ( !myTrihedron.IsNull() )
965     sz = myTrihedron->Size();
966   return sz;
967 }
968
969 /*!
970   Changes trihedron size
971   \param sz - new size
972 */
973 void OCCViewer_Viewer::setTrihedronSize( const double sz, bool isRelative )
974 {
975   if ( myTrihedronSize != sz || isRelative != myIsRelative) {
976     myTrihedronSize = sz; 
977     myIsRelative = isRelative;
978     updateTrihedron();
979   }
980 }
981
982 /*!
983   Set number of isolines
984   \param u - u-isolines (first parametric co-ordinate)
985   \param v - v-isolines (second parametric co-ordinate)
986 */
987 void OCCViewer_Viewer::setIsos( const int u, const int v )
988 {
989   Handle(AIS_InteractiveContext) ic = getAISContext();
990   if ( ic.IsNull() )
991   return;
992
993   ic->SetIsoNumber( u, AIS_TOI_IsoU );
994   ic->SetIsoNumber( v, AIS_TOI_IsoV );
995 }
996
997 /*!
998   \return number of isolines
999   \param u - to return u-isolines (first parametric co-ordinate)
1000   \param v - to return v-isolines (second parametric co-ordinate)
1001 */
1002 void OCCViewer_Viewer::isos( int& u, int& v ) const
1003 {
1004   Handle(AIS_InteractiveContext) ic = getAISContext();
1005   if ( !ic.IsNull() )
1006   {
1007     u = ic->IsoNumber( AIS_TOI_IsoU );
1008     v = ic->IsoNumber( AIS_TOI_IsoV );
1009   }
1010 }
1011
1012 /* 
1013  * Returns a new OCCViewer_ViewWindow instance which will be placed as a sub window in ViewFrame
1014  */
1015 OCCViewer_ViewWindow* OCCViewer_Viewer::createSubWindow()
1016 {
1017   return new OCCViewer_ViewWindow(0,  this);
1018 }
1019
1020 // obsolete  
1021 QColor OCCViewer_Viewer::backgroundColor( int theViewId ) const
1022 {
1023   return background( theViewId ).color();
1024 }
1025
1026 Qtx::BackgroundData OCCViewer_Viewer::background( int theViewId ) const
1027 {
1028   return ( theViewId >= 0 && theViewId < myBackgrounds.count() ) ? myBackgrounds[theViewId] : Qtx::BackgroundData();
1029 }
1030
1031 // obsolete
1032 void OCCViewer_Viewer::setBackgroundColor( int theViewId, const QColor& theColor )
1033 {
1034   if ( theColor.isValid() ) {
1035     Qtx::BackgroundData bg = background( theViewId );
1036     bg.setColor( theColor );
1037     setBackground( theViewId, bg );
1038   }
1039 }
1040
1041 void OCCViewer_Viewer::setBackground( int theViewId, const Qtx::BackgroundData& theBackground )
1042 {
1043   if ( theBackground.isValid() && theViewId >= 0 && theViewId < myBackgrounds.count() )
1044     myBackgrounds[theViewId] = theBackground;    
1045 }
1046
1047
1048 /*!
1049   Set the show static trihedron flag
1050 */
1051 void OCCViewer_Viewer::setStaticTrihedronDisplayed(const bool on)
1052 {
1053   OCCViewer_ViewWindow* aView = (OCCViewer_ViewWindow*)(myViewManager->getActiveView());
1054   if ( aView ) aView->showStaticTrihedron( on );
1055 }
1056
1057 /*!
1058   Get new and current trihedron size corresponding to the current model size
1059 */
1060 bool OCCViewer_Viewer::computeTrihedronSize( double& theNewSize, double& theSize )
1061 {
1062   theNewSize = 100;
1063   theSize = 100;
1064
1065   //SRN: BUG IPAL8996, a usage of method ActiveView without an initialization
1066   Handle(V3d_Viewer) viewer = getViewer3d();
1067   viewer->InitActiveViews();
1068   if(!viewer->MoreActiveViews()) return false;
1069
1070   Handle(V3d_View) view3d = viewer->ActiveView();
1071   //SRN: END of fix
1072
1073   if ( view3d.IsNull() )
1074     return false;
1075
1076   double aMaxSide = computeSceneSize( view3d );
1077
1078   // IPAL21687
1079   // The boundary box of the view may be initialized but nullified
1080   // (case of infinite objects)
1081   if ( aMaxSide < Precision::Confusion() )
1082     return false;
1083
1084   float aSizeInPercents = SUIT_Session::session()->resourceMgr()->doubleValue("3DViewer","trihedron_size", 100.);
1085
1086   static float EPS = 5.0E-3;
1087   theSize = getTrihedron()->Size();
1088   theNewSize = aMaxSide*aSizeInPercents / 100.0;
1089
1090   return fabs( theNewSize - theSize ) > theSize    * EPS ||
1091          fabs( theNewSize - theSize ) > theNewSize * EPS;
1092 }
1093
1094 /*!
1095  * Compute scene size
1096  */
1097 double OCCViewer_Viewer::computeSceneSize(const Handle(V3d_View)& view3d) const
1098 {
1099   double aMaxSide = 0;
1100   double Xmin = 0, Ymin = 0, Zmin = 0, Xmax = 0, Ymax = 0, Zmax = 0;
1101
1102 #if OCC_VERSION_LARGE > 0x06070100
1103   Bnd_Box aBox = view3d->View()->MinMaxValues();
1104   Xmin = aBox.IsVoid() ? RealFirst() : aBox.CornerMin().X();
1105   Ymin = aBox.IsVoid() ? RealFirst() : aBox.CornerMin().Y();
1106   Zmin = aBox.IsVoid() ? RealFirst() : aBox.CornerMin().Z();
1107   Xmax = aBox.IsVoid() ? RealLast()  : aBox.CornerMax().X();
1108   Ymax = aBox.IsVoid() ? RealLast()  : aBox.CornerMax().Y();
1109   Zmax = aBox.IsVoid() ? RealLast()  : aBox.CornerMax().Z();
1110 #else
1111   view3d->View()->MinMaxValues( Xmin, Ymin, Zmin, Xmax, Ymax, Zmax );
1112 #endif
1113
1114   if ( Xmin != RealFirst() && Ymin != RealFirst() && Zmin != RealFirst() &&
1115        Xmax != RealLast()  && Ymax != RealLast()  && Zmax != RealLast() )
1116   {
1117     aMaxSide = Xmax - Xmin;
1118     if ( aMaxSide < Ymax -Ymin ) aMaxSide = Ymax -Ymin;
1119     if ( aMaxSide < Zmax -Zmin ) aMaxSide = Zmax -Zmin;
1120   }
1121
1122   return aMaxSide;
1123 }
1124
1125 /*! 
1126  * Update the size of the trihedron
1127  */
1128 void OCCViewer_Viewer::updateTrihedron() {
1129   if ( myTrihedron.IsNull() )
1130     return;
1131
1132   if(myIsRelative){
1133     double newSz, oldSz;
1134     
1135     if(computeTrihedronSize(newSz, oldSz))
1136       myTrihedron->SetSize(newSz);
1137     
1138   } else if(myTrihedron->Size() != myTrihedronSize) {
1139     myTrihedron->SetSize(myTrihedronSize);
1140   }
1141 }
1142
1143 /*!
1144   Set number of isolines
1145   \param u - u-isolines (first parametric co-ordinate)
1146   \param v - v-isolines (second parametric co-ordinate)
1147 */
1148 void OCCViewer_Viewer::setSelectionOptions( bool isPreselectionEnabled, bool isSelectionEnabled )
1149 {
1150   myPreselectionEnabled = isPreselectionEnabled;
1151   mySelectionEnabled = isSelectionEnabled;
1152   //clear current selection in the viewer
1153   
1154   if(!mySelectionEnabled) {
1155     myAISContext->ClearSelected( Standard_True );
1156   }
1157 }
1158
1159 /*!
1160   Creates clipping plane based on the incoming plane
1161 */
1162 Handle(Graphic3d_ClipPlane) OCCViewer_Viewer::createClipPlane(const gp_Pln& thePlane, const Standard_Boolean theIsOn)
1163 {
1164   Handle(Graphic3d_ClipPlane) aGraphic3dPlane = new Graphic3d_ClipPlane( thePlane );
1165   aGraphic3dPlane->SetOn( theIsOn );
1166   aGraphic3dPlane->SetCapping( Standard_True );
1167
1168   // set capping color
1169   Graphic3d_MaterialAspect aMaterialAspect = Graphic3d_MaterialAspect();
1170   aMaterialAspect.SetColor( Quantity_Color( myClippingColor.redF(), myClippingColor.greenF(),
1171                                             myClippingColor.blueF(), Quantity_TOC_RGB ) );
1172   aGraphic3dPlane->SetCappingMaterial( aMaterialAspect );
1173
1174   // set capping texture
1175   aGraphic3dPlane->SetCappingTexture( initClippingTexture( myDefaultTextureUsed, myClippingTexture,
1176                                                            myTextureModulated, myClippingTextureScale ) );
1177
1178   return aGraphic3dPlane;
1179 }
1180 /*!
1181   Applies clipping planes to clippable objects
1182 */
1183 void OCCViewer_Viewer::setClipPlanes(ClipPlanesList theList)
1184 {
1185   // 1. Remove existing clipping planes
1186   myClipPlanes.clear();
1187   myInternalClipPlanes.Clear();
1188
1189   // 2. Create new clipping planes
1190   ClipPlanesList::iterator inIt = theList.begin();
1191   for (;inIt != theList.end(); inIt++ )
1192   {
1193     OCCViewer_ClipPlane aPlane = *inIt;
1194
1195     double aDx = 0.0, aDy = 0.0, aDz = 0.0;
1196     aPlane.OrientationToXYZ( aDx, aDy, aDz );
1197
1198     gp_Pnt anOrigin( aPlane.X, aPlane.Y, aPlane.Z );
1199     gp_Dir aDirection( aDx, aDy, aDz );
1200
1201     myInternalClipPlanes.Append( createClipPlane( gp_Pln( anOrigin, aDirection ), aPlane.IsOn ) );
1202     myClipPlanes.push_back( aPlane );
1203   }
1204
1205   // 3. Apply clipping planes
1206   AIS_ListOfInteractive aList;
1207   myAISContext->DisplayedObjects (aList);
1208   for ( AIS_ListIteratorOfListOfInteractive anIter (aList); anIter.More(); anIter.Next() ) {
1209     Handle(AIS_InteractiveObject) anObj = anIter.Value();
1210     Handle(ViewerData_AISShape) aShape = Handle(ViewerData_AISShape)::DownCast (anObj);
1211     if (!aShape.IsNull() && aShape->IsClippable()) {
1212       aShape->SetClipPlanes(myInternalClipPlanes);
1213     }
1214   }
1215 }
1216
1217 /*!
1218   Returns the clipping planes applied to the displayed objects.
1219 */
1220 ClipPlanesList OCCViewer_Viewer::getClipPlanes() const {
1221   return myClipPlanes;
1222 }
1223 /*!
1224   Applies clipping planes to given object objects
1225 */
1226 void OCCViewer_Viewer::applyExistingClipPlanesToObject (const Handle(AIS_InteractiveObject)& theObject)
1227 {
1228   Handle(ViewerData_AISShape) aShape = Handle(ViewerData_AISShape)::DownCast (theObject);
1229   if (!aShape.IsNull() && aShape->IsClippable())
1230   {
1231     aShape->SetClipPlanes (myInternalClipPlanes);
1232   }
1233 }
1234
1235 /*!
1236   Returns the pointer to the clipping dialog box.
1237 */
1238 OCCViewer_ClippingDlg* OCCViewer_Viewer::getClippingDlg() const{
1239   return myClippingDlg;
1240 }
1241
1242
1243 /*!
1244   Stores pointer to the clipping dialog box.
1245 */
1246 void OCCViewer_Viewer::setClippingDlg(OCCViewer_ClippingDlg* theDlg) {
1247   if(myClippingDlg != theDlg) {
1248     myClippingDlg = theDlg;
1249   }
1250 }