Salome HOME
Update copyright notes (for 2010)
[modules/smesh.git] / src / SMESHGUI / SMESHGUI_VTKUtils.cxx
1 //  Copyright (C) 2007-2010  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.
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 // SMESH SMESHGUI : GUI for SMESH component
24 // File   : SMESHGUI_VTKUtils.cxx
25 // Author : Open CASCADE S.A.S.
26 // SMESH includes
27 //
28 #include "SMESHGUI_VTKUtils.h"
29
30 #include "SMESHGUI.h"
31 #include "SMESHGUI_Utils.h"
32 #include "SMESHGUI_Filter.h"
33
34 #include <SMESH_Actor.h>
35 #include <SMESH_ActorUtils.h>
36 #include <SMESH_ObjectDef.h>
37 #include <SMDS_Mesh.hxx>
38
39 // SALOME GUI includes
40 #include <SUIT_Desktop.h>
41 #include <SUIT_Session.h>
42 #include <SUIT_MessageBox.h>
43 #include <SUIT_ViewManager.h>
44 #include <SUIT_ResourceMgr.h>
45
46 #include <SALOME_ListIO.hxx>
47 #include <SALOME_ListIteratorOfListIO.hxx>
48
49 #include <SVTK_Selector.h>
50 #include <SVTK_ViewModel.h>
51 #include <SVTK_ViewWindow.h>
52
53 #include <VTKViewer_Algorithm.h>
54
55 #include <LightApp_SelectionMgr.h>
56 #include <SalomeApp_Application.h>
57 #include <SalomeApp_Study.h>
58
59 // SALOME KERNEL includes
60 #include <utilities.h>
61
62 // IDL includes
63 #include <SALOMEconfig.h>
64 #include CORBA_CLIENT_HEADER(SMESH_Mesh)
65 #include CORBA_CLIENT_HEADER(SMESH_Group)
66
67 // VTK includes
68 #include <vtkRenderer.h>
69 #include <vtkActorCollection.h>
70 #include <vtkUnstructuredGrid.h>
71
72 // OCCT includes
73 #include <TColStd_IndexedMapOfInteger.hxx>
74 #include <Standard_ErrorHandler.hxx>
75
76 namespace SMESH
77 {
78   typedef std::map<TKeyOfVisualObj,TVisualObjPtr> TVisualObjCont;
79   static TVisualObjCont VISUAL_OBJ_CONT;
80
81   //=============================================================================
82   /*!
83    * \brief Allocate some memory at construction and release it at destruction.
84    * Is used to be able to continue working after mesh generation or visualization
85    * break due to lack of memory
86    */
87   //=============================================================================
88
89   struct MemoryReserve
90   {
91     char* myBuf;
92     MemoryReserve(): myBuf( new char[1024*1024*1] ){} // 1M
93     void Free() { if (myBuf) { delete [] myBuf; myBuf = 0; }}
94     ~MemoryReserve() { Free(); }
95   };
96   static MemoryReserve* theVISU_MemoryReserve = new MemoryReserve;
97
98   //================================================================================
99   /*!
100    * \brief Remove VisualObj and its actor from all views
101    */
102   //================================================================================
103
104   void RemoveVisualObjectWithActors( const char* theEntry )
105   {
106     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>
107       ( SUIT_Session::session()->activeApplication() );
108     SUIT_ViewManager* aViewManager =
109       app ? app->getViewManager(SVTK_Viewer::Type(), true) : 0;
110     if ( aViewManager ) {
111       QVector<SUIT_ViewWindow*> views = aViewManager->getViews();
112       for ( int iV = 0; iV < views.count(); ++iV ) {
113         if ( SMESH_Actor* actor = FindActorByEntry( views[iV], theEntry)) {
114           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV]))
115             vtkWnd->RemoveActor(actor);
116           actor->Delete();
117         }
118       }
119       int aStudyId = aViewManager->study()->id();
120       TVisualObjCont::key_type aKey(aStudyId,theEntry);
121       TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.find(aKey);
122       if(anIter != VISUAL_OBJ_CONT.end()) {
123         // for unknown reason, object destructor is not called, so clear object manually
124         anIter->second->GetUnstructuredGrid()->SetCells(0,0,0);
125         anIter->second->GetUnstructuredGrid()->SetPoints(0);
126       }
127       VISUAL_OBJ_CONT.erase(aKey);
128     }
129   }
130   //================================================================================
131   /*!
132    * \brief Remove all VisualObjs and their actors from all views
133    */
134   //================================================================================
135
136   void RemoveAllObjectsWithActors()
137   {
138     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>
139       ( SUIT_Session::session()->activeApplication() );
140     if (!app) return;
141     ViewManagerList viewMgrs = app->viewManagers();
142     for ( int iM = 0; iM < viewMgrs.count(); ++iM ) {
143       SUIT_ViewManager* aViewManager = viewMgrs.at( iM );
144       if ( aViewManager && aViewManager->getType() == SVTK_Viewer::Type()) {
145         QVector<SUIT_ViewWindow*> views = aViewManager->getViews();
146         for ( int iV = 0; iV < views.count(); ++iV ) {
147           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV])) {
148             vtkRenderer *aRenderer = vtkWnd->getRenderer();
149             VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
150             vtkActorCollection *actors = aCopy.GetActors();
151             for (int i = 0; i < actors->GetNumberOfItems(); ++i ) {
152               // size of actors changes inside the loop
153               if (SMESH_Actor *actor = dynamic_cast<SMESH_Actor*>(actors->GetItemAsObject(i)))
154               {
155                 vtkWnd->RemoveActor(actor);
156                 actor->Delete();
157               }
158             }
159           }
160         }
161       }
162     }
163     TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.begin();
164     for ( ; anIter != VISUAL_OBJ_CONT.end(); ++anIter ) {
165       // for unknown reason, object destructor is not called, so clear object manually
166       anIter->second->GetUnstructuredGrid()->SetCells(0,0,0);
167       anIter->second->GetUnstructuredGrid()->SetPoints(0);
168     }
169     VISUAL_OBJ_CONT.clear();
170   }
171
172   //================================================================================
173   /*!
174    * \brief Remove all VisualObjs of a study
175    */
176   //================================================================================
177
178   void RemoveVisuData(int studyID)
179   {
180     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>
181       ( SUIT_Session::session()->activeApplication() );
182     if (!app) return;
183     ViewManagerList viewMgrs = app->viewManagers();
184     for ( int iM = 0; iM < viewMgrs.count(); ++iM ) {
185       SUIT_ViewManager* aViewManager = viewMgrs.at( iM );
186       if ( aViewManager && aViewManager->getType() == SVTK_Viewer::Type() &&
187            aViewManager->study()->id() == studyID ) {
188         QVector<SUIT_ViewWindow*> views = aViewManager->getViews();
189         for ( int iV = 0; iV < views.count(); ++iV ) {
190           if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(views[iV])) {
191             vtkRenderer *aRenderer = vtkWnd->getRenderer();
192             VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
193             vtkActorCollection *actors = aCopy.GetActors();
194             for (int i = 0; i < actors->GetNumberOfItems(); ++i ) {
195               // size of actors changes inside the loop
196               if(SMESH_Actor *actor = dynamic_cast<SMESH_Actor*>(actors->GetItemAsObject(i)))
197               {
198                 vtkWnd->RemoveActor(actor);
199                 actor->Delete();
200               }
201             }
202           }
203         }
204       }
205     }
206     TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.begin();
207     for ( ; anIter != VISUAL_OBJ_CONT.end(); ++anIter ) {
208       int curId = anIter->first.first;
209       if ( curId == studyID ) {
210         // for unknown reason, object destructor is not called, so clear object manually
211         anIter->second->GetUnstructuredGrid()->SetCells(0,0,0);
212         anIter->second->GetUnstructuredGrid()->SetPoints(0);
213         VISUAL_OBJ_CONT.erase( anIter-- );  // dercement occures before erase()
214       }
215     }
216   }
217
218   //================================================================================
219   /*!
220    * \brief Notify the user on problems during visualization
221    */
222   //================================================================================
223
224   void OnVisuException()
225   {
226     try {
227 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
228       OCC_CATCH_SIGNALS;
229 #endif
230       // PAL16774 (Crash after display of many groups). Salome sometimes crashes just
231       // after or at showing this message, so we do an additional check of available memory
232 //       char* buf = new char[100*1024];
233 //       delete [] buf;
234       SUIT_MessageBox::warning(SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
235                                QObject::tr("SMESH_VISU_PROBLEM"));
236     } catch (...) {
237       // no more memory at all: last resort
238       MESSAGE_BEGIN ( "SMESHGUI_VTKUtils::OnVisuException(), exception even at showing a message!!!" <<
239                       std::endl << "Try to remove all visual data..." );
240       if (theVISU_MemoryReserve) {
241         delete theVISU_MemoryReserve;
242         theVISU_MemoryReserve = 0;
243       }
244       RemoveAllObjectsWithActors();
245       SUIT_MessageBox::warning(SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
246                                QObject::tr("SMESH_VISU_PROBLEM_CLEAR"));
247       MESSAGE_END ( "...done" );
248     }
249   }
250   //================================================================================
251   /*!
252    * \brief Returns an updated visual object
253    */
254   //================================================================================
255
256   TVisualObjPtr GetVisualObj(int theStudyId, const char* theEntry){
257     TVisualObjPtr aVisualObj;
258     TVisualObjCont::key_type aKey(theStudyId,theEntry);
259     try{
260 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
261       OCC_CATCH_SIGNALS;
262 #endif
263       TVisualObjCont::iterator anIter = VISUAL_OBJ_CONT.find(aKey);
264       if(anIter != VISUAL_OBJ_CONT.end()){
265         aVisualObj = anIter->second;
266       }else{
267         SalomeApp_Application* app =
268           dynamic_cast<SalomeApp_Application*>( SMESHGUI::activeStudy()->application() );
269         _PTR(Study) aStudy = SMESHGUI::activeStudy()->studyDS();
270         _PTR(SObject) aSObj = aStudy->FindObjectID(theEntry);
271         if(aSObj){
272           _PTR(GenericAttribute) anAttr;
273           if(aSObj->FindAttribute(anAttr,"AttributeIOR")){
274             _PTR(AttributeIOR) anIOR = anAttr;
275             CORBA::String_var aVal = anIOR->Value().c_str();
276             CORBA::Object_var anObj = app->orb()->string_to_object( aVal.in() );
277             if(!CORBA::is_nil(anObj)){
278               //Try narrow to SMESH_Mesh interface
279               SMESH::SMESH_Mesh_var aMesh = SMESH::SMESH_Mesh::_narrow(anObj);
280               if(!aMesh->_is_nil()){
281                 aVisualObj.reset(new SMESH_MeshObj(aMesh));
282                 TVisualObjCont::value_type aValue(aKey,aVisualObj);
283                 VISUAL_OBJ_CONT.insert(aValue);
284               }
285               //Try narrow to SMESH_Group interface
286               SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow(anObj);
287               if(!aGroup->_is_nil()){
288                 _PTR(SObject) aFatherSObj = aSObj->GetFather();
289                 if(!aFatherSObj) return aVisualObj;
290                 aFatherSObj = aFatherSObj->GetFather();
291                 if(!aFatherSObj) return aVisualObj;
292                 CORBA::String_var anEntry = aFatherSObj->GetID().c_str();
293                 TVisualObjPtr aVisObj = GetVisualObj(theStudyId,anEntry.in());
294                 if(SMESH_MeshObj* aMeshObj = dynamic_cast<SMESH_MeshObj*>(aVisObj.get())){
295                   aVisualObj.reset(new SMESH_GroupObj(aGroup,aMeshObj));
296                   TVisualObjCont::value_type aValue(aKey,aVisualObj);
297                   VISUAL_OBJ_CONT.insert(aValue);
298                 }
299               }
300               //Try narrow to SMESH_subMesh interface
301               SMESH::SMESH_subMesh_var aSubMesh = SMESH::SMESH_subMesh::_narrow(anObj);
302               if(!aSubMesh->_is_nil()){
303                 _PTR(SObject) aFatherSObj = aSObj->GetFather();
304                 if(!aFatherSObj) return aVisualObj;
305                 aFatherSObj = aFatherSObj->GetFather();
306                 if(!aFatherSObj) return aVisualObj;
307                 CORBA::String_var anEntry = aFatherSObj->GetID().c_str();
308                 TVisualObjPtr aVisObj = GetVisualObj(theStudyId,anEntry.in());
309                 if(SMESH_MeshObj* aMeshObj = dynamic_cast<SMESH_MeshObj*>(aVisObj.get())){
310                   aVisualObj.reset(new SMESH_subMeshObj(aSubMesh,aMeshObj));
311                   TVisualObjCont::value_type aValue(aKey,aVisualObj);
312                   VISUAL_OBJ_CONT.insert(aValue);
313                 }
314               }
315             }
316           }
317         }
318       }
319     }catch(...){
320       INFOS("GetMeshObj - There is no SMESH_Mesh object for the SALOMEDS::Strudy and Entry!!!");
321       return TVisualObjPtr();
322     }
323     // Update object
324     bool objModified = false;
325     if ( aVisualObj ) {
326       try {
327 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
328         OCC_CATCH_SIGNALS;
329 #endif
330         objModified = aVisualObj->Update();
331       }
332       catch (...) {
333 #ifdef _DEBUG_
334         MESSAGE ( "Exception in SMESHGUI_VTKUtils::GetVisualObj()" );
335 #endif
336         RemoveVisualObjectWithActors( theEntry ); // remove this object
337         OnVisuException();
338         aVisualObj.reset();
339       }
340     }
341
342     if ( objModified ) {
343       // PAL16631. Mesurements showed that to show aVisualObj in SHADING(default) mode,
344       // ~10 times more memory is used than it occupies.
345       // Warn the user if there is less free memory than 30 sizes of a grid
346       // TODO: estimate memory usage in other modes and take current mode into account
347       int freeMB = SMDS_Mesh::CheckMemory(true);
348       int usedMB = aVisualObj->GetUnstructuredGrid()->GetActualMemorySize() / 1024;
349       if ( freeMB > 0 && usedMB * 30 > freeMB ) {
350 #ifdef _DEBUG_
351         MESSAGE ( "SMESHGUI_VTKUtils::GetVisualObj(), freeMB=" << freeMB
352                << ", usedMB=" << usedMB );
353 #endif
354         bool continu = false;
355         if ( usedMB * 10 > freeMB )
356           // even dont try to show
357           SUIT_MessageBox::warning(SMESHGUI::desktop(), QObject::tr("SMESH_WRN_WARNING"),
358                                    QObject::tr("SMESH_NO_MESH_VISUALIZATION"));
359         else
360           // there is a chance to succeed
361           continu = SUIT_MessageBox::warning
362             (SMESHGUI::desktop(),
363              QObject::tr("SMESH_WRN_WARNING"),
364              QObject::tr("SMESH_CONTINUE_MESH_VISUALIZATION"),
365              SUIT_MessageBox::Yes | SUIT_MessageBox::No, 
366              SUIT_MessageBox::Yes ) == SUIT_MessageBox::Yes;
367         if ( !continu ) {
368           // remove the corresponding actors from all views
369           RemoveVisualObjectWithActors( theEntry );
370           aVisualObj.reset();
371         }
372       }
373     }
374
375     return aVisualObj;
376   }
377
378
379   /*! Return active view window, if it instantiates SVTK_ViewWindow class,
380    *  overwise find or create corresponding view window, make it active and return it.
381    *  \note Active VVTK_ViewWindow can be returned, because it inherits SVTK_ViewWindow.
382    */
383   SVTK_ViewWindow* GetViewWindow (const SalomeApp_Module* theModule,
384                                   bool createIfNotFound)
385   {
386     SalomeApp_Application* anApp;
387     if (theModule)
388       anApp = theModule->getApp();
389     else
390       anApp = dynamic_cast<SalomeApp_Application*>
391         (SUIT_Session::session()->activeApplication());
392
393     if (anApp) {
394       if (SVTK_ViewWindow* aView = dynamic_cast<SVTK_ViewWindow*>(anApp->desktop()->activeWindow()))
395         return aView;
396
397       SUIT_ViewManager* aViewManager =
398         anApp->getViewManager(SVTK_Viewer::Type(), createIfNotFound);
399       if (aViewManager) {
400         if (SUIT_ViewWindow* aViewWindow = aViewManager->getActiveView()) {
401           if (SVTK_ViewWindow* aView = dynamic_cast<SVTK_ViewWindow*>(aViewWindow)) {
402             aViewWindow->raise();
403             aViewWindow->setFocus();
404             return aView;
405           }
406         }
407       }
408     }
409     return NULL;
410   }
411
412   SVTK_ViewWindow* FindVtkViewWindow (SUIT_ViewManager* theMgr,
413                                       SUIT_ViewWindow * theWindow)
414   {
415     if( !theMgr )
416       return NULL;
417
418     QVector<SUIT_ViewWindow*> views = theMgr->getViews();
419     if( views.contains( theWindow ) )
420       return GetVtkViewWindow( theWindow );
421     else
422       return NULL;
423   }
424
425   SVTK_ViewWindow* GetVtkViewWindow(SUIT_ViewWindow* theWindow){
426     return dynamic_cast<SVTK_ViewWindow*>(theWindow);
427   }
428
429 /*  SUIT_ViewWindow* GetActiveWindow()
430   {
431     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
432     if( !app )
433       return NULL;
434     SUIT_ViewManager* mgr = app->activeViewManager();
435     if( mgr )
436       return mgr->getActiveView();
437     else
438       return NULL;
439   }*/
440
441   SVTK_ViewWindow* GetCurrentVtkView(){
442     return GetVtkViewWindow( GetActiveWindow() );
443   }
444
445
446   void RepaintCurrentView()
447   {
448     if (SVTK_ViewWindow* wnd = GetCurrentVtkView())
449     {
450       try {
451 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
452         OCC_CATCH_SIGNALS;
453 #endif
454         wnd->getRenderer()->Render();
455         wnd->Repaint(false);
456       }
457       catch (...) {
458 #ifdef _DEBUG_
459         MESSAGE ( "Exception in SMESHGUI_VTKUtils::RepaintCurrentView()" );
460 #endif
461         OnVisuException();
462       }
463     }
464   }
465
466   void RepaintViewWindow(SVTK_ViewWindow* theWindow)
467   {
468     try {
469 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
470       OCC_CATCH_SIGNALS;
471 #endif
472       theWindow->getRenderer()->Render();
473       theWindow->Repaint();
474     }
475     catch (...) {
476 #ifdef _DEBUG_
477       MESSAGE ( "Exception in SMESHGUI_VTKUtils::RepaintViewWindow(SVTK_ViewWindow*)" );
478 #endif
479       OnVisuException();
480     }
481   }
482
483   void RenderViewWindow(SVTK_ViewWindow* theWindow)
484   {
485     try {
486 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
487       OCC_CATCH_SIGNALS;
488 #endif
489       theWindow->getRenderer()->Render();
490       theWindow->Repaint();
491     }
492     catch (...) {
493 #ifdef _DEBUG_
494       MESSAGE ( "Exception in SMESHGUI_VTKUtils::RenderViewWindow(SVTK_ViewWindow*)" );
495 #endif
496       OnVisuException();
497     }
498   }
499
500   void FitAll(){
501     if(SVTK_ViewWindow* wnd = GetCurrentVtkView() ){
502       try {
503 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
504         OCC_CATCH_SIGNALS;
505 #endif
506         wnd->onFitAll();
507         wnd->Repaint();
508       }
509       catch (...) {
510 #ifdef _DEBUG_
511         MESSAGE ( "Exception in SMESHGUI_VTKUtils::FitAll()" );
512 #endif
513         OnVisuException();
514       }
515     }
516   }
517
518
519   SMESH_Actor* FindActorByEntry(SUIT_ViewWindow *theWindow,
520                                 const char* theEntry)
521   {
522     if(SVTK_ViewWindow* aViewWindow = GetVtkViewWindow(theWindow)){
523       vtkRenderer *aRenderer = aViewWindow->getRenderer();
524       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
525       vtkActorCollection *aCollection = aCopy.GetActors();
526       aCollection->InitTraversal();
527       while(vtkActor *anAct = aCollection->GetNextActor()){
528         if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
529           if(anActor->hasIO()){
530             Handle(SALOME_InteractiveObject) anIO = anActor->getIO();
531             if(anIO->hasEntry() && strcmp(anIO->getEntry(),theEntry) == 0){
532               return anActor;
533             }
534           }
535         }
536       }
537     }
538     return NULL;
539   }
540
541
542   SMESH_Actor* FindActorByEntry(const char* theEntry){
543     return FindActorByEntry(GetActiveWindow(),theEntry);
544   }
545
546
547   SMESH_Actor* FindActorByObject(CORBA::Object_ptr theObject){
548     SalomeApp_Application* app = dynamic_cast<SalomeApp_Application*>( SUIT_Session::session()->activeApplication() );
549     if( !app )
550       return NULL;
551
552     if(!CORBA::is_nil(theObject)){
553       _PTR(Study) aStudy = GetActiveStudyDocument();
554       CORBA::String_var anIOR = app->orb()->object_to_string( theObject );
555       _PTR(SObject) aSObject = aStudy->FindObjectIOR(anIOR.in());
556       if(aSObject){
557         CORBA::String_var anEntry = aSObject->GetID().c_str();
558         return FindActorByEntry(anEntry.in());
559       }
560     }
561     return NULL;
562   }
563
564
565   SMESH_Actor* CreateActor(_PTR(Study) theStudy,
566                            const char* theEntry,
567                            int theIsClear)
568   {
569     SMESH_Actor *anActor = NULL;
570     CORBA::Long anId = theStudy->StudyId();
571     if(TVisualObjPtr aVisualObj = GetVisualObj(anId,theEntry)){
572       _PTR(SObject) aSObj = theStudy->FindObjectID(theEntry);
573       if(aSObj){
574         _PTR(GenericAttribute) anAttr;
575         if(aSObj->FindAttribute(anAttr,"AttributeName")){
576           _PTR(AttributeName) aName = anAttr;
577           std::string aNameVal = aName->Value();
578           anActor = SMESH_Actor::New(aVisualObj,theEntry,aNameVal.c_str(),theIsClear);
579         }
580
581         SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_narrow( SMESH::SObjectToObject( aSObj ));
582         if(!CORBA::is_nil(aGroup))
583         {
584           SALOMEDS::Color aColor = aGroup->GetColor();
585           if( !( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 ) )
586           {
587             int r = 0, g = 0, b = 0;
588             SMESH::GetColor( "SMESH", "fill_color", r, g, b, QColor( 0, 170, 255 ) );
589             aColor.R = (float)r / 255.0;
590             aColor.G = (float)g / 255.0;
591             aColor.B = (float)b / 255.0;
592             aGroup->SetColor( aColor );
593           }
594           if( aGroup->GetType() == SMESH::NODE )
595             anActor->SetNodeColor( aColor.R, aColor.G, aColor.B );
596           else if( aGroup->GetType() == SMESH::EDGE )
597             anActor->SetEdgeColor( aColor.R, aColor.G, aColor.B );
598           else if( aGroup->GetType() == SMESH::ELEM0D )
599             anActor->Set0DColor( aColor.R, aColor.G, aColor.B );
600           else
601             anActor->SetSufaceColor( aColor.R, aColor.G, aColor.B );
602         }
603       }
604     }
605     return anActor;
606   }
607
608
609   void DisplayActor( SUIT_ViewWindow *theWnd, SMESH_Actor* theActor){
610     if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(theWnd)){
611       try {
612 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
613         OCC_CATCH_SIGNALS;
614 #endif
615         vtkWnd->AddActor(theActor);
616         vtkWnd->Repaint();
617       }
618       catch (...) {
619 #ifdef _DEBUG_
620         MESSAGE ( "Exception in SMESHGUI_VTKUtils::DisplayActor()" );
621 #endif
622         OnVisuException();
623       }
624     }
625   }
626
627
628   void RemoveActor( SUIT_ViewWindow *theWnd, SMESH_Actor* theActor){
629     if(SVTK_ViewWindow* vtkWnd = GetVtkViewWindow(theWnd)){
630       vtkWnd->RemoveActor(theActor);
631       if(theActor->hasIO()){
632         Handle(SALOME_InteractiveObject) anIO = theActor->getIO();
633         if(anIO->hasEntry()){
634           std::string anEntry = anIO->getEntry();
635           SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>( vtkWnd->getViewManager()->study() );
636           int aStudyId = aStudy->id();
637           TVisualObjCont::key_type aKey(aStudyId,anEntry);
638           VISUAL_OBJ_CONT.erase(aKey);
639         }
640       }
641       theActor->Delete();
642       vtkWnd->Repaint();
643     }
644   }
645
646   //================================================================================
647   /*!
648    * \brief Return true if there are no SMESH actors in a view
649    */
650   //================================================================================
651
652   bool noSmeshActors(SUIT_ViewWindow *theWnd)
653   {
654     if(SVTK_ViewWindow* aViewWindow = GetVtkViewWindow(theWnd)) {
655       vtkRenderer *aRenderer = aViewWindow->getRenderer();
656       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
657       vtkActorCollection *aCollection = aCopy.GetActors();
658       aCollection->InitTraversal();
659       while(vtkActor *anAct = aCollection->GetNextActor())
660         if(dynamic_cast<SMESH_Actor*>(anAct))
661           return false;
662     }
663     return true;
664   }
665
666   bool UpdateView(SUIT_ViewWindow *theWnd, EDisplaing theAction, const char* theEntry)
667   {
668     bool OK = false;
669     SVTK_ViewWindow* aViewWnd = GetVtkViewWindow(theWnd);
670     if (!aViewWnd)
671       return OK;
672
673     {
674       OK = true;
675       vtkRenderer *aRenderer = aViewWnd->getRenderer();
676       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
677       vtkActorCollection *aCollection = aCopy.GetActors();
678       aCollection->InitTraversal();
679
680       switch (theAction) {
681       case eDisplayAll: {
682         while (vtkActor *anAct = aCollection->GetNextActor()) {
683           if (SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)) {
684             anActor->SetVisibility(true);
685           }
686         }
687         break;
688       }
689       case eDisplayOnly:
690       case eEraseAll: {
691         while (vtkActor *anAct = aCollection->GetNextActor()) {
692           if (SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)) {
693             anActor->SetVisibility(false);
694           }
695         }
696       }
697       default: {
698         if (SMESH_Actor *anActor = FindActorByEntry(theWnd,theEntry)) {
699           switch (theAction) {
700             case eDisplay:
701             case eDisplayOnly:
702               anActor->SetVisibility(true);
703               if (theAction == eDisplayOnly) aRenderer->ResetCameraClippingRange();
704               break;
705             case eErase:
706               anActor->SetVisibility(false);
707               break;
708           }
709         } else {
710           switch (theAction) {
711           case eDisplay:
712           case eDisplayOnly:
713             {
714               SalomeApp_Study* aStudy = dynamic_cast<SalomeApp_Study*>(theWnd->getViewManager()->study());
715               _PTR(Study) aDocument = aStudy->studyDS();
716               // Pass non-visual objects (hypotheses, etc.), return true in this case
717               CORBA::Long anId = aDocument->StudyId();
718               TVisualObjPtr aVisualObj;
719               if ( (aVisualObj = GetVisualObj(anId,theEntry)) && aVisualObj->IsValid())
720               {
721                 if ((anActor = CreateActor(aDocument,theEntry,true))) {
722                   bool needFitAll = noSmeshActors(theWnd); // fit for the first object only
723                   DisplayActor(theWnd,anActor);
724                   // FitAll(); - PAL16770(Display of a group performs an automatic fit all)
725                   if (needFitAll) FitAll();
726                 } else {
727                   OK = false;
728                 }
729               }
730               break;
731             }
732           }
733         }
734       }
735       }
736     }
737     return OK;
738   }
739
740
741   bool UpdateView(EDisplaing theAction, const char* theEntry){
742     SalomeApp_Study* aStudy = dynamic_cast< SalomeApp_Study* >( GetActiveStudy() );
743     SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( aStudy->application() );
744     SUIT_ViewWindow *aWnd = app->activeViewManager()->getActiveView();
745     return UpdateView(aWnd,theAction,theEntry);
746   }
747
748   void UpdateView(){
749     if(SVTK_ViewWindow* aWnd = SMESH::GetCurrentVtkView()){
750       LightApp_SelectionMgr* mgr = SMESHGUI::selectionMgr();
751       SALOME_ListIO selected; mgr->selectedObjects( selected );
752
753       if( selected.Extent() == 0){
754         vtkRenderer* aRenderer = aWnd->getRenderer();
755         VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
756         vtkActorCollection *aCollection = aCopy.GetActors();
757         aCollection->InitTraversal();
758         while(vtkActor *anAct = aCollection->GetNextActor()){
759           if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
760             if(anActor->hasIO())
761               if (!Update(anActor->getIO(),anActor->GetVisibility()))
762                 break; // avoid multiple warinings if visu failed
763           }
764         }
765       }else{
766         SALOME_ListIteratorOfListIO anIter( selected );
767         for( ; anIter.More(); anIter.Next()){
768           Handle(SALOME_InteractiveObject) anIO = anIter.Value();
769           if ( !Update(anIO,true) )
770             break; // avoid multiple warinings if visu failed
771         }
772       }
773       RepaintCurrentView();
774     }
775   }
776
777
778   bool Update(const Handle(SALOME_InteractiveObject)& theIO, bool theDisplay)
779   {
780     _PTR(Study) aStudy = GetActiveStudyDocument();
781     CORBA::Long anId = aStudy->StudyId();
782     if ( TVisualObjPtr aVisualObj = SMESH::GetVisualObj(anId,theIO->getEntry())) {
783       if ( theDisplay )
784         UpdateView(SMESH::eDisplay,theIO->getEntry());
785       return true;
786     }
787     return false;
788   }
789
790
791   void UpdateSelectionProp( SMESHGUI* theModule ) {
792     if( !theModule )
793       return;
794
795     SalomeApp_Application* app = dynamic_cast< SalomeApp_Application* >( theModule->application() );
796     if( !app )
797     {
798       MESSAGE( "UpdateSelectionProp: Application is null" );
799       return;
800     }
801
802     SUIT_ViewManager* vm = app->activeViewManager();
803     if( !vm )
804     {
805       MESSAGE( "UpdateSelectionProp: View manager is null" );
806       return;
807     }
808
809     QVector<SUIT_ViewWindow*> views = vm->getViews();
810
811     SUIT_ResourceMgr* mgr = SMESH::GetResourceMgr( theModule );
812     if( !mgr )
813     {
814       MESSAGE( "UpdateSelectionProp: Resource manager is null" );
815       return;
816     }
817
818     QColor aHiColor = mgr->colorValue( "SMESH", "selection_object_color", Qt::white ),
819            aSelColor = mgr->colorValue( "SMESH", "selection_element_color", Qt::yellow ),
820            aPreColor = mgr->colorValue( "SMESH", "highlight_color", Qt::cyan );
821
822     int SW = mgr->integerValue( "SMESH", "selection_width", 5 ),
823         PW = mgr->integerValue( "SMESH", "highlight_width", 5 );
824
825     // adjust highlight_width to the width of mesh entities
826     int aElem0DSize = mgr->integerValue("SMESH", "elem0d_size", 5);
827     int aLineWidth  = mgr->integerValue("SMESH", "element_width", 1);
828     int maxSize = aElem0DSize;
829     if (aElem0DSize > maxSize) maxSize = aElem0DSize;
830     if (aLineWidth > maxSize) maxSize = aLineWidth;
831     if (PW < maxSize + 2) PW = maxSize + 2;
832
833     double SP1 = mgr->doubleValue( "SMESH", "selection_precision_node", 0.025 ),
834            SP2 = mgr->doubleValue( "SMESH", "selection_precision_element", 0.001 ),
835            SP3 = mgr->doubleValue( "SMESH", "selection_precision_object", 0.025 );
836
837     for ( int i=0, n=views.count(); i<n; i++ ){
838       // update VTK viewer properties
839       if(SVTK_ViewWindow* aVtkView = GetVtkViewWindow( views[i] )){
840         // mesh element selection
841         aVtkView->SetSelectionProp(aSelColor.red()/255.,
842                                    aSelColor.green()/255.,
843                                    aSelColor.blue()/255.,
844                                    SW );
845         // tolerances
846         aVtkView->SetSelectionTolerance(SP1, SP2, SP3);
847
848         // pre-selection
849         aVtkView->SetPreselectionProp(aPreColor.red()/255.,
850                                       aPreColor.green()/255.,
851                                       aPreColor.blue()/255.,
852                                       PW);
853         // update actors
854         vtkRenderer* aRenderer = aVtkView->getRenderer();
855         VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
856         vtkActorCollection *aCollection = aCopy.GetActors();
857         aCollection->InitTraversal();
858         while(vtkActor *anAct = aCollection->GetNextActor()){
859           if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
860             anActor->SetHighlightColor(aHiColor.red()/255.,
861                                        aHiColor.green()/255.,
862                                        aHiColor.blue()/255.);
863             anActor->SetPreHighlightColor(aPreColor.red()/255.,
864                                           aPreColor.green()/255.,
865                                           aPreColor.blue()/255.);
866           }
867         }
868       }
869     }
870   }
871
872
873   //----------------------------------------------------------------------------
874   SVTK_Selector*
875   GetSelector(SUIT_ViewWindow *theWindow)
876   {
877     if(SVTK_ViewWindow* aWnd = GetVtkViewWindow(theWindow))
878       return aWnd->GetSelector();
879
880     return NULL;
881   }
882
883   void SetFilter(const Handle(VTKViewer_Filter)& theFilter,
884                  SVTK_Selector* theSelector)
885   {
886     if (theSelector)
887       theSelector->SetFilter(theFilter);
888   }
889
890   Handle(VTKViewer_Filter) GetFilter(int theId, SVTK_Selector* theSelector)
891   {
892     return theSelector->GetFilter(theId);
893   }
894
895   bool IsFilterPresent(int theId, SVTK_Selector* theSelector)
896   {
897     return theSelector->IsFilterPresent(theId);
898   }
899
900   void RemoveFilter(int theId, SVTK_Selector* theSelector)
901   {
902     theSelector->RemoveFilter(theId);
903   }
904
905   void RemoveFilters(SVTK_Selector* theSelector)
906   {
907     for ( int id = SMESH::NodeFilter; theSelector && id < SMESH::LastFilter; id++ )
908       theSelector->RemoveFilter( id );
909   }
910
911   bool IsValid(SALOME_Actor* theActor, int theCellId,
912                SVTK_Selector* theSelector)
913   {
914     return theSelector->IsValid(theActor,theCellId);
915   }
916
917
918   //----------------------------------------------------------------------------
919   void SetPointRepresentation(bool theIsVisible){
920     if(SVTK_ViewWindow* aViewWindow = GetCurrentVtkView()){
921       vtkRenderer *aRenderer = aViewWindow->getRenderer();
922       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
923       vtkActorCollection *aCollection = aCopy.GetActors();
924       aCollection->InitTraversal();
925       while(vtkActor *anAct = aCollection->GetNextActor()){
926         if(SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>(anAct)){
927           if(anActor->GetVisibility()){
928             anActor->SetPointRepresentation(theIsVisible);
929           }
930         }
931       }
932       RepaintCurrentView();
933     }
934   }
935
936
937   void SetPickable(SMESH_Actor* theActor){
938     if(SVTK_ViewWindow* aWnd = GetCurrentVtkView()){
939       int anIsAllPickable = (theActor == NULL);
940       vtkRenderer *aRenderer = aWnd->getRenderer();
941       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
942       vtkActorCollection *aCollection = aCopy.GetActors();
943       aCollection->InitTraversal();
944       while(vtkActor *anAct = aCollection->GetNextActor()){
945         if(SALOME_Actor *anActor = dynamic_cast<SALOME_Actor*>(anAct)){
946           if(anActor->GetVisibility()){
947             anActor->SetPickable(anIsAllPickable);
948           }
949         }
950       }
951       if(theActor)
952         theActor->SetPickable(!anIsAllPickable);
953       RepaintCurrentView();
954     }
955   }
956
957
958   //----------------------------------------------------------------------------
959   int GetNameOfSelectedNodes(SVTK_Selector* theSelector,
960                              const Handle(SALOME_InteractiveObject)& theIO,
961                              QString& theName)
962   {
963     theName = "";
964     TColStd_IndexedMapOfInteger aMapIndex;
965     theSelector->GetIndex(theIO,aMapIndex);
966
967     for(int i = 1; i <= aMapIndex.Extent(); i++)
968       theName += QString(" %1").arg(aMapIndex(i));
969
970     return aMapIndex.Extent();
971   }
972
973   int GetNameOfSelectedElements(SVTK_Selector* theSelector,
974                                 const Handle(SALOME_InteractiveObject)& theIO,
975                                 QString& theName)
976   {
977     theName = "";
978     TColStd_IndexedMapOfInteger aMapIndex;
979     theSelector->GetIndex(theIO,aMapIndex);
980
981     typedef std::set<int> TIdContainer;
982     TIdContainer anIdContainer;
983     for( int i = 1; i <= aMapIndex.Extent(); i++)
984       anIdContainer.insert(aMapIndex(i));
985
986     TIdContainer::const_iterator anIter = anIdContainer.begin();
987     for( ; anIter != anIdContainer.end(); anIter++)
988       theName += QString(" %1").arg(*anIter);
989
990     return aMapIndex.Extent();
991   }
992
993
994   int GetEdgeNodes(SVTK_Selector* theSelector,
995                    const TVisualObjPtr& theVisualObject,
996                    int& theId1,
997                    int& theId2)
998   {
999     const SALOME_ListIO& selected = theSelector->StoredIObjects();
1000
1001     if ( selected.Extent() != 1 )
1002       return -1;
1003
1004     Handle(SALOME_InteractiveObject) anIO = selected.First();
1005     if ( anIO.IsNull() || !anIO->hasEntry() )
1006       return -1;
1007
1008     TColStd_IndexedMapOfInteger aMapIndex;
1009     theSelector->GetIndex( anIO, aMapIndex );
1010     if ( aMapIndex.Extent() != 2 )
1011       return -1;
1012
1013     int anObjId = -1, anEdgeNum = -1;
1014     for ( int i = 1; i <= aMapIndex.Extent(); i++ ) {
1015       int aVal = aMapIndex( i );
1016       if ( aVal > 0 )
1017         anObjId = aVal;
1018       else
1019         anEdgeNum = abs( aVal ) - 1;
1020     }
1021
1022     if ( anObjId == -1 || anEdgeNum == -1 )
1023       return -1;
1024
1025     return theVisualObject->GetEdgeNodes( anObjId, anEdgeNum, theId1, theId2 ) ? 1 : -1;
1026   }
1027
1028   //----------------------------------------------------------------------------
1029   int GetNameOfSelectedNodes(LightApp_SelectionMgr *theMgr,
1030                              const Handle(SALOME_InteractiveObject)& theIO,
1031                              QString& theName)
1032   {
1033     theName = "";
1034     if(theIO->hasEntry()){
1035       if(FindActorByEntry(theIO->getEntry())){
1036         TColStd_IndexedMapOfInteger aMapIndex;
1037         theMgr->GetIndexes(theIO,aMapIndex);
1038         for(int i = 1; i <= aMapIndex.Extent(); i++){
1039           theName += QString(" %1").arg(aMapIndex(i));
1040         }
1041         return aMapIndex.Extent();
1042       }
1043     }
1044     return -1;
1045   }
1046
1047   int GetNameOfSelectedNodes(LightApp_SelectionMgr *theMgr, QString& theName){
1048     theName = "";
1049     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1050     if(selected.Extent() == 1){
1051       Handle(SALOME_InteractiveObject) anIO = selected.First();
1052       return GetNameOfSelectedNodes(theMgr,anIO,theName);
1053     }
1054     return -1;
1055   }
1056
1057
1058   int GetNameOfSelectedElements(LightApp_SelectionMgr *theMgr,
1059                                 const Handle(SALOME_InteractiveObject)& theIO,
1060                                 QString& theName)
1061   {
1062     theName = "";
1063     if(theIO->hasEntry()){
1064       if(FindActorByEntry(theIO->getEntry())){
1065         TColStd_IndexedMapOfInteger aMapIndex;
1066         theMgr->GetIndexes(theIO,aMapIndex);
1067         typedef std::set<int> TIdContainer;
1068         TIdContainer anIdContainer;
1069         for( int i = 1; i <= aMapIndex.Extent(); i++)
1070           anIdContainer.insert(aMapIndex(i));
1071         TIdContainer::const_iterator anIter = anIdContainer.begin();
1072         for( ; anIter != anIdContainer.end(); anIter++){
1073           theName += QString(" %1").arg(*anIter);
1074         }
1075         return aMapIndex.Extent();
1076       }
1077     }
1078     return -1;
1079   }
1080
1081
1082   int GetNameOfSelectedElements(LightApp_SelectionMgr *theMgr, QString& theName)
1083   {
1084     theName = "";
1085     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1086
1087     if( selected.Extent() == 1){
1088       Handle(SALOME_InteractiveObject) anIO = selected.First();
1089       return GetNameOfSelectedElements(theMgr,anIO,theName);
1090     }
1091     return -1;
1092   }
1093
1094   int GetSelected(LightApp_SelectionMgr*       theMgr,
1095                   TColStd_IndexedMapOfInteger& theMap,
1096                   const bool                   theIsElement)
1097   {
1098     theMap.Clear();
1099     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1100
1101     if ( selected.Extent() == 1 )
1102     {
1103       Handle(SALOME_InteractiveObject) anIO = selected.First();
1104       if ( anIO->hasEntry() ) {
1105         theMgr->GetIndexes( anIO, theMap );
1106       }
1107     }
1108     return theMap.Extent();
1109   }
1110
1111
1112   int GetEdgeNodes( LightApp_SelectionMgr* theMgr, int& theId1, int& theId2 )
1113   {
1114     SALOME_ListIO selected; theMgr->selectedObjects( selected );
1115
1116     if ( selected.Extent() != 1 )
1117       return -1;
1118
1119     Handle(SALOME_InteractiveObject) anIO = selected.First();
1120     if ( anIO.IsNull() || !anIO->hasEntry() )
1121       return -1;
1122
1123     SMESH_Actor *anActor = SMESH::FindActorByEntry( anIO->getEntry() );
1124     if ( anActor == 0 )
1125       return -1;
1126
1127     TColStd_IndexedMapOfInteger aMapIndex;
1128     theMgr->GetIndexes( anIO, aMapIndex );
1129     if ( aMapIndex.Extent() != 2 )
1130       return -1;
1131
1132     int anObjId = -1, anEdgeNum = -1;
1133     for ( int i = 1; i <= aMapIndex.Extent(); i++ ) {
1134       int aVal = aMapIndex( i );
1135       if ( aVal > 0 )
1136         anObjId = aVal;
1137       else
1138         anEdgeNum = abs( aVal );
1139     }
1140
1141     if ( anObjId == -1 || anEdgeNum == -1 )
1142       return -1;
1143
1144     return anActor->GetObject()->GetEdgeNodes( anObjId, anEdgeNum, theId1, theId2 ) ? 1 : -1;
1145   }
1146
1147   void SetControlsPrecision( const long theVal )
1148   {
1149     if( SVTK_ViewWindow* aWnd = SMESH::GetCurrentVtkView() )
1150     {
1151       vtkRenderer *aRenderer = aWnd->getRenderer();
1152       VTK::ActorCollectionCopy aCopy(aRenderer->GetActors());
1153       vtkActorCollection *aCollection = aCopy.GetActors();
1154       aCollection->InitTraversal();
1155
1156       while ( vtkActor *anAct = aCollection->GetNextActor())
1157       {
1158         if ( SMESH_Actor *anActor = dynamic_cast<SMESH_Actor*>( anAct ) )
1159         {
1160           anActor->SetControlsPrecision( theVal );
1161           anActor->SetControlMode( anActor->GetControlMode() );
1162         }
1163       }
1164
1165     }
1166   }
1167 } // end of namespace SMESH