Salome HOME
5e962796a3cd8d4d092d71924647089200ac0c1e
[modules/smesh.git] / src / SMESH_I / SMESH_Gen_i.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 //  File   : SMESH_Gen_i.cxx
23 //  Author : Paul RASCLE, EDF
24 //  Module : SMESH
25
26 #include <TopExp.hxx>
27 #include <TopExp_Explorer.hxx>
28 #include <TopoDS.hxx>
29 #include <TopoDS_Iterator.hxx>
30 #include <TopoDS_Compound.hxx>
31 #include <TopoDS_CompSolid.hxx>
32 #include <TopoDS_Solid.hxx>
33 #include <TopoDS_Shell.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TopoDS_Wire.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Vertex.hxx>
38 #include <TopoDS_Shape.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <gp_Pnt.hxx>
44 #include <BRep_Tool.hxx>
45 #include <TCollection_AsciiString.hxx>
46 #include <OSD.hxx>
47 #include <BRepPrimAPI_MakeSphere.hxx>
48 #include <BRepPrimAPI_MakeCylinder.hxx>
49 #include <BRepPrimAPI_MakeBox.hxx>
50
51
52 #ifdef WIN32
53  #include <windows.h>
54  #include <process.h>
55 #else
56  #include <dlfcn.h>
57 #endif
58
59 #ifdef WIN32
60  #define LibHandle HMODULE
61  #define LoadLib( name ) LoadLibrary( name )
62  #define GetProc GetProcAddress
63  #define UnLoadLib( handle ) FreeLibrary( handle );
64 #else
65  #define LibHandle void*
66  #define LoadLib( name ) dlopen( name, RTLD_LAZY )
67  #define GetProc dlsym
68  #define UnLoadLib( handle ) dlclose( handle );
69 #endif
70
71 #include "SMESH_Gen_i.hxx"
72 #include "SMESH_version.h"
73
74 #include "DriverMED_W_SMESHDS_Mesh.h"
75 #include "DriverMED_R_SMESHDS_Mesh.h"
76 #ifdef WITH_CGNS
77 #include "DriverCGNS_Read.hxx"
78 #endif
79 #include "MED_Factory.hxx"
80 #include "SMDS_EdgePosition.hxx"
81 #include "SMDS_FacePosition.hxx"
82 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
83 #include "SMDS_SetIterator.hxx"
84 #include "SMDS_SpacePosition.hxx"
85 #include "SMDS_VertexPosition.hxx"
86 #include "SMESHDS_Document.hxx"
87 #include "SMESHDS_Group.hxx"
88 #include "SMESHDS_GroupOnGeom.hxx"
89 #include "SMESH_Algo_i.hxx"
90 #include "SMESH_File.hxx"
91 #include "SMESH_Group.hxx"
92 #include "SMESH_Group_i.hxx"
93 #include "SMESH_Hypothesis.hxx"
94 #include "SMESH_Hypothesis_i.hxx"
95 #include "SMESH_Mesh.hxx"
96 #include "SMESH_MeshEditor.hxx"
97 #include "SMESH_Mesh_i.hxx"
98 #include "SMESH_PreMeshInfo.hxx"
99 #include "SMESH_PythonDump.hxx"
100 #include "SMESH_ControlsDef.hxx"
101 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
102
103 #include CORBA_SERVER_HEADER(SMESH_Group)
104 #include CORBA_SERVER_HEADER(SMESH_Filter)
105 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
106
107
108 #include <GEOM_Client.hxx>
109
110 #include <Basics_Utils.hxx>
111 #include <Basics_DirUtils.hxx>
112 #include <HDFOI.hxx>
113 #include <OpUtil.hxx>
114 #include <SALOMEDS_Tool.hxx>
115 #include <SALOME_Container_i.hxx>
116 #include <SALOME_LifeCycleCORBA.hxx>
117 #include <SALOME_NamingService.hxx>
118 #include <Utils_CorbaException.hxx>
119 #include <Utils_ExceptHandlers.hxx>
120 #include <Utils_SINGLETON.hxx>
121 #include <utilities.h>
122
123 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
124 #include CORBA_CLIENT_HEADER(SALOME_Session)
125
126 // helpers about SALOME::GenericObj
127 #include <SALOMEDS_wrap.hxx>
128 #include <SALOMEDS_Attributes_wrap.hxx>
129 #include <GEOM_wrap.hxx>
130
131 #include <map>
132 #include <fstream>
133 #include <cstdio>
134 #include <cstdlib>
135
136 using namespace std;
137 using SMESH::TPythonDump;
138 using SMESH::TVar;
139
140 #define NUM_TMP_FILES 2
141
142 #ifdef _DEBUG_
143 static int MYDEBUG = 0;
144 #else
145 static int MYDEBUG = 0;
146 #endif
147
148 // Static variables definition
149 GEOM::GEOM_Gen_var      SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
150 CORBA::ORB_var          SMESH_Gen_i::myOrb;
151 PortableServer::POA_var SMESH_Gen_i::myPoa;
152 SALOME_NamingService*   SMESH_Gen_i::myNS  = NULL;
153 SALOME_LifeCycleCORBA*  SMESH_Gen_i::myLCC = NULL;
154 SMESH_Gen_i*            SMESH_Gen_i::mySMESHGen = NULL;
155
156
157 const int nbElemPerDiagonal = 10;
158
159 //=============================================================================
160 /*!
161  *  GetServant [ static ]
162  *
163  *  Get servant of the CORBA object
164  */
165 //=============================================================================
166
167 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
168 {
169   if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
170     return NULL;
171   try {
172     PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
173     return aServant;
174   }
175   catch (...) {
176     INFOS( "GetServant - Unknown exception was caught!!!" );
177     return NULL;
178   }
179 }
180
181 //=============================================================================
182 /*!
183  *  SObjectToObject [ static ]
184  *
185  *  Get CORBA object corresponding to the SALOMEDS::SObject
186  */
187 //=============================================================================
188
189 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
190 {
191   SALOMEDS::GenericAttribute_wrap anAttr;
192   CORBA::Object_var anObj;
193   if ( !theSObject->_is_nil() ) {
194     try {
195       if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
196         SALOMEDS::AttributeIOR_wrap anIOR  = anAttr;
197         CORBA::String_var aValue = anIOR->Value();
198         if( strcmp( aValue, "" ) != 0 )
199           anObj = GetORB()->string_to_object( aValue );
200       }
201     }
202     catch( ... ) {
203       INFOS( "SObjectToObject - Unknown exception was caught!!!" );
204     }
205   }
206   return anObj;
207 }
208
209 //=============================================================================
210 /*!
211  *  GetNS [ static ]
212  *
213  *  Get SALOME_NamingService object
214  */
215 //=============================================================================
216
217 SALOME_NamingService* SMESH_Gen_i::GetNS()
218 {
219   if ( myNS == NULL ) {
220     myNS = SINGLETON_<SALOME_NamingService>::Instance();
221     ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
222     myNS->init_orb( GetORB() );
223   }
224   return myNS;
225 }
226
227 //=============================================================================
228 /*!
229  *  GetLCC [ static ]
230  *
231  *  Get SALOME_LifeCycleCORBA object
232  */
233 //=============================================================================
234 SALOME_LifeCycleCORBA*  SMESH_Gen_i::GetLCC() {
235   if ( myLCC == NULL ) {
236     myLCC = new SALOME_LifeCycleCORBA( GetNS() );
237   }
238   return myLCC;
239 }
240
241
242 //=============================================================================
243 /*!
244  *  GetGeomEngine [ static ]
245  *
246  *  Get GEOM::GEOM_Gen reference
247  */
248 //=============================================================================
249 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
250   //CCRT GEOM::GEOM_Gen_var aGeomEngine =
251   //CCRT   GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
252   //CCRT return aGeomEngine._retn();
253   if(CORBA::is_nil(myGeomGen))
254   {
255     Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
256     myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
257   }
258   return myGeomGen;
259 }
260
261 //=============================================================================
262 /*!
263  *  SMESH_Gen_i::SMESH_Gen_i
264  *
265  *  Default constructor: not for use
266  */
267 //=============================================================================
268
269 SMESH_Gen_i::SMESH_Gen_i()
270 {
271   INFOS( "SMESH_Gen_i::SMESH_Gen_i : default constructor" );
272 }
273
274 //=============================================================================
275 /*!
276  *  SMESH_Gen_i::SMESH_Gen_i
277  *
278  *  Standard constructor, used with Container
279  */
280 //=============================================================================
281
282 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr            orb,
283                           PortableServer::POA_ptr   poa,
284                           PortableServer::ObjectId* contId,
285                           const char*               instanceName,
286                           const char*               interfaceName )
287   : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
288 {
289   MESSAGE( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
290
291   myOrb = CORBA::ORB::_duplicate(orb);
292   myPoa = PortableServer::POA::_duplicate(poa);
293
294   _thisObj = this ;
295   _id = myPoa->activate_object( _thisObj );
296
297   myIsEmbeddedMode = false;
298   myShapeReader = NULL;  // shape reader
299   mySMESHGen = this;
300   myIsHistoricalPythonDump = true;
301   myToForgetMeshDataOnHypModif = false;
302
303   // set it in standalone mode only
304   //OSD::SetSignal( true );
305
306   // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
307   // find out mode (embedded or standalone) here else
308   // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
309   // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
310   if ( SALOME_NamingService* ns = GetNS() )
311   {
312     CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
313     SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
314     if ( !session->_is_nil() )
315     {
316       CORBA::String_var str_host = session->getHostname();
317       CORBA::Long        s_pid = session->getPID();
318       string my_host = Kernel_Utils::GetHostname();
319 #ifdef WIN32
320       long    my_pid = (long)_getpid();
321 #else
322       long    my_pid = (long) getpid();
323 #endif
324       SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
325     }
326   }
327 }
328
329 //=============================================================================
330 /*!
331  *  SMESH_Gen_i::~SMESH_Gen_i
332  *
333  *  Destructor
334  */
335 //=============================================================================
336
337 SMESH_Gen_i::~SMESH_Gen_i()
338 {
339   MESSAGE( "SMESH_Gen_i::~SMESH_Gen_i" );
340
341   // delete hypothesis creators
342   map<string, GenericHypothesisCreator_i*>::iterator itHyp;
343   for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
344   {
345     delete (*itHyp).second;
346   }
347   myHypCreatorMap.clear();
348
349   // Clear study contexts data
350   map<int, StudyContext*>::iterator it;
351   for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
352     delete it->second;
353   }
354   myStudyContextMap.clear();
355   // delete shape reader
356   if ( myShapeReader )
357     delete myShapeReader;
358 }
359 //=============================================================================
360 /*!
361  *  SMESH_Gen_i::getHypothesisCreator
362  *
363  *  Get hypothesis creator
364  */
365 //=============================================================================
366 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
367                                                               const char* theLibName,
368                                                               std::string& thePlatformLibName)
369   throw (SALOME::SALOME_Exception)
370 {
371   std::string aPlatformLibName;
372   /* It's Need to tranlate lib name for WIN32 or X platform */
373   if ( theLibName && theLibName[0] != '\0'  )
374   {
375     int libNameLen = strlen(theLibName);
376     //check for old format "libXXXXXXX.so"
377     if (libNameLen > 7 &&
378         !strncmp( theLibName, "lib", 3 ) &&
379         !strcmp( theLibName+libNameLen-3, ".so" ))
380     {
381       //the old format
382 #ifdef WIN32
383       aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
384 #else
385       aPlatformLibName = theLibName;
386 #endif
387     }
388     else
389     {
390       //try to use new format
391 #ifdef WIN32
392       aPlatformLibName = theLibName;
393       aPlatformLibName += ".dll";
394 #else
395       aPlatformLibName = "lib" + std::string( theLibName ) + ".so";
396 #endif
397     }
398   }
399   thePlatformLibName = aPlatformLibName;
400
401   Unexpect aCatch(SALOME_SalomeException);
402   if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
403
404   typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
405   GenericHypothesisCreator_i* aCreator;
406   try
407   {
408     // check, if creator for this hypothesis type already exists
409     if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
410     {
411       // load plugin library
412       if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
413       LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
414       if (!libHandle)
415       {
416         // report any error, if occured
417 #ifndef WIN32
418         const char* anError = dlerror();
419         throw(SALOME_Exception(anError));
420 #else
421         throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
422 #endif
423       }
424
425       // get method, returning hypothesis creator
426       if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
427       GetHypothesisCreator procHandle =
428         (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
429       if (!procHandle)
430       {
431         throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
432         UnLoadLib(libHandle);
433       }
434
435       // get hypothesis creator
436       if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
437       aCreator = procHandle(theHypName);
438       if (!aCreator)
439       {
440         throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
441       }
442       // map hypothesis creator to a hypothesis name
443       myHypCreatorMap[string(theHypName)] = aCreator;
444       return aCreator;
445     }
446     else
447     {
448       return myHypCreatorMap[string(theHypName)];
449     }
450   }
451   catch (SALOME_Exception& S_ex)
452   {
453     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
454   }
455   return aCreator;
456 }
457
458 //=============================================================================
459 /*!
460  *  SMESH_Gen_i::createHypothesis
461  *
462  *  Create hypothesis of given type
463  */
464 //=============================================================================
465 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
466                                                           const char* theLibName)
467 {
468   SMESH_Hypothesis_i* myHypothesis_i = 0;
469   SMESH::SMESH_Hypothesis_var hypothesis_i;
470   std::string aPlatformLibName;
471   GenericHypothesisCreator_i* aCreator =
472     getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
473
474   // create a new hypothesis object, store its ref. in studyContext
475   myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
476   if (myHypothesis_i)
477   {
478     myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
479     CORBA::String_var hypName = myHypothesis_i->GetName();
480     myHypCreatorMap[ hypName.in() ] = aCreator;
481
482     // activate the CORBA servant of hypothesis
483     hypothesis_i = myHypothesis_i->_this();
484     int nextId = RegisterObject( hypothesis_i );
485     if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
486     else        { nextId = 0; } // avoid "unused variable" warning in release mode
487   }
488   return hypothesis_i._retn();
489 }
490
491 //=============================================================================
492 /*!
493  *  SMESH_Gen_i::createMesh
494  *
495  *  Create empty mesh on shape
496  */
497 //=============================================================================
498 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
499   throw ( SALOME::SALOME_Exception )
500 {
501   Unexpect aCatch(SALOME_SalomeException);
502   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
503
504   // Get or create the GEOM_Client instance
505   try {
506     // create a new mesh object servant, store it in a map in study context
507     SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
508     // create a new mesh object
509     MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
510     meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
511
512     // activate the CORBA servant of Mesh
513     SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
514     int nextId = RegisterObject( mesh );
515     if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
516     else        { nextId = 0; } // avoid "unused variable" warning in release mode
517     return mesh._retn();
518   }
519   catch (SALOME_Exception& S_ex) {
520     THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
521   }
522   return SMESH::SMESH_Mesh::_nil();
523 }
524
525 //=============================================================================
526 /*!
527  *  SMESH_Gen_i::GetShapeReader
528  *
529  *  Get shape reader
530  */
531 //=============================================================================
532 GEOM_Client* SMESH_Gen_i::GetShapeReader()
533 {
534   // create shape reader if necessary
535   if ( !myShapeReader )
536     myShapeReader = new GEOM_Client(GetContainerRef());
537   ASSERT( myShapeReader );
538   return myShapeReader;
539 }
540
541 //=============================================================================
542 /*!
543  *  SMESH_Gen_i::SetGeomEngine
544  *
545  *  Set GEOM::GEOM_Gen reference
546  */
547 //=============================================================================
548 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
549 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
550 {
551   //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
552   //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
553   myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
554   //return myGeomGen;
555 }
556
557 //=============================================================================
558 /*!
559  *  SMESH_Gen_i::SetEmbeddedMode
560  *
561  *  Set current mode
562  */
563 //=============================================================================
564
565 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
566 {
567   myIsEmbeddedMode = theMode;
568   MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
569
570   if ( !myIsEmbeddedMode ) {
571     //PAL10867: disable signals catching with "noexcepthandler" option
572     char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
573     if (!envNoCatchSignals || !atoi(envNoCatchSignals))
574     {
575       bool raiseFPE;
576 #ifdef _DEBUG_
577       raiseFPE = true;
578       char* envDisableFPE = getenv("DISABLE_FPE");
579       if (envDisableFPE && atoi(envDisableFPE))
580         raiseFPE = false;
581 #else
582       raiseFPE = false;
583 #endif
584       OSD::SetSignal( raiseFPE );
585     }
586     // else OSD::SetSignal() is called in GUI
587   }
588 }
589
590 //=============================================================================
591 /*!
592  *  SMESH_Gen_i::IsEmbeddedMode
593  *
594  *  Get current mode
595  */
596 //=============================================================================
597
598 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
599 {
600   return myIsEmbeddedMode;
601 }
602
603 //=============================================================================
604 /*!
605  *  SMESH_Gen_i::SetCurrentStudy
606  *
607  *  Set current study
608  */
609 //=============================================================================
610
611 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
612 {
613   setCurrentStudy( theStudy );
614 }
615
616 void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
617                                    bool                theStudyIsBeingClosed)
618 {
619   int curStudyId = GetCurrentStudyID();
620   myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
621   // create study context, if it doesn't exist and set current study
622   int studyId = GetCurrentStudyID();
623   if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
624     myStudyContextMap[ studyId ] = new StudyContext;
625
626   // myCurrentStudy may be nil
627   if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
628     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
629     SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
630     if( !GEOM_var->_is_nil() )
631       aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
632     // NPAL16168, issue 0020210
633     // Let meshes update their data depending on GEOM groups that could change
634     if ( curStudyId != studyId )
635     {
636       CORBA::String_var compDataType = ComponentDataType();
637       SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
638       if ( !me->_is_nil() ) {
639         SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
640         for ( ; anIter->More(); anIter->Next() ) {
641           SALOMEDS::SObject_wrap so = anIter->Value();
642           CORBA::Object_var     ior = SObjectToObject( so );
643           if ( SMESH_Mesh_i*   mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
644             mesh->CheckGeomModif();
645         }
646       }
647     }
648   }
649 }
650
651 //=============================================================================
652 /*!
653  *  SMESH_Gen_i::GetCurrentStudy
654  *
655  *  Get current study
656  */
657 //=============================================================================
658
659 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
660 {
661   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
662   if ( GetCurrentStudyID() < 0 )
663     return SALOMEDS::Study::_nil();
664   return SALOMEDS::Study::_duplicate( myCurrentStudy );
665 }
666
667 //=============================================================================
668 /*!
669  *  SMESH_Gen_i::GetCurrentStudyContext
670  *
671  *  Get current study context
672  */
673 //=============================================================================
674 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
675 {
676   if ( !CORBA::is_nil( myCurrentStudy ) &&
677        myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
678     return myStudyContextMap[ myCurrentStudy->StudyId() ];
679   else
680     return 0;
681 }
682
683 //=============================================================================
684 /*!
685  *  SMESH_Gen_i::CreateHypothesis
686  *
687  *  Create hypothesis/algorothm of given type and publish it in the study
688  */
689 //=============================================================================
690
691 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
692                                                            const char* theLibName )
693   throw ( SALOME::SALOME_Exception )
694 {
695   Unexpect aCatch(SALOME_SalomeException);
696   // Create hypothesis/algorithm
697   SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
698
699   // Publish hypothesis/algorithm in the study
700   if ( CanPublishInStudy( hyp ) ) {
701     SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
702     if ( !aSO->_is_nil() ) {
703       // Update Python script
704       TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
705                     << theHypName << "', '" << theLibName << "')";
706     }
707   }
708
709   return hyp._retn();
710 }
711
712 //================================================================================
713 /*!
714  * \brief Return a hypothesis holding parameter values corresponding either to the mesh
715  * existing on the given geometry or to size of the geometry.
716  *  \param theHypType - hypothesis type name
717  *  \param theLibName - plugin library name
718  *  \param theMesh - The mesh of interest
719  *  \param theGeom - The shape to get parameter values from
720  *  \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
721  *     in a study and used to compute the mesh, or a temporary one created just to pass
722  *     parameter values
723  */
724 //================================================================================
725
726 SMESH::SMESH_Hypothesis_ptr
727 SMESH_Gen_i::GetHypothesisParameterValues (const char*           theHypType,
728                                            const char*           theLibName,
729                                            SMESH::SMESH_Mesh_ptr theMesh,
730                                            GEOM::GEOM_Object_ptr theGeom,
731                                            CORBA::Boolean        byMesh)
732   throw ( SALOME::SALOME_Exception )
733 {
734   Unexpect aCatch(SALOME_SalomeException);
735   if ( byMesh && CORBA::is_nil( theMesh ) )
736     return SMESH::SMESH_Hypothesis::_nil();
737   if ( byMesh && CORBA::is_nil( theGeom ) )
738     return SMESH::SMESH_Hypothesis::_nil();
739
740   // -----------------------------------------------
741   // find hypothesis used to mesh theGeom
742   // -----------------------------------------------
743
744   // get mesh and shape
745   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
746   TopoDS_Shape shape = GeomObjectToShape( theGeom );
747   if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
748     return SMESH::SMESH_Hypothesis::_nil();
749   ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
750
751   // create a temporary hypothesis to know its dimension
752   SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
753   SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
754   if ( !hypServant )
755     return SMESH::SMESH_Hypothesis::_nil();
756   ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
757
758   if ( byMesh ) {
759     // look for a hypothesis of theHypType used to mesh the shape
760     if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
761     {
762       // check local shape
763       SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
764       int nbLocalHyps = aHypList->length();
765       for ( int i = 0; i < nbLocalHyps; i++ ) {
766         CORBA::String_var hypName = aHypList[i]->GetName();
767         if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
768           return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
769       }
770       // check super shapes
771       TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
772       while ( nbLocalHyps == 0 && itShape.More() ) {
773         GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
774         if ( ! CORBA::is_nil( geomObj )) {
775           SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
776           nbLocalHyps = aHypList->length();
777           for ( int i = 0; i < nbLocalHyps; i++ )
778             if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
779               return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
780         }
781         itShape.Next();
782       }
783     }
784
785     // let the temporary hypothesis find out somehow parameter values by mesh
786     if ( hyp->SetParametersByMesh( mesh, shape ))
787       return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
788   }
789   else {
790     double diagonal = 0;
791     if ( mesh )
792       diagonal = mesh->GetShapeDiagonalSize();
793     else
794       diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
795     ::SMESH_Hypothesis::TDefaults dflts;
796     dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
797     dflts._nbSegments = myGen.GetDefaultNbSegments();
798     dflts._shape      = &shape;
799     // let the temporary hypothesis initialize it's values
800     if ( hyp->SetParametersByDefaults( dflts, mesh ))
801       return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
802   }
803
804   return SMESH::SMESH_Hypothesis::_nil();
805 }
806
807 //=============================================================================
808 /*!
809  * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
810  *  \param [in] theHyp - the hypothesis of interest
811  *  \param [out] theMesh - the sole mesh using \a theHyp
812  *  \param [out] theShape - the sole geometry \a theHyp is assigned to
813  *  \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
814  *
815  * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
816  * considered as SAME sub-mesh => result is \c true.
817  * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
818  * a shape to which an hyp being edited is assigned.
819  */
820 //=============================================================================
821
822 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
823                                                     SMESH::SMESH_Mesh_out       theMesh,
824                                                     GEOM::GEOM_Object_out       theShape)
825 {
826   if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
827     return false;
828
829   // get Mesh component SO
830   CORBA::String_var compDataType = ComponentDataType();
831   SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
832   if ( CORBA::is_nil( comp ))
833     return false;
834
835   // look for child SO of meshes
836   SMESH::SMESH_Mesh_var foundMesh;
837   TopoDS_Shape          foundShape;
838   bool                  isSole = true;
839   SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
840   for ( ; meshIter->More() && isSole; meshIter->Next() )
841   {
842     SALOMEDS::SObject_wrap curSO = meshIter->Value();
843     CORBA::Object_var        obj = SObjectToObject( curSO );
844     SMESH_Mesh_i*         mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
845     if ( ! mesh_i )
846       continue;
847
848     // look for a sole shape where theHyp is assigned
849     bool isHypFound = false;
850     const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
851     ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
852     for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
853     {
854       const THypList& hyps = s2hypsIt.Value();
855       THypList::const_iterator h = hyps.begin();
856       for ( ; h != hyps.end(); ++h )
857         if ( (*h)->GetID() == theHyp->GetId() )
858           break;
859       if ( h != hyps.end()) // theHyp found
860       {
861         isHypFound = true;
862         if ( ! foundShape.IsNull() &&
863              ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
864         {
865           foundShape.Nullify();
866           isSole = false;
867           break;
868         }
869         foundShape = s2hypsIt.Key();
870       }
871     } // loop on assigned hyps
872
873     if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
874     {
875       if ( !foundMesh->_is_nil() ) // not a sole mesh
876       {
877         GEOM::GEOM_Object_var s1 = mesh_i   ->GetShapeToMesh();
878         GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
879         if ( ! ( isSole = s1->IsSame( s2 )))
880           break;
881       }
882       foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
883     }
884
885   } // loop on meshes
886
887   if ( isSole &&
888        ! foundMesh->_is_nil() &&
889        ! foundShape.IsNull() )
890   {
891     theMesh  = foundMesh._retn();
892     theShape = ShapeToGeomObject( foundShape );
893     return ( !theMesh->_is_nil() && !theShape->_is_nil() );
894   }
895   return false;
896 }
897
898 //=============================================================================
899 /*!
900  * Sets number of segments per diagonal of boundary box of geometry by which
901  * default segment length of appropriate 1D hypotheses is defined
902  */
903 //=============================================================================
904
905 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
906   throw ( SALOME::SALOME_Exception )
907 {
908   if ( theNbSegments > 0 )
909     myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
910   else
911     THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
912 }
913 //=============================================================================
914   /*!
915    * \brief Sets default number of segments per edge
916    */
917 //=============================================================================
918 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
919   throw ( SALOME::SALOME_Exception )
920 {
921   if ( theNbSegments > 0 )
922     myGen.SetDefaultNbSegments( int(theNbSegments) );
923   else
924     THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
925 }
926
927 //=============================================================================
928 /*!
929   Set an option value
930 */
931 //=============================================================================
932
933 void SMESH_Gen_i::SetOption(const char* name, const char* value)
934 {
935   if ( name && value && strlen( value ) > 0 )
936   {
937     string msgToGUI;
938     if ( strcmp(name, "historical_python_dump") == 0 )
939     {
940       myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
941       msgToGUI = "preferences/SMESH/historical_python_dump/";
942       msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
943     }
944     else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
945     {
946       myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
947       msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
948       msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
949     }
950
951     // update preferences in case if SetOption() is invoked from python console
952     if ( !msgToGUI.empty() )
953     {
954       CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
955       SALOME::Session_var session = SALOME::Session::_narrow( obj );
956       if ( !CORBA::is_nil( session ) )
957         session->emitMessageOneWay(msgToGUI.c_str());
958     }
959   }
960 }
961
962 //=============================================================================
963 /*!
964   Return an option value
965 */
966 //=============================================================================
967
968 char* SMESH_Gen_i::GetOption(const char* name)
969 {
970   if ( name )
971   {
972     if ( strcmp(name, "historical_python_dump") == 0 )
973     {
974       return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
975     }
976     if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
977     {
978       return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
979     }
980   }
981   return CORBA::string_dup( "" );
982 }
983
984 //=============================================================================
985 /*!
986  *  SMESH_Gen_i::CreateMesh
987  *
988  *  Create empty mesh on a shape and publish it in the study
989  */
990 //=============================================================================
991
992 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
993      throw ( SALOME::SALOME_Exception )
994 {
995   Unexpect aCatch(SALOME_SalomeException);
996   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
997   // create mesh
998   SMESH::SMESH_Mesh_var mesh = this->createMesh();
999   // set shape
1000   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1001   ASSERT( meshServant );
1002   meshServant->SetShape( theShapeObject );
1003
1004   // publish mesh in the study
1005   if ( CanPublishInStudy( mesh ) ) {
1006     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1007     aStudyBuilder->NewCommand();  // There is a transaction
1008     SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1009     aStudyBuilder->CommitCommand();
1010     if ( !aSO->_is_nil() ) {
1011       // Update Python script
1012       TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1013     }
1014   }
1015
1016   return mesh._retn();
1017 }
1018
1019 //=============================================================================
1020 /*!
1021  *  SMESH_Gen_i::CreateEmptyMesh
1022  *
1023  *  Create empty mesh
1024  */
1025 //=============================================================================
1026
1027 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1028      throw ( SALOME::SALOME_Exception )
1029 {
1030   Unexpect aCatch(SALOME_SalomeException);
1031   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1032   // create mesh
1033   SMESH::SMESH_Mesh_var mesh = this->createMesh();
1034
1035   // publish mesh in the study
1036   if ( CanPublishInStudy( mesh ) ) {
1037     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1038     aStudyBuilder->NewCommand();  // There is a transaction
1039     SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1040     aStudyBuilder->CommitCommand();
1041     if ( !aSO->_is_nil() ) {
1042       // Update Python script
1043       TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1044     }
1045   }
1046
1047   return mesh._retn();
1048 }
1049
1050 namespace
1051 {
1052   //================================================================================
1053   /*!
1054    * \brief Throws an exception in case if the file can't be read
1055    */
1056   //================================================================================
1057
1058   void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1059   {
1060     SMESH_File f ( theFileName );
1061     if ( !f )
1062     {
1063       if ( !f.error().empty() )
1064         THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1065
1066       THROW_SALOME_CORBA_EXCEPTION
1067         (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1068          SALOME::BAD_PARAM );
1069     }
1070   }
1071 }
1072
1073 //=============================================================================
1074 /*!
1075  *  SMESH_Gen_i::CreateMeshFromUNV
1076  *
1077  *  Create mesh and import data from UNV file
1078  */
1079 //=============================================================================
1080
1081 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1082   throw ( SALOME::SALOME_Exception )
1083 {
1084   Unexpect aCatch(SALOME_SalomeException);
1085
1086   checkFileReadable( theFileName );
1087
1088   SMESH::SMESH_Mesh_var aMesh = createMesh();
1089   string aFileName;
1090   // publish mesh in the study
1091   if ( CanPublishInStudy( aMesh ) ) {
1092     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1093     aStudyBuilder->NewCommand();  // There is a transaction
1094     SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
1095     aStudyBuilder->CommitCommand();
1096     if ( !aSO->_is_nil() ) {
1097       // Update Python script
1098       TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1099     }
1100   }
1101
1102   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1103   ASSERT( aServant );
1104   aServant->ImportUNVFile( theFileName );
1105
1106   // Dump creation of groups
1107   SMESH::ListOfGroups_var groups = aServant->GetGroups();
1108
1109   aServant->GetImpl().GetMeshDS()->Modified();
1110   return aMesh._retn();
1111 }
1112
1113 //=============================================================================
1114 /*!
1115  *  SMESH_Gen_i::CreateMeshFromMED
1116  *
1117  *  Create mesh and import data from MED file
1118  */
1119 //=============================================================================
1120
1121 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1122                                                            SMESH::DriverMED_ReadStatus& theStatus,
1123                                                            const char* theCommandNameForPython,
1124                                                            const char* theFileNameForPython)
1125 {
1126 #ifdef WIN32
1127   char bname[ _MAX_FNAME ];
1128   _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1129   string aFileName = bname;
1130 #else
1131   string aFileName = basename( theFileNameForPython );
1132 #endif
1133   // Retrieve mesh names from the file
1134   DriverMED_R_SMESHDS_Mesh myReader;
1135   myReader.SetFile( theFileName );
1136   myReader.SetMeshId( -1 );
1137   Driver_Mesh::Status aStatus;
1138   list<string> aNames = myReader.GetMeshNames(aStatus);
1139   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1140   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1141
1142   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1143
1144   // Python Dump
1145   TPythonDump aPythonDump;
1146   aPythonDump << "([";
1147
1148   if (theStatus == SMESH::DRS_OK) {
1149     SALOMEDS::StudyBuilder_var aStudyBuilder;
1150     if ( GetCurrentStudyID() > -1 )
1151     {
1152       aStudyBuilder = myCurrentStudy->NewBuilder();
1153       aStudyBuilder->NewCommand();  // There is a transaction
1154     }
1155     aResult->length( aNames.size() );
1156     int i = 0;
1157
1158     // Iterate through all meshes and create mesh objects
1159     for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1160     {
1161       // Python Dump
1162       if (i > 0) aPythonDump << ", ";
1163
1164       // create mesh
1165       SMESH::SMESH_Mesh_var mesh = createMesh();
1166
1167       // publish mesh in the study
1168       SALOMEDS::SObject_wrap aSO;
1169       if ( CanPublishInStudy( mesh ) )
1170         // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1171         // - as names of meshes are stored in MED file, we use them for data publishing
1172         // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1173         aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1174       if ( !aSO->_is_nil() ) {
1175         // Python Dump
1176         aPythonDump << aSO;
1177       } else {
1178         // Python Dump
1179         aPythonDump << "mesh_" << i;
1180       }
1181
1182       // Read mesh data (groups are published automatically by ImportMEDFile())
1183       SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1184       ASSERT( meshServant );
1185       SMESH::DriverMED_ReadStatus status1 =
1186         meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1187       if (status1 > theStatus)
1188         theStatus = status1;
1189
1190       aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1191       meshServant->GetImpl().GetMeshDS()->Modified();
1192     }
1193     if ( !aStudyBuilder->_is_nil() )
1194       aStudyBuilder->CommitCommand();
1195   }
1196
1197   // Update Python script
1198   aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1199   }
1200   // Dump creation of groups
1201   for ( int i = 0; i < aResult->length(); ++i )
1202     SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1203
1204   return aResult._retn();
1205 }
1206
1207 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1208                                                      SMESH::DriverMED_ReadStatus& theStatus)
1209   throw ( SALOME::SALOME_Exception )
1210 {
1211   Unexpect aCatch(SALOME_SalomeException);
1212   checkFileReadable( theFileName );
1213
1214   SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1215   return result;
1216 }
1217
1218 //=============================================================================
1219 /*!
1220  *  SMESH_Gen_i::CreateMeshFromSAUV
1221  *
1222  *  Create mesh and import data from SAUV file
1223  */
1224 //=============================================================================
1225
1226 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1227                                                       SMESH::DriverMED_ReadStatus& theStatus)
1228      throw ( SALOME::SALOME_Exception )
1229 {
1230   Unexpect aCatch(SALOME_SalomeException);
1231   checkFileReadable( theFileName );
1232
1233   std::string sauvfilename(theFileName);
1234   std::string medfilename(theFileName);
1235   medfilename += ".med";
1236   std::string cmd;
1237 #ifdef WIN32
1238   cmd = "%PYTHONBIN% ";
1239 #else
1240   cmd = "python ";
1241 #endif
1242   cmd += "-c \"";
1243   cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1244   cmd += "\"";
1245   system(cmd.c_str());
1246   SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1247 #ifdef WIN32
1248   cmd = "%PYTHONBIN% ";
1249 #else
1250   cmd = "python ";
1251 #endif
1252   cmd += "-c \"";
1253   cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1254   cmd += "\"";
1255   system(cmd.c_str());
1256   return result;
1257 }
1258
1259 //=============================================================================
1260 /*!
1261  *  SMESH_Gen_i::CreateMeshFromSTL
1262  *
1263  *  Create mesh and import data from STL file
1264  */
1265 //=============================================================================
1266
1267 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1268   throw ( SALOME::SALOME_Exception )
1269 {
1270   Unexpect aCatch(SALOME_SalomeException);
1271   checkFileReadable( theFileName );
1272
1273   SMESH::SMESH_Mesh_var aMesh = createMesh();
1274   //string aFileName;
1275 #ifdef WIN32
1276   char bname[ _MAX_FNAME ];
1277   _splitpath( theFileName, NULL, NULL, bname, NULL );
1278   string aFileName = bname;
1279 #else
1280   string aFileName = basename( theFileName );
1281 #endif
1282   // publish mesh in the study
1283   if ( CanPublishInStudy( aMesh ) ) {
1284     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1285     aStudyBuilder->NewCommand();  // There is a transaction
1286     SALOMEDS::SObject_wrap aSO = PublishInStudy
1287       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1288     aStudyBuilder->CommitCommand();
1289     if ( !aSO->_is_nil() ) {
1290       // Update Python script
1291       TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1292     }
1293   }
1294
1295   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1296   ASSERT( aServant );
1297   aServant->ImportSTLFile( theFileName );
1298   aServant->GetImpl().GetMeshDS()->Modified();
1299   return aMesh._retn();
1300 }
1301
1302 //================================================================================
1303 /*!
1304  * \brief Create meshes and import data from the CGSN file
1305  */
1306 //================================================================================
1307
1308 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1309                                                       SMESH::DriverMED_ReadStatus& theStatus)
1310   throw ( SALOME::SALOME_Exception )
1311 {
1312   Unexpect aCatch(SALOME_SalomeException);
1313   checkFileReadable( theFileName );
1314
1315   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1316
1317 #ifdef WITH_CGNS
1318   // Retrieve nb meshes from the file
1319   DriverCGNS_Read myReader;
1320   myReader.SetFile( theFileName );
1321   Driver_Mesh::Status aStatus;
1322   int nbMeshes = myReader.GetNbMeshes(aStatus);
1323   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1324
1325   aResult->length( nbMeshes );
1326
1327   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1328
1329     // Python Dump
1330     TPythonDump aPythonDump;
1331     aPythonDump << "([";
1332
1333     if (theStatus == SMESH::DRS_OK)
1334     {
1335       SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1336       aStudyBuilder->NewCommand();  // There is a transaction
1337
1338       int i = 0;
1339
1340       // Iterate through all meshes and create mesh objects
1341       for ( ; i < nbMeshes; ++i )
1342       {
1343         // Python Dump
1344         if (i > 0) aPythonDump << ", ";
1345
1346         // create mesh
1347         SMESH::SMESH_Mesh_var mesh = createMesh();
1348         aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1349
1350         // Read mesh data (groups are published automatically by ImportMEDFile())
1351         SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1352         ASSERT( meshServant );
1353         string meshName;
1354         SMESH::DriverMED_ReadStatus status1 =
1355           meshServant->ImportCGNSFile( theFileName, i, meshName );
1356         if (status1 > theStatus)
1357           theStatus = status1;
1358
1359         meshServant->GetImpl().GetMeshDS()->Modified();
1360         // publish mesh in the study
1361         SALOMEDS::SObject_wrap aSO;
1362         if ( CanPublishInStudy( mesh ) )
1363           aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
1364
1365         // Python Dump
1366         if ( !aSO->_is_nil() ) {
1367           aPythonDump << aSO;
1368         }
1369         else {
1370           aPythonDump << "mesh_" << i;
1371         }
1372       }
1373       aStudyBuilder->CommitCommand();
1374     }
1375
1376     aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1377   }
1378   // Dump creation of groups
1379   for ( int i = 0; i < aResult->length(); ++i )
1380     SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1381 #else
1382   THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1383 #endif
1384
1385   return aResult._retn();
1386 }
1387
1388 //================================================================================
1389 /*!
1390  * \brief Create a mesh and import data from a GMF file
1391  */
1392 //================================================================================
1393
1394 SMESH::SMESH_Mesh_ptr
1395 SMESH_Gen_i::CreateMeshesFromGMF( const char*             theFileName,
1396                                   CORBA::Boolean          theMakeRequiredGroups,
1397                                   SMESH::ComputeError_out theError)
1398     throw ( SALOME::SALOME_Exception )
1399 {
1400   Unexpect aCatch(SALOME_SalomeException);
1401   checkFileReadable( theFileName );
1402
1403   SMESH::SMESH_Mesh_var aMesh = createMesh();
1404 #ifdef WIN32
1405   char bname[ _MAX_FNAME ];
1406   _splitpath( theFileName, NULL, NULL, bname, NULL );
1407   string aFileName = bname;
1408 #else
1409   string aFileName = basename( theFileName );
1410 #endif
1411   // publish mesh in the study
1412   if ( CanPublishInStudy( aMesh ) ) {
1413     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1414     aStudyBuilder->NewCommand();  // There is a transaction
1415     SALOMEDS::SObject_wrap aSO = PublishInStudy
1416       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1417     aStudyBuilder->CommitCommand();
1418     if ( !aSO->_is_nil() ) {
1419       // Update Python script
1420       TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1421                     << theFileName << "', "
1422                     << theMakeRequiredGroups << " )";
1423     }
1424   }
1425   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1426   ASSERT( aServant );
1427   theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1428   aServant->GetImpl().GetMeshDS()->Modified();
1429   return aMesh._retn();
1430 }
1431
1432
1433 //=============================================================================
1434 /*!
1435  *  SMESH_Gen_i::IsReadyToCompute
1436  *
1437  *  Returns true if mesh contains enough data to be computed
1438  */
1439 //=============================================================================
1440
1441 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1442                                               GEOM::GEOM_Object_ptr theShapeObject )
1443   throw ( SALOME::SALOME_Exception )
1444 {
1445   Unexpect aCatch(SALOME_SalomeException);
1446   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1447
1448   if ( CORBA::is_nil( theShapeObject ) )
1449     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1450                                   SALOME::BAD_PARAM );
1451
1452   if ( CORBA::is_nil( theMesh ) )
1453     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1454                                   SALOME::BAD_PARAM );
1455
1456   try {
1457     // get mesh servant
1458     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1459     ASSERT( meshServant );
1460     if ( meshServant ) {
1461       // get local TopoDS_Shape
1462       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1463       // call implementation
1464       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1465       return myGen.CheckAlgoState( myLocMesh, myLocShape );
1466     }
1467   }
1468   catch ( SALOME_Exception& S_ex ) {
1469     INFOS( "catch exception "<< S_ex.what() );
1470   }
1471   return false;
1472 }
1473
1474 //================================================================================
1475 /*!
1476  * \brief  Find SObject for an algo
1477  */
1478 //================================================================================
1479
1480 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1481 {
1482   if ( algo ) {
1483     if ( !myCurrentStudy->_is_nil() ) {
1484       // find algo in the study
1485       CORBA::String_var compDataType  = ComponentDataType();
1486       SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
1487       if ( !father->_is_nil() ) {
1488         SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
1489         for ( ; itBig->More(); itBig->Next() ) {
1490           SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1491           if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1492             SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1493             for ( ; algoIt->More(); algoIt->Next() ) {
1494               SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1495               CORBA::Object_var     algoIOR = SObjectToObject( algoSO );
1496               if ( !CORBA::is_nil( algoIOR )) {
1497                 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1498                 if ( impl && impl->GetImpl() == algo )
1499                   return algoSO._retn();
1500               }
1501             } // loop on algo SO's
1502             break;
1503           } // if algo tag
1504         } // SMESH component iterator
1505       }
1506     }
1507   }
1508   return SALOMEDS::SObject::_nil();
1509 }
1510
1511 //================================================================================
1512 /*!
1513  * \brief Return errors of mesh computation
1514  */
1515 //================================================================================
1516
1517 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1518                                                            GEOM::GEOM_Object_ptr theSubObject )
1519   throw ( SALOME::SALOME_Exception )
1520 {
1521   Unexpect aCatch(SALOME_SalomeException);
1522   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1523
1524   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1525     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1526
1527   if ( CORBA::is_nil( theMesh ) )
1528     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1529
1530   SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1531   try {
1532     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1533     {
1534       TopoDS_Shape shape;
1535       if(theMesh->HasShapeToMesh())
1536         shape = GeomObjectToShape( theSubObject );
1537       else
1538         shape = SMESH_Mesh::PseudoShape();
1539
1540       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1541
1542       error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1543       int nbErr = 0;
1544
1545       SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1546       const bool includeSelf = true, complexShapeFirst = true;
1547       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1548                                                                complexShapeFirst);
1549       while ( smIt->more() )
1550       {
1551         sm = smIt->next();
1552         // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1553         //   break;
1554         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1555         if ( error && !error->IsOK() )
1556         {
1557           if ( !( error->myAlgo ) &&
1558                !( error->myAlgo = sm->GetAlgo() ))
1559             continue;
1560           SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1561           errStruct.code       = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1562           errStruct.comment    = error->myComment.c_str();
1563           errStruct.subShapeID = sm->GetId();
1564           SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1565           if ( !algoSO->_is_nil() ) {
1566             CORBA::String_var algoName = algoSO->GetName();
1567             errStruct.algoName = algoName;
1568           }
1569           else {
1570             errStruct.algoName = error->myAlgo->GetName();
1571           }
1572           errStruct.hasBadMesh = !error->myBadElements.empty();
1573         }
1574       }
1575       error_array->length( nbErr );
1576     }
1577   }
1578   catch ( SALOME_Exception& S_ex ) {
1579     INFOS( "catch exception "<< S_ex.what() );
1580   }
1581
1582   return error_array._retn();
1583 }
1584
1585 //================================================================================
1586 /*!
1587  * \brief Return mesh elements preventing computation of a subshape
1588  */
1589 //================================================================================
1590
1591 SMESH::MeshPreviewStruct*
1592 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1593                                   CORBA::Short          theSubShapeID )
1594   throw ( SALOME::SALOME_Exception )
1595 {
1596   Unexpect aCatch(SALOME_SalomeException);
1597   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1598
1599   if ( CORBA::is_nil( theMesh ) )
1600     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1601
1602   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1603   try {
1604     // mesh servant
1605     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1606     {
1607       // mesh implementation
1608       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1609       // submesh by subshape id
1610       if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1611       {
1612         // compute error
1613         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1614         if ( error && !error->myBadElements.empty())
1615         {
1616           typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1617           typedef TNode2LocalIDMap::iterator         TNodeLocalID;
1618
1619           // get nodes of elements and count elements
1620           TNode2LocalIDMap mapNode2LocalID;
1621           list< TNodeLocalID > connectivity;
1622           int i, nbElements = 0, nbConnNodes = 0;
1623
1624           list<const SMDS_MeshElement*>::iterator elemIt  = error->myBadElements.begin();
1625           list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1626           for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1627           {
1628             SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1629             while ( nIt->more() )
1630               connectivity.push_back
1631                 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1632           }
1633           // fill node coords and assign local ids to the nodes
1634           int nbNodes = mapNode2LocalID.size();
1635           result->nodesXYZ.length( nbNodes );
1636           TNodeLocalID node2ID = mapNode2LocalID.begin();
1637           for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1638             node2ID->second = i;
1639             const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1640             result->nodesXYZ[i].x = node->X();
1641             result->nodesXYZ[i].y = node->Y();
1642             result->nodesXYZ[i].z = node->Z();
1643           }
1644           // fill connectivity
1645           result->elementConnectivities.length( nbConnNodes );
1646           list< TNodeLocalID >::iterator connIt = connectivity.begin();
1647           for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1648             result->elementConnectivities[i] = (*connIt)->second;
1649           }
1650           // fill element types
1651           result->elementTypes.length( nbElements );
1652           for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1653           {
1654             const SMDS_MeshElement* elem = *elemIt;
1655             result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1656             result->elementTypes[i].isPoly           = elem->IsPoly();
1657             result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1658           }
1659         }
1660       }
1661     }
1662   }
1663   catch ( SALOME_Exception& S_ex ) {
1664     INFOS( "catch exception "<< S_ex.what() );
1665   }
1666
1667   return result._retn();
1668 }
1669
1670 //================================================================================
1671 /*!
1672  * \brief Create a group of elements preventing computation of a sub-shape
1673  */
1674 //================================================================================
1675
1676 SMESH::ListOfGroups*
1677 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1678                                            CORBA::Short          theSubShapeID,
1679                                            const char*           theGroupName )
1680   throw ( SALOME::SALOME_Exception )
1681 {
1682   Unexpect aCatch(SALOME_SalomeException);
1683
1684   SMESH::ListOfGroups_var groups;
1685
1686   if ( CORBA::is_nil( theMesh ) )
1687     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1688
1689   try {
1690     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1691     {
1692       groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1693       TPythonDump() << groups << " = " << this
1694                     << ".MakeGroupsOfBadInputElements( "
1695                     << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1696     }
1697   }
1698   catch ( SALOME_Exception& S_ex ) {
1699     INFOS( "catch exception "<< S_ex.what() );
1700   }
1701   return groups._retn();
1702 }
1703
1704 //================================================================================
1705 /*!
1706  * \brief Returns errors of hypotheses definintion
1707  * \param theMesh - the mesh
1708  * \param theSubObject - the main or sub- shape
1709  * \retval SMESH::algo_error_array* - sequence of errors
1710  */
1711 //================================================================================
1712
1713 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1714                                                     GEOM::GEOM_Object_ptr theSubObject )
1715       throw ( SALOME::SALOME_Exception )
1716 {
1717   Unexpect aCatch(SALOME_SalomeException);
1718   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1719
1720   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1721     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1722
1723   if ( CORBA::is_nil( theMesh ) )
1724     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1725
1726   SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1727   try {
1728     SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1729     ASSERT( meshServant );
1730     if ( meshServant ) {
1731       TopoDS_Shape myLocShape;
1732       if(theMesh->HasShapeToMesh())
1733         myLocShape = GeomObjectToShape( theSubObject );
1734       else
1735         myLocShape = SMESH_Mesh::PseudoShape();
1736
1737       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1738       list< ::SMESH_Gen::TAlgoStateError > error_list;
1739       list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1740       // call ::SMESH_Gen::GetAlgoState()
1741       myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1742       error_array->length( error_list.size() );
1743       int i = 0;
1744       for ( error = error_list.begin(); error != error_list.end(); ++error )
1745       {
1746         // fill AlgoStateError structure
1747         SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1748         errStruct.state        = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1749         errStruct.algoDim      = error->_algoDim;
1750         errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1751         errStruct.algoName     = "";
1752         SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1753         if ( !algoSO->_is_nil() ) {
1754           CORBA::String_var algoName = algoSO->GetName();
1755           errStruct.algoName = algoName.in();
1756         }
1757       }
1758     }
1759   }
1760   catch ( SALOME_Exception& S_ex ) {
1761     INFOS( "catch exception "<< S_ex.what() );
1762   }
1763   return error_array._retn();
1764 }
1765
1766 //=============================================================================
1767 /*!
1768  *  SMESH_Gen_i::GetSubShapesId
1769  *
1770  *  Get sub-shapes unique ID's list
1771  */
1772 //=============================================================================
1773
1774 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1775                                             const SMESH::object_array& theListOfSubShapeObject )
1776      throw ( SALOME::SALOME_Exception )
1777 {
1778   Unexpect aCatch(SALOME_SalomeException);
1779   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1780
1781   SMESH::long_array_var shapesId = new SMESH::long_array;
1782   set<int> setId;
1783
1784   if ( CORBA::is_nil( theMainShapeObject ) )
1785     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1786                                   SALOME::BAD_PARAM );
1787
1788   try
1789     {
1790       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1791       TopTools_IndexedMapOfShape myIndexToShape;
1792       TopExp::MapShapes(myMainShape,myIndexToShape);
1793
1794       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1795         {
1796           GEOM::GEOM_Object_var aShapeObject
1797             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1798           if ( CORBA::is_nil( aShapeObject ) )
1799             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1800                                         SALOME::BAD_PARAM );
1801
1802           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
1803           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1804             {
1805               const TopoDS_Face& F = TopoDS::Face(exp.Current());
1806               setId.insert(myIndexToShape.FindIndex(F));
1807               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1808             }
1809           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1810             {
1811               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1812               setId.insert(myIndexToShape.FindIndex(E));
1813               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1814             }
1815           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1816             {
1817               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1818               setId.insert(myIndexToShape.FindIndex(V));
1819               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1820             }
1821         }
1822       shapesId->length(setId.size());
1823       set<int>::iterator iind;
1824       int i=0;
1825       for (iind = setId.begin(); iind != setId.end(); iind++)
1826         {
1827           if(MYDEBUG) SCRUTE((*iind));
1828           shapesId[i] = (*iind);
1829           if(MYDEBUG) SCRUTE(shapesId[i]);
1830           i++;
1831         }
1832     }
1833   catch (SALOME_Exception& S_ex)
1834     {
1835       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1836     }
1837
1838   return shapesId._retn();
1839 }
1840
1841 //=============================================================================
1842 /*!
1843  *  SMESH_Gen_i::Compute
1844  *
1845  *  Compute mesh on a shape
1846  */
1847 //=============================================================================
1848
1849 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1850                                      GEOM::GEOM_Object_ptr theShapeObject )
1851      throw ( SALOME::SALOME_Exception )
1852 {
1853   //MEMOSTAT;
1854   Unexpect aCatch(SALOME_SalomeException);
1855   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1856
1857   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1858     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1859                                   SALOME::BAD_PARAM );
1860
1861   if ( CORBA::is_nil( theMesh ) )
1862     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1863                                   SALOME::BAD_PARAM );
1864
1865   // Update Python script
1866   TPythonDump() << "isDone = " << this << ".Compute( "
1867                 << theMesh << ", " << theShapeObject << ")";
1868
1869   try {
1870     // get mesh servant
1871     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1872     meshServant->Load();
1873     ASSERT( meshServant );
1874     if ( meshServant ) {
1875       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1876       meshServant->CheckGeomModif();
1877       // get local TopoDS_Shape
1878       TopoDS_Shape myLocShape;
1879       if(theMesh->HasShapeToMesh())
1880         myLocShape = GeomObjectToShape( theShapeObject );
1881       else
1882         myLocShape = SMESH_Mesh::PseudoShape();
1883       // call implementation compute
1884       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1885       myGen.PrepareCompute( myLocMesh, myLocShape);
1886       bool ok = myGen.Compute( myLocMesh, myLocShape);
1887       meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1888       myLocMesh.GetMeshDS()->Modified();
1889       return ok;
1890     }
1891   }
1892   catch ( std::bad_alloc ) {
1893     INFOS( "Compute(): lack of memory" );
1894   }
1895   catch ( SALOME_Exception& S_ex ) {
1896     INFOS( "Compute(): catch exception "<< S_ex.what() );
1897   }
1898   catch ( ... ) {
1899     INFOS( "Compute(): unknown exception " );
1900   }
1901   return false;
1902 }
1903
1904 //=============================================================================
1905 /*!
1906  *  SMESH_Gen_i::CancelCompute
1907  *
1908  *  Cancel Compute mesh on a shape
1909  */
1910 //=============================================================================
1911
1912 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1913                                  GEOM::GEOM_Object_ptr theShapeObject )
1914 {
1915   SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1916   ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1917   TopoDS_Shape myLocShape;
1918   if(theMesh->HasShapeToMesh())
1919     myLocShape = GeomObjectToShape( theShapeObject );
1920   else
1921     myLocShape = SMESH_Mesh::PseudoShape();
1922   myGen.CancelCompute( myLocMesh, myLocShape);
1923 }
1924
1925 //=============================================================================
1926 /*!
1927  *  SMESH_Gen_i::Precompute
1928  *
1929  *  Compute mesh as preview till indicated dimension on shape
1930  */
1931 //=============================================================================
1932
1933 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1934                                                    GEOM::GEOM_Object_ptr theShapeObject,
1935                                                    SMESH::Dimension      theDimension,
1936                                                    SMESH::long_array&    theShapesId)
1937      throw ( SALOME::SALOME_Exception )
1938 {
1939   Unexpect aCatch(SALOME_SalomeException);
1940   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1941
1942   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1943     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1944                                   SALOME::BAD_PARAM );
1945
1946   if ( CORBA::is_nil( theMesh ) )
1947     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1948                                   SALOME::BAD_PARAM );
1949
1950   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1951   try {
1952     // get mesh servant
1953     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1954     meshServant->Load();
1955     ASSERT( meshServant );
1956     if ( meshServant ) {
1957       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1958       meshServant->CheckGeomModif();
1959       // get local TopoDS_Shape
1960       TopoDS_Shape myLocShape;
1961       if(theMesh->HasShapeToMesh())
1962         myLocShape = GeomObjectToShape( theShapeObject );
1963       else
1964         return result._retn();;
1965
1966       // call implementation compute
1967       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1968       TSetOfInt shapeIds;
1969       ::MeshDimension aDim = (MeshDimension)theDimension;
1970       if ( myGen.Compute( myLocMesh, myLocShape, false, false, aDim, &shapeIds ) )
1971       {
1972         int nbShapeId = shapeIds.size();
1973         theShapesId.length( nbShapeId );
1974         // iterates on shapes and collect mesh entities into mesh preview
1975         TSetOfInt::const_iterator idIt = shapeIds.begin();
1976         TSetOfInt::const_iterator idEnd = shapeIds.end();
1977         std::map< int, int > mapOfShIdNb;
1978         std::set< SMESH_TLink > setOfEdge;
1979         std::list< SMDSAbs_ElementType > listOfElemType;
1980         typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1981         typedef TNode2LocalIDMap::iterator         TNodeLocalID;
1982         TNode2LocalIDMap mapNode2LocalID;
1983         list< TNodeLocalID > connectivity;
1984         int i, nbConnNodes = 0;
1985         std::set< const SMESH_subMesh* > setOfVSubMesh;
1986         // iterates on shapes
1987         for ( ; idIt != idEnd; idIt++ )
1988         {
1989           if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
1990             continue;
1991           SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
1992           if ( !sm || !sm->IsMeshComputed() )
1993             continue;
1994
1995           const TopoDS_Shape& aSh = sm->GetSubShape();
1996           const int shDim = myGen.GetShapeDim( aSh );
1997           if ( shDim < 1 || shDim > theDimension )
1998             continue;
1999
2000           mapOfShIdNb[ *idIt ] = 0;
2001           theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2002
2003           SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2004           if ( !smDS ) continue;
2005
2006           if ( theDimension == SMESH::DIM_2D )
2007           {
2008             SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2009             while ( faceIt->more() )
2010             {
2011               const SMDS_MeshElement* face = faceIt->next();
2012               int aNbNode = face->NbNodes();
2013               if ( aNbNode > 4 )
2014                 aNbNode /= 2; // do not take into account additional middle nodes
2015
2016               SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2017               for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2018               {
2019                 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2020                 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2021                 {
2022                   listOfElemType.push_back( SMDSAbs_Edge );
2023                   connectivity.push_back
2024                     ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2025                   connectivity.push_back
2026                     ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2027                 }
2028                 node1 = node2;
2029               }
2030             }
2031           }
2032           else if ( theDimension == SMESH::DIM_1D )
2033           {
2034             SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2035             while ( nodeIt->more() )
2036             {
2037               listOfElemType.push_back( SMDSAbs_Node );
2038               connectivity.push_back
2039                 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2040             }
2041             // add corner nodes by first vertex from edge
2042             SMESH_subMeshIteratorPtr edgeSmIt =
2043               sm->getDependsOnIterator(/*includeSelf*/false,
2044                                        /*complexShapeFirst*/false);
2045             while ( edgeSmIt->more() )
2046             {
2047               SMESH_subMesh* vertexSM = edgeSmIt->next();
2048               // check that vertex is not already treated
2049               if ( !setOfVSubMesh.insert( vertexSM ).second )
2050                 continue;
2051               if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2052                 continue;
2053
2054               const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2055               SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2056               while ( nodeIt->more() )
2057               {
2058                 listOfElemType.push_back( SMDSAbs_Node );
2059                 connectivity.push_back
2060                   ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2061               }
2062             }
2063           }
2064         }
2065
2066         // fill node coords and assign local ids to the nodes
2067         int nbNodes = mapNode2LocalID.size();
2068         result->nodesXYZ.length( nbNodes );
2069         TNodeLocalID node2ID = mapNode2LocalID.begin();
2070         for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2071           node2ID->second = i;
2072           const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2073           result->nodesXYZ[i].x = node->X();
2074           result->nodesXYZ[i].y = node->Y();
2075           result->nodesXYZ[i].z = node->Z();
2076         }
2077         // fill connectivity
2078         result->elementConnectivities.length( nbConnNodes );
2079         list< TNodeLocalID >::iterator connIt = connectivity.begin();
2080         for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2081           result->elementConnectivities[i] = (*connIt)->second;
2082         }
2083
2084         // fill element types
2085         result->elementTypes.length( listOfElemType.size() );
2086         std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2087         std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2088         for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2089         {
2090           SMDSAbs_ElementType elemType = *typeIt;
2091           result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2092           result->elementTypes[i].isPoly           = false;
2093           result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2094         }
2095
2096         // correct number of shapes
2097         theShapesId.length( mapOfShIdNb.size() );
2098       }
2099     }
2100   }
2101   catch ( std::bad_alloc ) {
2102     INFOS( "Precompute(): lack of memory" );
2103   }
2104   catch ( SALOME_Exception& S_ex ) {
2105     INFOS( "Precompute(): catch exception "<< S_ex.what() );
2106   }
2107   catch ( ... ) {
2108     INFOS( "Precompute(): unknown exception " );
2109   }
2110   return result._retn();
2111 }
2112
2113
2114 //=============================================================================
2115 /*!
2116  *  SMESH_Gen_i::Evaluate
2117  *
2118  *  Evaluate mesh on a shape
2119  */
2120 //=============================================================================
2121
2122 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2123                                          GEOM::GEOM_Object_ptr theShapeObject)
2124 //                                     SMESH::long_array& theNbElems)
2125      throw ( SALOME::SALOME_Exception )
2126 {
2127   Unexpect aCatch(SALOME_SalomeException);
2128   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2129
2130   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2131     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2132                                   SALOME::BAD_PARAM );
2133
2134   if ( CORBA::is_nil( theMesh ) )
2135     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2136                                   SALOME::BAD_PARAM );
2137
2138   SMESH::long_array_var nbels = new SMESH::long_array;
2139   nbels->length(SMESH::Entity_Last);
2140   int i = SMESH::Entity_Node;
2141   for (; i < SMESH::Entity_Last; i++)
2142     nbels[i] = 0;
2143
2144   // Update Python script
2145   TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2146                 << theMesh << ", " << theShapeObject << ")";
2147
2148   try {
2149     // get mesh servant
2150     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2151     ASSERT( meshServant );
2152     if ( meshServant ) {
2153       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2154       meshServant->CheckGeomModif();
2155       // get local TopoDS_Shape
2156       TopoDS_Shape myLocShape;
2157       if(theMesh->HasShapeToMesh())
2158         myLocShape = GeomObjectToShape( theShapeObject );
2159       else
2160         myLocShape = SMESH_Mesh::PseudoShape();
2161       // call implementation compute
2162       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2163       MapShapeNbElems aResMap;
2164       /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2165       MapShapeNbElemsItr anIt = aResMap.begin();
2166       for(; anIt!=aResMap.end(); anIt++) {
2167         const vector<int>& aVec = (*anIt).second;
2168         for(i = SMESH::Entity_Node; i < aVec.size(); i++) {
2169           int nbElem = aVec[i];
2170           if ( nbElem < 0 ) // algo failed, check that it has reported a message
2171           {
2172             SMESH_subMesh* sm = anIt->first;
2173             SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2174             const SMESH_Algo* algo = myGen.GetAlgo( myLocMesh, sm->GetSubShape());
2175             if ( (algo && !error.get()) || error->IsOK() )
2176               error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2177           }
2178           else
2179           {
2180             nbels[i] += aVec[i];
2181           }
2182         }
2183       }
2184       return nbels._retn();
2185     }
2186   }
2187   catch ( std::bad_alloc ) {
2188     INFOS( "Evaluate(): lack of memory" );
2189   }
2190   catch ( SALOME_Exception& S_ex ) {
2191     INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2192   }
2193   catch ( ... ) {
2194     INFOS( "Evaluate(): unknown exception " );
2195   }
2196
2197   return nbels._retn();
2198 }
2199
2200 //================================================================================
2201 /*!
2202  * \brief Return geometrical object the given element is built on
2203  *  \param theMesh - the mesh the element is in
2204  *  \param theElementID - the element ID
2205  *  \param theGeomName - the name of the result geom object if it is not yet published
2206  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2207  */
2208 //================================================================================
2209
2210 GEOM::GEOM_Object_ptr
2211 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
2212                                        CORBA::Long            theElementID,
2213                                        const char*            theGeomName)
2214   throw ( SALOME::SALOME_Exception )
2215 {
2216   Unexpect aCatch(SALOME_SalomeException);
2217
2218   GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2219   if ( !geom->_is_nil() ) {
2220     GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2221     GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
2222
2223     // try to find the corresponding SObject
2224     SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2225     if ( SObj->_is_nil() ) // submesh can be not found even if published
2226     {
2227       // try to find published submesh
2228       GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2229       if ( !geom->IsMainShape() && list->length() == 1 ) {
2230         SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2231         SALOMEDS::ChildIterator_wrap it;
2232         if ( !mainSO->_is_nil() ) {
2233           it = myCurrentStudy->NewChildIterator( mainSO );
2234         }
2235         if ( !it->_is_nil() ) {
2236           for ( it->InitEx(true); it->More(); it->Next() ) {
2237             SALOMEDS::SObject_wrap      so = it->Value();
2238             CORBA::Object_var         obj = SObjectToObject( so );
2239             GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2240             if ( !subGeom->_is_nil() ) {
2241               GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2242               if ( subList->length() == 1 && list[0] == subList[0] ) {
2243                 SObj = so;
2244                 geom = subGeom;
2245                 break;
2246               }
2247             }
2248           }
2249         }
2250       }
2251     }
2252     if ( SObj->_is_nil() ) // publish a new subshape
2253       SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2254
2255     // return only published geometry
2256     if ( !SObj->_is_nil() ) {
2257       //return geom._retn(); -- servant of geom must be UnRegister()ed;
2258       CORBA::Object_var    obj = SObjectToObject( SObj );
2259       GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2260       return go._retn();
2261     }
2262   }
2263   return GEOM::GEOM_Object::_nil();
2264 }
2265
2266 //================================================================================
2267 /*!
2268  * \brief Return geometrical object the given element is built on.
2269  *  \param theMesh - the mesh the element is in
2270  *  \param theElementID - the element ID
2271  *  \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2272  */
2273 //================================================================================
2274
2275 GEOM::GEOM_Object_ptr
2276 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
2277                                         CORBA::Long            theElementID)
2278   throw ( SALOME::SALOME_Exception )
2279 {
2280   Unexpect aCatch(SALOME_SalomeException);
2281   if ( CORBA::is_nil( theMesh ) )
2282     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2283
2284   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2285   GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
2286
2287   // get a core mesh DS
2288   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2289   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2290   {
2291     ::SMESH_Mesh & mesh = meshServant->GetImpl();
2292     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2293     // find the element in mesh
2294     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2295       // find a shape id by the element
2296       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2297         // get a geom object by the shape id
2298         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2299         if ( geom->_is_nil() ) {
2300           // try to find a published sub-shape
2301           SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2302           SALOMEDS::ChildIterator_wrap it;
2303           if ( !mainSO->_is_nil() ) {
2304             it = myCurrentStudy->NewChildIterator( mainSO );
2305           }
2306           if ( !it->_is_nil() ) {
2307             for ( it->InitEx(true); it->More(); it->Next() ) {
2308               SALOMEDS::SObject_wrap      so = it->Value();
2309               CORBA::Object_var         obj = SObjectToObject( so );
2310               GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2311               if ( !subGeom->_is_nil() ) {
2312                 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2313                 if ( subList->length() == 1 && shapeID == subList[0] ) {
2314                   geom = subGeom;
2315                   break;
2316                 }
2317               }
2318             }
2319           }
2320         }
2321         if ( geom->_is_nil() ) {
2322           // explode
2323           GEOM::GEOM_IShapesOperations_wrap op =
2324             geomGen->GetIShapesOperations( GetCurrentStudyID() );
2325           if ( !op->_is_nil() )
2326             geom = op->GetSubShape( mainShape, shapeID );
2327         }
2328         else {
2329           geom->Register();
2330         }
2331         if ( !geom->_is_nil() ) {
2332           GeomObjectToShape( geom ); // let geom client remember the found shape
2333           return geom._retn();
2334         }
2335       }
2336     }
2337   }
2338   return GEOM::GEOM_Object::_nil();
2339 }
2340
2341 //================================================================================
2342 /*!
2343  *  SMESH_Gen_i::Concatenate
2344  *
2345  *  Concatenate the given meshes into one mesh
2346  */
2347 //================================================================================
2348
2349 SMESH::SMESH_Mesh_ptr
2350 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2351                          CORBA::Boolean                theUniteIdenticalGroups,
2352                          CORBA::Boolean                theMergeNodesAndElements,
2353                          CORBA::Double                 theMergeTolerance)
2354   throw ( SALOME::SALOME_Exception )
2355 {
2356   return ConcatenateCommon(theMeshesArray,
2357                            theUniteIdenticalGroups,
2358                            theMergeNodesAndElements,
2359                            theMergeTolerance,
2360                            false);
2361 }
2362
2363 //================================================================================
2364 /*!
2365  *  SMESH_Gen_i::ConcatenateWithGroups
2366  *
2367  *  Concatenate the given meshes into one mesh
2368  *  Create the groups of all elements from initial meshes
2369  */
2370 //================================================================================
2371
2372 SMESH::SMESH_Mesh_ptr
2373 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2374                                    CORBA::Boolean                theUniteIdenticalGroups,
2375                                    CORBA::Boolean                theMergeNodesAndElements,
2376                                    CORBA::Double                 theMergeTolerance)
2377   throw ( SALOME::SALOME_Exception )
2378 {
2379   return ConcatenateCommon(theMeshesArray,
2380                            theUniteIdenticalGroups,
2381                            theMergeNodesAndElements,
2382                            theMergeTolerance,
2383                            true);
2384 }
2385
2386 //================================================================================
2387 /*!
2388  *  SMESH_Gen_i::ConcatenateCommon
2389  *
2390  *  Concatenate the given meshes into one mesh
2391  */
2392 //================================================================================
2393
2394 SMESH::SMESH_Mesh_ptr
2395 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2396                                CORBA::Boolean                theUniteIdenticalGroups,
2397                                CORBA::Boolean                theMergeNodesAndElements,
2398                                CORBA::Double                 theMergeTolerance,
2399                                CORBA::Boolean                theCommonGroups)
2400   throw ( SALOME::SALOME_Exception )
2401 {
2402   typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
2403   typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
2404
2405   TPythonDump* pPythonDump = new TPythonDump;
2406   TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
2407
2408   // create mesh
2409   SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
2410
2411   if ( aNewMesh->_is_nil() )
2412     return aNewMesh._retn();
2413
2414   SMESH_Mesh_i* aNewImpl = SMESH::DownCast<SMESH_Mesh_i*>( aNewMesh );
2415   if ( !aNewImpl )
2416     return aNewMesh._retn();
2417
2418   ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
2419   SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
2420
2421   TGroupsMap aGroupsMap;
2422   TListOfNewGroups aListOfNewGroups;
2423   ::SMESH_MeshEditor aNewEditor(&aLocMesh);
2424   SMESH::ListOfGroups_var aListOfGroups;
2425
2426   ::SMESH_MeshEditor::ElemFeatures  elemType;
2427   std::vector<const SMDS_MeshNode*> aNodesArray;
2428
2429   // loop on sub-meshes
2430   for ( int i = 0; i < theMeshesArray.length(); i++)
2431   {
2432     if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2433     SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i]->GetMesh();
2434     if ( anInitMesh->_is_nil() ) continue;
2435     SMESH_Mesh_i* anInitImpl = SMESH::DownCast<SMESH_Mesh_i*>( anInitMesh );
2436     if ( !anInitImpl ) continue;
2437     anInitImpl->Load();
2438
2439     ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
2440     SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
2441
2442     // remember nb of elements before filling in
2443     SMESH::long_array_var prevState =  aNewMesh->GetNbElementsByType();
2444
2445     typedef std::map<const SMDS_MeshElement*, const SMDS_MeshElement*, TIDCompare > TEEMap;
2446     TEEMap elemsMap, nodesMap;
2447
2448     // loop on elements of a sub-mesh
2449     SMDS_ElemIteratorPtr itElems = anInitImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2450     const SMDS_MeshElement* anElem;
2451     const SMDS_MeshElement* aNewElem;
2452     const SMDS_MeshNode*    aNode;
2453     const SMDS_MeshNode*    aNewNode;
2454     int anElemNbNodes;
2455
2456     while ( itElems->more() )
2457     {
2458       anElem = itElems->next();
2459       anElemNbNodes = anElem->NbNodes();
2460       aNodesArray.resize( anElemNbNodes );
2461
2462       // loop on nodes of an element
2463       SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
2464       for ( int k = 0; itNodes->more(); k++)
2465       {
2466         aNode = static_cast<const SMDS_MeshNode*>( itNodes->next() );
2467         TEEMap::iterator n2nnIt = nodesMap.find( aNode );
2468         if ( n2nnIt == nodesMap.end() )
2469         {
2470           aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2471           nodesMap.insert( make_pair( aNode, aNewNode ));
2472         }
2473         else
2474         {
2475           aNewNode = static_cast<const SMDS_MeshNode*>( n2nnIt->second );
2476         }
2477         aNodesArray[k] = aNewNode;
2478       }
2479
2480       // creates a corresponding element on existent nodes in new mesh
2481       if ( anElem->GetType() == SMDSAbs_Node )
2482         aNewElem = 0;
2483       else
2484         aNewElem =
2485           aNewEditor.AddElement( aNodesArray, elemType.Init( anElem, /*basicOnly=*/false ));
2486
2487       if ( aNewElem )
2488         elemsMap.insert( make_pair( anElem, aNewElem ));
2489
2490     } //elems loop
2491
2492     aNewEditor.ClearLastCreated(); // forget the history
2493
2494
2495     // create groups of just added elements
2496     SMESH::SMESH_Group_var aNewGroup;
2497     SMESH::ElementType aGroupType;
2498     if ( theCommonGroups )
2499     {
2500       SMESH::long_array_var curState = aNewMesh->GetNbElementsByType();
2501
2502       for( aGroupType = SMESH::NODE;
2503            aGroupType < SMESH::NB_ELEMENT_TYPES;
2504            aGroupType = (SMESH::ElementType)( aGroupType + 1 ))
2505       {
2506         if ( curState[ aGroupType ] <= prevState[ aGroupType ])
2507           continue;
2508
2509         // make a group name
2510         const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2511         { // check of typeNames, compilation failure mains that NB_ELEMENT_TYPES changed:
2512           const int nbNames = sizeof(typeNames) / sizeof(const char*);
2513           int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 1 : -1 ];
2514         }
2515         string groupName = "Gr";
2516         SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
2517         if ( aMeshSObj ) {
2518           CORBA::String_var name = aMeshSObj->GetName();
2519           groupName += name;
2520         }
2521         groupName += "_";
2522         groupName += typeNames[ aGroupType ];
2523
2524         // make and fill a group
2525         TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2526         aNewGroup = aNewImpl->CreateGroup( aGroupType, groupName.c_str() );
2527         if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( aNewGroup ))
2528         {
2529           if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2530           {
2531             TEEMap::iterator e2neIt = e2neMap.begin();
2532             for ( ; e2neIt != e2neMap.end(); ++e2neIt )
2533             {
2534               aNewElem = e2neIt->second;
2535               if ( aNewElem->GetType() == grpDS->GetType() )
2536               {
2537                 grpDS->Add( aNewElem );
2538
2539                 if ( prevState[ aGroupType ]++ >= curState[ aGroupType ] )
2540                   break;
2541               }
2542             }
2543           }
2544         }
2545         aListOfNewGroups.clear();
2546         aListOfNewGroups.push_back(aNewGroup);
2547         aGroupsMap.insert(make_pair( make_pair(groupName, aGroupType), aListOfNewGroups ));
2548       }
2549     }
2550
2551     if ( SMESH_Mesh_i* anSrcImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2552     {
2553       // copy orphan nodes
2554       if ( anSrcImpl->NbNodes() > nodesMap.size() )
2555       {
2556         SMDS_ElemIteratorPtr itNodes = anInitImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2557         while ( itNodes->more() )
2558         {
2559           const SMDS_MeshNode* aNode = static_cast< const SMDS_MeshNode* >( itNodes->next() );
2560           if ( aNode->NbInverseElements() == 0 )
2561           {
2562             aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2563             nodesMap.insert( make_pair( aNode, aNewNode ));
2564           }
2565         }
2566       }
2567
2568       // copy groups
2569
2570       SMESH::SMESH_GroupBase_ptr aGroup;
2571       CORBA::String_var aGroupName;
2572       SMESH::long_array_var anNewIDs = new SMESH::long_array();
2573
2574       // loop on groups of a source mesh
2575       aListOfGroups = anSrcImpl->GetGroups();
2576       for (int iG = 0; iG < aListOfGroups->length(); iG++)
2577       {
2578         aGroup = aListOfGroups[iG];
2579         aGroupType = aGroup->GetType();
2580         aGroupName = aGroup->GetName();
2581
2582         // convert a list of IDs
2583         anNewIDs->length( aGroup->Size() );
2584         TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2585         SMDS_ElemIteratorPtr itGrElems = anSrcImpl->GetElements( aGroup, SMESH::ALL );
2586         int iElem = 0;
2587         while ( itGrElems->more() )
2588         {
2589           anElem = itGrElems->next();
2590           TEEMap::iterator e2neIt = e2neMap.find( anElem );
2591           if ( e2neIt != e2neMap.end() )
2592             anNewIDs[ iElem++ ] = e2neIt->second->GetID();
2593         }
2594         anNewIDs->length( iElem );
2595
2596         // check a current group name and type don't have identical ones in final mesh
2597         aListOfNewGroups.clear();
2598         TGroupsMap::iterator anIter = aGroupsMap.find( make_pair( aGroupName, aGroupType ));
2599         if ( anIter == aGroupsMap.end() ) {
2600           // add a new group in the mesh
2601           aNewGroup = aNewImpl->CreateGroup( aGroupType, aGroupName );
2602           // add elements into new group
2603           aNewGroup->Add( anNewIDs );
2604
2605           aListOfNewGroups.push_back(aNewGroup);
2606           aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2607         }
2608
2609         else if ( theUniteIdenticalGroups ) {
2610           // unite identical groups
2611           TListOfNewGroups& aNewGroups = anIter->second;
2612           aNewGroups.front()->Add( anNewIDs );
2613         }
2614
2615         else {
2616           // rename identical groups
2617           aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2618           aNewGroup->Add( anNewIDs );
2619
2620           TListOfNewGroups& aNewGroups = anIter->second;
2621           string aNewGroupName;
2622           if (aNewGroups.size() == 1) {
2623             aNewGroupName = string(aGroupName) + "_1";
2624             aNewGroups.front()->SetName(aNewGroupName.c_str());
2625           }
2626           char aGroupNum[128];
2627           sprintf(aGroupNum, "%u", aNewGroups.size()+1);
2628           aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
2629           aNewGroup->SetName(aNewGroupName.c_str());
2630           aNewGroups.push_back(aNewGroup);
2631         }
2632       } //groups loop
2633     } // if an IDSource is a mesh
2634   } //meshes loop
2635
2636   if (theMergeNodesAndElements) // merge nodes
2637   {
2638     TIDSortedNodeSet aMeshNodes; // no input nodes
2639     SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2640     aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes,
2641                                     /*SeparateCornersAndMedium=*/ false );
2642     aNewEditor.MergeNodes( aGroupsOfNodes );
2643     // merge elements
2644     aNewEditor.MergeEqualElements();
2645   }
2646
2647   // Update Python script
2648   aPythonDump << aNewMesh << " = " << this << "."
2649               << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" )
2650               << "([";
2651   for ( int i = 0; i < theMeshesArray.length(); i++) {
2652     if (i > 0) aPythonDump << ", ";
2653     aPythonDump << theMeshesArray[i];
2654   }
2655   aPythonDump << "], ";
2656   aPythonDump << theUniteIdenticalGroups << ", "
2657               << theMergeNodesAndElements << ", "
2658               << TVar( theMergeTolerance ) << ")";
2659
2660   delete pPythonDump; // enable python dump from GetGroups()
2661
2662   // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2663   if ( !aNewMesh->_is_nil() )
2664   {
2665     SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2666   }
2667
2668   // IPAL21468 Change icon of compound because it need not be computed.
2669   SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
2670   SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
2671
2672   if (aNewMeshDS)
2673     aNewMeshDS->Modified();
2674
2675   return aNewMesh._retn();
2676 }
2677
2678 //================================================================================
2679 /*!
2680  * \brief Create a mesh by copying a part of another mesh
2681  *  \param meshPart - a part of mesh to copy
2682  *  \param toCopyGroups - to create in the new mesh groups
2683  *                        the copied elements belongs to
2684  *  \param toKeepIDs - to preserve IDs of the copied elements or not
2685  *  \retval SMESH::SMESH_Mesh_ptr - the new mesh
2686  */
2687 //================================================================================
2688
2689 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2690                                             const char*               meshName,
2691                                             CORBA::Boolean            toCopyGroups,
2692                                             CORBA::Boolean            toKeepIDs)
2693 {
2694   Unexpect aCatch(SALOME_SalomeException);
2695
2696   TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2697
2698   // 1. Get source mesh
2699
2700   if ( CORBA::is_nil( meshPart ))
2701     THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2702
2703   SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2704   SMESH_Mesh_i*       srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2705   if ( !srcMesh_i )
2706     THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2707
2708   SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2709
2710   // 2. Make a new mesh
2711
2712   SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2713   SMESH_Mesh_i*       newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2714   if ( !newMesh_i )
2715     THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2716   SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2717   if ( !meshSO->_is_nil() )
2718   {
2719     SetName( meshSO, meshName, "Mesh" );
2720     SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2721   }
2722   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2723   ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2724   ::SMESH_MeshEditor::ElemFeatures elemType;
2725
2726   // 3. Get elements to copy
2727
2728   SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2729   TIDSortedElemSet srcElems;
2730   SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2731   if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2732   {
2733     srcMesh_i->Load();
2734     srcElemIt = srcMeshDS->elementsIterator();
2735     srcNodeIt = srcMeshDS->nodesIterator();
2736   }
2737   else
2738   {
2739     SMESH::long_array_var ids = meshPart->GetIDs();
2740     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2741     {
2742       for (int i=0; i < ids->length(); i++)
2743         if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2744           srcElems.insert( elem );
2745     }
2746     else
2747     {
2748       for (int i=0; i < ids->length(); i++)
2749         if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2750           srcElems.insert( elem );
2751     }
2752     if ( srcElems.empty() )
2753       return newMesh._retn();
2754
2755     typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2756     srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2757   }
2758
2759   // 4. Copy elements
2760
2761   typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2762   TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2763   TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2764   int iN;
2765   const SMDS_MeshNode *nSrc, *nTgt;
2766   vector< const SMDS_MeshNode* > nodes;
2767   while ( srcElemIt->more() )
2768   {
2769     const SMDS_MeshElement * elem = srcElemIt->next();
2770     // find / add nodes
2771     nodes.resize( elem->NbNodes());
2772     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2773     if ( toKeepIDs ) {
2774       for ( iN = 0; nIt->more(); ++iN )
2775       {
2776         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2777         nTgt = newMeshDS->FindNode( nSrc->GetID());
2778         if ( !nTgt )
2779           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2780         nodes[ iN ] = nTgt;
2781       }
2782     }
2783     else {
2784       for ( iN = 0; nIt->more(); ++iN )
2785       {
2786         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2787         TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2788         if ( !n2n->second )
2789           n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2790         nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2791       }
2792     }
2793     // add elements
2794     if ( elem->GetType() != SMDSAbs_Node )
2795     {
2796       elemType.Init( elem, /*basicOnly=*/false );
2797       if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2798
2799       const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2800       if ( toCopyGroups && !toKeepIDs )
2801         e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2802     }
2803   } // while ( srcElemIt->more() )
2804
2805   // 4(b). Copy free nodes
2806
2807   if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2808   {
2809     while ( srcNodeIt->more() )
2810     {
2811       nSrc = srcNodeIt->next();
2812       if ( nSrc->NbInverseElements() == 0 )
2813       {
2814         if ( toKeepIDs )
2815           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2816         else
2817           n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2818       }
2819     }
2820   }
2821
2822   // 5. Copy groups
2823
2824   int nbNewGroups = 0;
2825   if ( toCopyGroups )
2826   {
2827     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2828     while ( gIt->more() )
2829     {
2830       SMESH_Group* group = gIt->next();
2831       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2832
2833       // Check group type. We copy nodal groups containing nodes of copied element
2834       SMDSAbs_ElementType groupType = groupDS->GetType();
2835       if ( groupType != SMDSAbs_Node &&
2836            newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2837         continue; // group type differs from types of meshPart
2838
2839       // Find copied elements in the group
2840       vector< const SMDS_MeshElement* > groupElems;
2841       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2842       if ( toKeepIDs )
2843       {
2844         const SMDS_MeshElement* foundElem;
2845         if ( groupType == SMDSAbs_Node )
2846         {
2847           while ( eIt->more() )
2848             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2849               groupElems.push_back( foundElem );
2850         }
2851         else
2852         {
2853           while ( eIt->more() )
2854             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2855               groupElems.push_back( foundElem );
2856         }
2857       }
2858       else
2859       {
2860         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2861         if ( e2eMap.empty() ) continue;
2862         int minID = e2eMap.begin()->first->GetID();
2863         int maxID = e2eMap.rbegin()->first->GetID();
2864         TE2EMap::iterator e2e;
2865         while ( eIt->more() && groupElems.size() < e2eMap.size())
2866         {
2867           const SMDS_MeshElement* e = eIt->next();
2868           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2869           if ((e2e = e2eMap.find( e )) != e2eMap.end())
2870             groupElems.push_back( e2e->second );
2871         }
2872       }
2873       // Make a new group
2874       if ( !groupElems.empty() )
2875       {
2876         SMESH::SMESH_Group_var newGroupObj =
2877           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2878         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2879         {
2880           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2881           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2882           for ( unsigned i = 0; i < groupElems.size(); ++i )
2883             smdsGroup.Add( groupElems[i] );
2884
2885           nbNewGroups++;
2886         }
2887       }
2888     }
2889   }
2890
2891   newMeshDS->Modified();
2892
2893   *pyDump << newMesh << " = " << this
2894           << ".CopyMesh( " << meshPart << ", "
2895           << "'" << meshName << "', "
2896           << toCopyGroups << ", "
2897           << toKeepIDs << ")";
2898
2899   delete pyDump; pyDump = 0; // allow dump in GetGroups()
2900
2901   if ( nbNewGroups > 0 ) // dump created groups
2902     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2903
2904   return newMesh._retn();
2905 }
2906
2907 //================================================================================
2908 /*!
2909  *  SMESH_Gen_i::GetMEDVersion
2910  *
2911  *  Get MED version of the file by its name
2912  */
2913 //================================================================================
2914 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2915                                           SMESH::MED_VERSION& theVersion)
2916 {
2917   theVersion = SMESH::MED_V2_1;
2918   MED::EVersion aVersion = MED::GetVersionId( theFileName );
2919   switch( aVersion ) {
2920     case MED::eV2_1     : theVersion = SMESH::MED_V2_1; return true;
2921     case MED::eV2_2     : theVersion = SMESH::MED_V2_2; return true;
2922     case MED::eVUnknown : return false;
2923   }
2924   return false;
2925 }
2926
2927 //================================================================================
2928 /*!
2929  *  SMESH_Gen_i::GetMeshNames
2930  *
2931  *  Get names of meshes defined in file with the specified name
2932  */
2933 //================================================================================
2934 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2935 {
2936   SMESH::string_array_var aResult = new SMESH::string_array();
2937   MED::PWrapper aMed = MED::CrWrapper( theFileName );
2938   MED::TErr anErr;
2939   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2940   if( anErr >= 0 ) {
2941     aResult->length( aNbMeshes );
2942     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2943       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2944       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2945     }
2946   }
2947   return aResult._retn();
2948 }
2949
2950 //=============================================================================
2951 /*!
2952  *  SMESH_Gen_i::Save
2953  *
2954  *  Save SMESH module's data
2955  */
2956 //=============================================================================
2957 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2958                                       const char*              theURL,
2959                                       bool                     isMultiFile )
2960 {
2961   INFOS( "SMESH_Gen_i::Save" );
2962
2963   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2964   // san -- in case <myCurrentStudy> differs from theComponent's study,
2965   // use that of the component
2966   if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
2967     SetCurrentStudy( theComponent->GetStudy() );
2968
2969   // Store study contents as a set of python commands
2970   SavePython(myCurrentStudy);
2971
2972   StudyContext* myStudyContext = GetCurrentStudyContext();
2973
2974   // Declare a byte stream
2975   SALOMEDS::TMPFile_var aStreamFile;
2976
2977   // Obtain a temporary dir
2978   TCollection_AsciiString tmpDir =
2979     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2980
2981   // Create a sequence of files processed
2982   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2983   aFileSeq->length( NUM_TMP_FILES );
2984
2985   TCollection_AsciiString aStudyName( "" );
2986   if ( isMultiFile )
2987     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2988
2989   // Set names of temporary files
2990   TCollection_AsciiString filename =
2991     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
2992   TCollection_AsciiString meshfile =
2993     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
2994   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
2995   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
2996   filename = tmpDir + filename;
2997   meshfile = tmpDir + meshfile;
2998
2999   HDFfile*    aFile;
3000   HDFdataset* aDataset;
3001   HDFgroup*   aTopGroup;
3002   HDFgroup*   aGroup;
3003   HDFgroup*   aSubGroup;
3004   HDFgroup*   aSubSubGroup;
3005   hdf_size    aSize[ 1 ];
3006
3007
3008   //Remove the files if they exist: BugID: 11225
3009 #ifndef WIN32 /* unix functionality */
3010   TCollection_AsciiString cmd("rm -f \"");
3011 #else /* windows */
3012   TCollection_AsciiString cmd("del /F \"");
3013 #endif
3014
3015   cmd+=filename;
3016   cmd+="\" \"";
3017   cmd+=meshfile;
3018   cmd+="\"";
3019   system(cmd.ToCString());
3020
3021   // MED writer to be used by storage process
3022   DriverMED_W_SMESHDS_Mesh myWriter;
3023   myWriter.SetFile( meshfile.ToCString() );
3024
3025   // IMP issue 20918
3026   // SetStoreName() to groups before storing hypotheses to let them refer to
3027   // groups using "store name", which is "Group <group_persistent_id>"
3028   {
3029     SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3030     for ( ; itBig->More(); itBig->Next() ) {
3031       SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3032       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3033         CORBA::Object_var anObject = SObjectToObject( gotBranch );
3034         if ( !CORBA::is_nil( anObject ) ) {
3035           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3036           if ( !myMesh->_is_nil() ) {
3037             myMesh->Load(); // load from study file if not yet done
3038             TPythonDump pd; // not to dump GetGroups()
3039             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3040             pd << ""; // to avoid optimizing pd out
3041             for ( int i = 0; i < groups->length(); ++i )
3042             {
3043               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3044               if ( grImpl )
3045               {
3046                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3047                 int anId = myStudyContext->findId( string( objStr.in() ) );
3048                 char grpName[ 30 ];
3049                 sprintf( grpName, "Group %d", anId );
3050                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3051                 aGrpBaseDS->SetStoreName( grpName );
3052               }
3053             }
3054           }
3055         }
3056       }
3057     }
3058   }
3059
3060   // Write data
3061   // ---> create HDF file
3062   aFile = new HDFfile( (char*) filename.ToCString() );
3063   aFile->CreateOnDisk();
3064
3065   // --> iterator for top-level objects
3066   SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3067   for ( ; itBig->More(); itBig->Next() ) {
3068     SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3069
3070     // --> hypotheses root branch (only one for the study)
3071     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3072       // create hypotheses root HDF group
3073       aTopGroup = new HDFgroup( "Hypotheses", aFile );
3074       aTopGroup->CreateOnDisk();
3075
3076       // iterator for all hypotheses
3077       SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3078       for ( ; it->More(); it->Next() ) {
3079         SALOMEDS::SObject_wrap mySObject = it->Value();
3080         CORBA::Object_var anObject = SObjectToObject( mySObject );
3081         if ( !CORBA::is_nil( anObject ) ) {
3082           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3083           if ( !myHyp->_is_nil() ) {
3084             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3085             if ( myImpl ) {
3086               string hypname = string( myHyp->GetName() );
3087               string libname = string( myHyp->GetLibName() );
3088               // BUG SWP13062
3089               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3090               // WIN32 and ".so" for X-system) must be deleted
3091               int libname_len = libname.length();
3092 #ifdef WIN32
3093               if( libname_len > 4 )
3094                 libname.resize( libname_len - 4 );
3095 #else
3096               // PAL17753 (Regresion: missing hypothesis in restored study)
3097               // "lib" also should be removed from the beginning
3098               //if( libname_len > 3 )
3099                 //libname.resize( libname_len - 3 );
3100               if( libname_len > 6 )
3101                 libname = libname.substr( 3, libname_len - 3 - 3 );
3102 #endif
3103               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3104               int    id      = myStudyContext->findId( string( objStr.in() ) );
3105               string hypdata = string( myImpl->SaveTo() );
3106
3107               // for each hypothesis create HDF group basing on its id
3108               char hypGrpName[30];
3109               sprintf( hypGrpName, "Hypothesis %d", id );
3110               aGroup = new HDFgroup( hypGrpName, aTopGroup );
3111               aGroup->CreateOnDisk();
3112               // --> type name of hypothesis
3113               aSize[ 0 ] = hypname.length() + 1;
3114               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3115               aDataset->CreateOnDisk();
3116               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3117               aDataset->CloseOnDisk();
3118               // --> server plugin library name of hypothesis
3119               aSize[ 0 ] = libname.length() + 1;
3120               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3121               aDataset->CreateOnDisk();
3122               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3123               aDataset->CloseOnDisk();
3124               // --> persistent data of hypothesis
3125               aSize[ 0 ] = hypdata.length() + 1;
3126               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3127               aDataset->CreateOnDisk();
3128               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3129               aDataset->CloseOnDisk();
3130               // close hypothesis HDF group
3131               aGroup->CloseOnDisk();
3132             }
3133           }
3134         }
3135       }
3136       // close hypotheses root HDF group
3137       aTopGroup->CloseOnDisk();
3138     }
3139     // --> algorithms root branch (only one for the study)
3140     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3141       // create algorithms root HDF group
3142       aTopGroup = new HDFgroup( "Algorithms", aFile );
3143       aTopGroup->CreateOnDisk();
3144
3145       // iterator for all algorithms
3146       SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3147       for ( ; it->More(); it->Next() ) {
3148         SALOMEDS::SObject_wrap mySObject = it->Value();
3149         CORBA::Object_var anObject = SObjectToObject( mySObject );
3150         if ( !CORBA::is_nil( anObject ) ) {
3151           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3152           if ( !myHyp->_is_nil() ) {
3153             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3154             if ( myImpl ) {
3155               string hypname = string( myHyp->GetName() );
3156               string libname = string( myHyp->GetLibName() );
3157               // BUG SWP13062
3158               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3159               // WIN32 and ".so" for X-system) must be deleted
3160               int libname_len = libname.length();
3161 #ifdef WIN32
3162               if( libname_len > 4 )
3163                 libname.resize( libname_len - 4 );
3164 #else
3165               // PAL17753 (Regresion: missing hypothesis in restored study)
3166               // "lib" also should be removed from the beginning
3167               //if( libname_len > 3 )
3168                 //libname.resize( libname_len - 3 );
3169               if( libname_len > 6 )
3170                 libname = libname.substr( 3, libname_len - 3 - 3 );
3171 #endif
3172               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3173               int    id      = myStudyContext->findId( string( objStr.in() ) );
3174               string hypdata = string( myImpl->SaveTo() );
3175
3176               // for each algorithm create HDF group basing on its id
3177               char hypGrpName[30];
3178               sprintf( hypGrpName, "Algorithm %d", id );
3179               aGroup = new HDFgroup( hypGrpName, aTopGroup );
3180               aGroup->CreateOnDisk();
3181               // --> type name of algorithm
3182               aSize[0] = hypname.length() + 1;
3183               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3184               aDataset->CreateOnDisk();
3185               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3186               aDataset->CloseOnDisk();
3187               // --> server plugin library name of hypothesis
3188               aSize[0] = libname.length() + 1;
3189               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3190               aDataset->CreateOnDisk();
3191               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3192               aDataset->CloseOnDisk();
3193               // --> persistent data of algorithm
3194               aSize[0] = hypdata.length() + 1;
3195               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3196               aDataset->CreateOnDisk();
3197               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3198               aDataset->CloseOnDisk();
3199               // close algorithm HDF group
3200               aGroup->CloseOnDisk();
3201             }
3202           }
3203         }
3204       }
3205       // close algorithms root HDF group
3206       aTopGroup->CloseOnDisk();
3207     }
3208     // --> mesh objects roots branches
3209     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3210       CORBA::Object_var anObject = SObjectToObject( gotBranch );
3211       if ( !CORBA::is_nil( anObject ) ) {
3212         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3213         if ( !myMesh->_is_nil() ) {
3214           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3215           if ( myImpl ) {
3216             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3217             int id = myStudyContext->findId( string( objStr.in() ) );
3218             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3219             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3220             bool hasShape = myLocMesh.HasShapeToMesh();
3221
3222             // for each mesh open the HDF group basing on its id
3223             char meshGrpName[ 30 ];
3224             sprintf( meshGrpName, "Mesh %d", id );
3225             aTopGroup = new HDFgroup( meshGrpName, aFile );
3226             aTopGroup->CreateOnDisk();
3227
3228             // --> put dataset to hdf file which is a flag that mesh has data
3229             string strHasData = "0";
3230             // check if the mesh is not empty
3231             if ( mySMESHDSMesh->NbNodes() > 0 ) {
3232               // write mesh data to med file
3233               myWriter.SetMesh( mySMESHDSMesh );
3234               myWriter.SetMeshId( id );
3235               strHasData = "1";
3236             }
3237             aSize[ 0 ] = strHasData.length() + 1;
3238             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3239             aDataset->CreateOnDisk();
3240             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3241             aDataset->CloseOnDisk();
3242
3243             // ouv : NPAL12872
3244             // for each mesh open the HDF group basing on its auto color parameter
3245             char meshAutoColorName[ 30 ];
3246             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3247             int anAutoColor[1];
3248             anAutoColor[0] = myImpl->GetAutoColor();
3249             aSize[ 0 ] = 1;
3250             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3251             aDataset->CreateOnDisk();
3252             aDataset->WriteOnDisk( anAutoColor );
3253             aDataset->CloseOnDisk();
3254
3255             // issue 0020693. Store _isModified flag
3256             int isModified = myLocMesh.GetIsModified();
3257             aSize[ 0 ] = 1;
3258             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3259             aDataset->CreateOnDisk();
3260             aDataset->WriteOnDisk( &isModified );
3261             aDataset->CloseOnDisk();
3262
3263             // issue 20918. Store Persistent Id of SMESHDS_Mesh
3264             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3265             aSize[ 0 ] = 1;
3266             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3267             aDataset->CreateOnDisk();
3268             aDataset->WriteOnDisk( &meshPersistentId );
3269             aDataset->CloseOnDisk();
3270
3271             // write reference on a shape if exists
3272             SALOMEDS::SObject_wrap myRef;
3273             bool shapeRefFound = false;
3274             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3275             if ( found ) {
3276               SALOMEDS::SObject_wrap myShape;
3277               bool ok = myRef->ReferencedObject( myShape.inout() );
3278               if ( ok ) {
3279                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
3280                 string myRefOnObject = myShape->GetID();
3281                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
3282                   aSize[ 0 ] = myRefOnObject.length() + 1;
3283                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3284                   aDataset->CreateOnDisk();
3285                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3286                   aDataset->CloseOnDisk();
3287                 }
3288               }
3289             }
3290
3291             // write applied hypotheses if exist
3292             SALOMEDS::SObject_wrap myHypBranch;
3293             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3294             if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3295               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3296             }
3297             if ( found && (shapeRefFound || !hasShape) ) {
3298               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3299               aGroup->CreateOnDisk();
3300
3301               SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myHypBranch );
3302               int hypNb = 0;
3303               for ( ; it->More(); it->Next() ) {
3304                 SALOMEDS::SObject_wrap mySObject = it->Value();
3305                 SALOMEDS::SObject_wrap myRefOnHyp;
3306                 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3307                 if ( ok ) {
3308                   // san - it is impossible to recover applied hypotheses
3309                   //       using their entries within Load() method,
3310                   // for there are no AttributeIORs in the study when Load() is working.
3311                   // Hence, it is better to store persistent IDs of hypotheses as references to them
3312
3313                   //string myRefOnObject = myRefOnHyp->GetID();
3314                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3315                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3316                   int id = myStudyContext->findId( string( objStr.in() ) );
3317                   //if ( myRefOnObject.length() > 0 ) {
3318                   //aSize[ 0 ] = myRefOnObject.length() + 1;
3319                   char hypName[ 30 ], hypId[ 30 ];
3320                   sprintf( hypName, "Hyp %d", ++hypNb );
3321                   sprintf( hypId, "%d", id );
3322                   aSize[ 0 ] = strlen( hypId ) + 1;
3323                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3324                   aDataset->CreateOnDisk();
3325                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3326                   aDataset->WriteOnDisk( hypId );
3327                   aDataset->CloseOnDisk();
3328                   //}
3329                 }
3330               }
3331               aGroup->CloseOnDisk();
3332             }
3333
3334             // write applied algorithms if exist
3335             SALOMEDS::SObject_wrap myAlgoBranch;
3336             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3337                                               myAlgoBranch.inout() );
3338             if ( found && !shapeRefFound && hasShape) { // remove applied algos
3339               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3340             }
3341             if ( found && (shapeRefFound || !hasShape)) {
3342               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3343               aGroup->CreateOnDisk();
3344
3345               SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myAlgoBranch );
3346               int algoNb = 0;
3347               for ( ; it->More(); it->Next() ) {
3348                 SALOMEDS::SObject_wrap mySObject = it->Value();
3349                 SALOMEDS::SObject_wrap myRefOnAlgo;
3350                 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3351                 if ( ok ) {
3352                   // san - it is impossible to recover applied algorithms
3353                   //       using their entries within Load() method,
3354                   // for there are no AttributeIORs in the study when Load() is working.
3355                   // Hence, it is better to store persistent IDs of algorithms as references to them
3356
3357                   //string myRefOnObject = myRefOnAlgo->GetID();
3358                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3359                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3360                   int id = myStudyContext->findId( string( objStr.in() ) );
3361                   //if ( myRefOnObject.length() > 0 ) {
3362                   //aSize[ 0 ] = myRefOnObject.length() + 1;
3363                   char algoName[ 30 ], algoId[ 30 ];
3364                   sprintf( algoName, "Algo %d", ++algoNb );
3365                   sprintf( algoId, "%d", id );
3366                   aSize[ 0 ] = strlen( algoId ) + 1;
3367                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3368                   aDataset->CreateOnDisk();
3369                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3370                   aDataset->WriteOnDisk( algoId );
3371                   aDataset->CloseOnDisk();
3372                   //}
3373                 }
3374               }
3375               aGroup->CloseOnDisk();
3376             }
3377
3378             // --> submesh objects sub-branches
3379
3380             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3381               SALOMEDS::SObject_wrap mySubmeshBranch;
3382               found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3383
3384               if ( found ) // check if there is shape reference in submeshes
3385               {
3386                 bool hasShapeRef = false;
3387                 SALOMEDS::ChildIterator_wrap itSM =
3388                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
3389                 for ( ; itSM->More(); itSM->Next() ) {
3390                   SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3391                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3392                     mySubRef->ReferencedObject( myShape.inout() );
3393                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3394                     hasShapeRef = true;
3395                   else
3396                   { // remove one submesh
3397                     if ( shapeRefFound )
3398                     { // unassign hypothesis
3399                       SMESH::SMESH_subMesh_var mySubMesh =
3400                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3401                       if ( !mySubMesh->_is_nil() ) {
3402                         int shapeID = mySubMesh->GetId();
3403                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3404                         const list<const SMESHDS_Hypothesis*>& hypList =
3405                           mySMESHDSMesh->GetHypothesis( S );
3406                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3407                         while ( hyp != hypList.end() ) {
3408                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
3409                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3410                         }
3411                       }
3412                     }
3413                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3414                   }
3415                 } // loop on submeshes of a type
3416                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3417                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3418                   found = false;
3419                 }
3420               }  // end check if there is shape reference in submeshes
3421               if ( found ) {
3422                 char name_meshgroup[ 30 ];
3423                 if ( i == GetSubMeshOnVertexTag() )
3424                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
3425                 else if ( i == GetSubMeshOnEdgeTag() )
3426                   strcpy( name_meshgroup, "SubMeshes On Edge" );
3427                 else if ( i == GetSubMeshOnWireTag() )
3428                   strcpy( name_meshgroup, "SubMeshes On Wire" );
3429                 else if ( i == GetSubMeshOnFaceTag() )
3430                   strcpy( name_meshgroup, "SubMeshes On Face" );
3431                 else if ( i == GetSubMeshOnShellTag() )
3432                   strcpy( name_meshgroup, "SubMeshes On Shell" );
3433                 else if ( i == GetSubMeshOnSolidTag() )
3434                   strcpy( name_meshgroup, "SubMeshes On Solid" );
3435                 else if ( i == GetSubMeshOnCompoundTag() )
3436                   strcpy( name_meshgroup, "SubMeshes On Compound" );
3437
3438                 // for each type of submeshes create container HDF group
3439                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3440                 aGroup->CreateOnDisk();
3441
3442                 // iterator for all submeshes of given type
3443                 SALOMEDS::ChildIterator_wrap itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
3444                 for ( ; itSM->More(); itSM->Next() ) {
3445                   SALOMEDS::SObject_wrap mySObject = itSM->Value();
3446                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3447                   if ( !CORBA::is_nil( anSubObject ))
3448                   {
3449                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3450                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3451                     int subid = myStudyContext->findId( string( objStr.in() ) );
3452
3453                     // for each mesh open the HDF group basing on its id
3454                     char submeshGrpName[ 30 ];
3455                     sprintf( submeshGrpName, "SubMesh %d", subid );
3456                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3457                     aSubGroup->CreateOnDisk();
3458
3459                     // write reference on a shape, already checked if it exists
3460                     SALOMEDS::SObject_wrap mySubRef, myShape;
3461                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3462                       mySubRef->ReferencedObject( myShape.inout() );
3463                     string myRefOnObject = myShape->GetID();
3464                     if ( myRefOnObject.length() > 0 ) {
3465                       aSize[ 0 ] = myRefOnObject.length() + 1;
3466                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3467                       aDataset->CreateOnDisk();
3468                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3469                       aDataset->CloseOnDisk();
3470                     }
3471
3472                     // write applied hypotheses if exist
3473                     SALOMEDS::SObject_wrap mySubHypBranch;
3474                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3475                                                       mySubHypBranch.inout() );
3476                     if ( found ) {
3477                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3478                       aSubSubGroup->CreateOnDisk();
3479
3480                       SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( mySubHypBranch );
3481                       int hypNb = 0;
3482                       for ( ; it->More(); it->Next() ) {
3483                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
3484                         SALOMEDS::SObject_wrap myRefOnHyp;
3485                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3486                         if ( ok ) {
3487                           //string myRefOnObject = myRefOnHyp->GetID();
3488                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3489                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3490                           int id = myStudyContext->findId( string( objStr.in() ) );
3491                           //if ( myRefOnObject.length() > 0 ) {
3492                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3493                           char hypName[ 30 ], hypId[ 30 ];
3494                           sprintf( hypName, "Hyp %d", ++hypNb );
3495                           sprintf( hypId, "%d", id );
3496                           aSize[ 0 ] = strlen( hypId ) + 1;
3497                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3498                           aDataset->CreateOnDisk();
3499                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3500                           aDataset->WriteOnDisk( hypId );
3501                           aDataset->CloseOnDisk();
3502                           //}
3503                         }
3504                       }
3505                       aSubSubGroup->CloseOnDisk();
3506                     }
3507
3508                     // write applied algorithms if exist
3509                     SALOMEDS::SObject_wrap mySubAlgoBranch;
3510                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3511                                                       mySubAlgoBranch.inout() );
3512                     if ( found ) {
3513                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3514                       aSubSubGroup->CreateOnDisk();
3515
3516                       SALOMEDS::ChildIterator_wrap it =
3517                         myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3518                       int algoNb = 0;
3519                       for ( ; it->More(); it->Next() ) {
3520                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
3521                         SALOMEDS::SObject_wrap myRefOnAlgo;
3522                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3523                         if ( ok ) {
3524                           //string myRefOnObject = myRefOnAlgo->GetID();
3525                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3526                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3527                           int id = myStudyContext->findId( string( objStr.in() ) );
3528                           //if ( myRefOnObject.length() > 0 ) {
3529                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3530                           char algoName[ 30 ], algoId[ 30 ];
3531                           sprintf( algoName, "Algo %d", ++algoNb );
3532                           sprintf( algoId, "%d", id );
3533                           aSize[ 0 ] = strlen( algoId ) + 1;
3534                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3535                           aDataset->CreateOnDisk();
3536                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3537                           aDataset->WriteOnDisk( algoId );
3538                           aDataset->CloseOnDisk();
3539                           //}
3540                         }
3541                       }
3542                       aSubSubGroup->CloseOnDisk();
3543                     }
3544                     // close submesh HDF group
3545                     aSubGroup->CloseOnDisk();
3546                   }
3547                 }
3548                 // close container of submeshes by type HDF group
3549                 aGroup->CloseOnDisk();
3550               }
3551             }
3552             // All sub-meshes will be stored in MED file
3553             // .. will NOT (PAL 12992)
3554             //if ( shapeRefFound )
3555             //myWriter.AddAllSubMeshes();
3556
3557             // store submesh order if any
3558             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3559             if ( theOrderIds.size() ) {
3560               char order_list[ 30 ];
3561               strcpy( order_list, "Mesh Order" );
3562               // count number of submesh ids
3563               int nbIDs = 0;
3564               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3565               for ( ; idIt != theOrderIds.end(); idIt++ )
3566                 nbIDs += (*idIt).size();
3567               // number of values = number of IDs +
3568               //                    number of lists (for separators) - 1
3569               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3570               idIt = theOrderIds.begin();
3571               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3572                 const TListOfInt& idList = *idIt;
3573                 if (idIt != theOrderIds.begin()) // not first list
3574                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3575                 // dump submesh ids from current list
3576                 TListOfInt::const_iterator id_smId = idList.begin();
3577                 for( ; id_smId != idList.end(); id_smId++ )
3578                   smIDs[ i++ ] = *id_smId;
3579               }
3580               // write HDF group
3581               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3582
3583               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3584               aDataset->CreateOnDisk();
3585               aDataset->WriteOnDisk( smIDs );
3586               aDataset->CloseOnDisk();
3587               //
3588               delete[] smIDs;
3589             }
3590
3591             // groups root sub-branch
3592             SALOMEDS::SObject_wrap myGroupsBranch;
3593             for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3594               found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3595               if ( found ) {
3596                 char name_group[ 30 ];
3597                 if ( i == GetNodeGroupsTag() )
3598                   strcpy( name_group, "Groups of Nodes" );
3599                 else if ( i == GetEdgeGroupsTag() )
3600                   strcpy( name_group, "Groups of Edges" );
3601                 else if ( i == GetFaceGroupsTag() )
3602                   strcpy( name_group, "Groups of Faces" );
3603                 else if ( i == GetVolumeGroupsTag() )
3604                   strcpy( name_group, "Groups of Volumes" );
3605                 else if ( i == Get0DElementsGroupsTag() )
3606                   strcpy( name_group, "Groups of 0D Elements" );
3607                 else if ( i == GetBallElementsGroupsTag() )
3608                   strcpy( name_group, "Groups of Balls" );
3609
3610                 aGroup = new HDFgroup( name_group, aTopGroup );
3611                 aGroup->CreateOnDisk();
3612
3613                 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3614                 for ( ; it->More(); it->Next() ) {
3615                   SALOMEDS::SObject_wrap mySObject = it->Value();
3616                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3617                   if ( !CORBA::is_nil( aSubObject ) ) {
3618                     SMESH_GroupBase_i* myGroupImpl =
3619                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3620                     if ( !myGroupImpl )
3621                       continue;
3622                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3623                     if ( !aGrpBaseDS )
3624                       continue;
3625
3626                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3627                     int anId = myStudyContext->findId( string( objStr.in() ) );
3628
3629                     // For each group, create a dataset named "Group <group_persistent_id>"
3630                     // and store the group's user name into it
3631                     const char* grpName = aGrpBaseDS->GetStoreName();
3632                     char* aUserName = myGroupImpl->GetName();
3633                     aSize[ 0 ] = strlen( aUserName ) + 1;
3634
3635                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3636                     aDataset->CreateOnDisk();
3637                     aDataset->WriteOnDisk( aUserName );
3638                     aDataset->CloseOnDisk();
3639
3640                     // ouv : NPAL12872
3641                     // For each group, create a dataset named "Group <group_persistent_id> Color"
3642                     // and store the group's color into it
3643                     char grpColorName[ 30 ];
3644                     sprintf( grpColorName, "ColorGroup %d", anId );
3645                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
3646                     double anRGB[3];
3647                     anRGB[ 0 ] = aColor.R;
3648                     anRGB[ 1 ] = aColor.G;
3649                     anRGB[ 2 ] = aColor.B;
3650                     aSize[ 0 ] = 3;
3651                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3652                     aDataset->CreateOnDisk();
3653                     aDataset->WriteOnDisk( anRGB );
3654                     aDataset->CloseOnDisk();
3655
3656                     // Pass SMESHDS_Group to MED writer
3657                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3658                     if ( aGrpDS )
3659                       myWriter.AddGroup( aGrpDS );
3660
3661                     // write reference on a shape if exists
3662                     SMESHDS_GroupOnGeom* aGeomGrp =
3663                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3664                     if ( aGeomGrp ) {
3665                       SALOMEDS::SObject_wrap mySubRef, myShape;
3666                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3667                           mySubRef->ReferencedObject( myShape.inout() ) &&
3668                           !CORBA::is_nil( myShape->GetObject() ))
3669                       {
3670                         string myRefOnObject = myShape->GetID();
3671                         if ( myRefOnObject.length() > 0 ) {
3672                           char aRefName[ 30 ];
3673                           sprintf( aRefName, "Ref on shape %d", anId);
3674                           aSize[ 0 ] = myRefOnObject.length() + 1;
3675                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3676                           aDataset->CreateOnDisk();
3677                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3678                           aDataset->CloseOnDisk();
3679                         }
3680                       }
3681                       else // shape ref is invalid:
3682                       {
3683                         // save a group on geometry as ordinary group
3684                         myWriter.AddGroup( aGeomGrp );
3685                       }
3686                     }
3687                     else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3688                               dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3689                     {
3690                       std::string str = aFilterGrp_i->FilterToString();
3691                       std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3692                       aSize[ 0 ] = str.length() + 1;
3693                       aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3694                       aDataset->CreateOnDisk();
3695                       aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3696                       aDataset->CloseOnDisk();
3697                     }
3698                   }
3699                 }
3700                 aGroup->CloseOnDisk();
3701               }
3702             } // loop on groups
3703
3704             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3705             {
3706               // Flush current mesh information into MED file
3707               myWriter.Perform();
3708
3709               // save info on nb of elements
3710               SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3711
3712               // maybe a shape was deleted in the study
3713               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3714                 TopoDS_Shape nullShape;
3715                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3716               }
3717
3718               SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3719               if ( smIt->more() )
3720               {
3721                 // Store submeshes
3722                 // ----------------
3723                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3724                 aGroup->CreateOnDisk();
3725
3726                 // each element belongs to one or none submesh,
3727                 // so for each node/element, we store a submesh ID
3728
3729                 // Store submesh IDs
3730                 for ( int isNode = 0; isNode < 2; ++isNode )
3731                 {
3732                   SMDS_ElemIteratorPtr eIt =
3733                     mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3734                   int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3735                   if ( nbElems < 1 )
3736                     continue;
3737                   std::vector<int> smIDs; smIDs.reserve( nbElems );
3738                   while ( eIt->more() )
3739                     if ( const SMDS_MeshElement* e = eIt->next())
3740                       smIDs.push_back( e->getshapeId() );
3741                   // write HDF group
3742                   aSize[ 0 ] = nbElems;
3743                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3744                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3745                   aDataset->CreateOnDisk();
3746                   aDataset->WriteOnDisk( & smIDs[0] );
3747                   aDataset->CloseOnDisk();
3748                 }
3749
3750                 aGroup->CloseOnDisk();
3751
3752                 // Store node positions on sub-shapes (SMDS_Position):
3753                 // ----------------------------------------------------
3754
3755                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3756                 aGroup->CreateOnDisk();
3757
3758                 // in aGroup, create 5 datasets to contain:
3759                 // "Nodes on Edges" - ID of node on edge
3760                 // "Edge positions" - U parameter on node on edge
3761                 // "Nodes on Faces" - ID of node on face
3762                 // "Face U positions" - U parameter of node on face
3763                 // "Face V positions" - V parameter of node on face
3764
3765                 // Find out nb of nodes on edges and faces
3766                 // Collect corresponing sub-meshes
3767                 int nbEdgeNodes = 0, nbFaceNodes = 0;
3768                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3769                 // loop on SMESHDS_SubMesh'es
3770                 while ( smIt->more() )
3771                 {
3772                   SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3773                   if ( aSubMesh->IsComplexSubmesh() )
3774                     continue; // submesh containing other submeshs
3775                   int nbNodes = aSubMesh->NbNodes();
3776                   if ( nbNodes == 0 ) continue;
3777
3778                   int aShapeID = aSubMesh->GetID();
3779                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3780                     continue;
3781                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3782                   // write only SMDS_FacePosition and SMDS_EdgePosition
3783                   switch ( aShapeType ) {
3784                   case TopAbs_FACE:
3785                     nbFaceNodes += nbNodes;
3786                     aFaceSM.push_back( aSubMesh );
3787                     break;
3788                   case TopAbs_EDGE:
3789                     nbEdgeNodes += nbNodes;
3790                     aEdgeSM.push_back( aSubMesh );
3791                     break;
3792                   default:
3793                     continue;
3794                   }
3795                 }
3796                 // Treat positions on edges or faces
3797                 for ( int onFace = 0; onFace < 2; onFace++ )
3798                 {
3799                   // Create arrays to store in datasets
3800                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3801                   if (!nbNodes) continue;
3802                   int* aNodeIDs = new int [ nbNodes ];
3803                   double* aUPos = new double [ nbNodes ];
3804                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3805
3806                   // Fill arrays
3807                   // loop on sub-meshes
3808                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3809                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3810                   for ( ; itSM != pListSM->end(); itSM++ )
3811                   {
3812                     SMESHDS_SubMesh* aSubMesh = (*itSM);
3813
3814                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3815                     // loop on nodes in aSubMesh
3816                     while ( itNode->more() )
3817                     {
3818                       //node ID
3819                       const SMDS_MeshNode* node = itNode->next();
3820                       aNodeIDs [ iNode ] = node->GetID();
3821
3822                       // Position
3823                       const SMDS_PositionPtr pos = node->GetPosition();
3824                       if ( onFace ) { // on FACE
3825                         const SMDS_FacePosition* fPos =
3826                           dynamic_cast<const SMDS_FacePosition*>( pos );
3827                         if ( fPos ) {
3828                           aUPos[ iNode ] = fPos->GetUParameter();
3829                           aVPos[ iNode ] = fPos->GetVParameter();
3830                           iNode++;
3831                         }
3832                         else
3833                           nbNodes--;
3834                       }
3835                       else { // on EDGE
3836                         const SMDS_EdgePosition* ePos =
3837                           dynamic_cast<const SMDS_EdgePosition*>( pos );
3838                         if ( ePos ) {
3839                           aUPos[ iNode ] = ePos->GetUParameter();
3840                           iNode++;
3841                         }
3842                         else
3843                           nbNodes--;
3844                       }
3845                     } // loop on nodes in aSubMesh
3846                   } // loop on sub-meshes
3847
3848                   // Write datasets
3849                   if ( nbNodes )
3850                   {
3851                     aSize[ 0 ] = nbNodes;
3852                     // IDS
3853                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3854                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3855                     aDataset->CreateOnDisk();
3856                     aDataset->WriteOnDisk( aNodeIDs );
3857                     aDataset->CloseOnDisk();
3858
3859                     // U Positions
3860                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
3861                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3862                     aDataset->CreateOnDisk();
3863                     aDataset->WriteOnDisk( aUPos );
3864                     aDataset->CloseOnDisk();
3865                     // V Positions
3866                     if ( onFace ) {
3867                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3868                       aDataset->CreateOnDisk();
3869                       aDataset->WriteOnDisk( aVPos );
3870                       aDataset->CloseOnDisk();
3871                     }
3872                   }
3873                   delete [] aNodeIDs;
3874                   delete [] aUPos;
3875                   if ( aVPos ) delete [] aVPos;
3876
3877                 } // treat positions on edges or faces
3878
3879                 // close "Node Positions" group
3880                 aGroup->CloseOnDisk();
3881
3882               } // if ( there are submeshes in SMESHDS_Mesh )
3883             } // if ( hasData )
3884
3885             // close mesh HDF group
3886             aTopGroup->CloseOnDisk();
3887           }
3888         }
3889       }
3890     }
3891   }
3892
3893   // close HDF file
3894   aFile->CloseOnDisk();
3895   delete aFile;
3896
3897   // Convert temporary files to stream
3898   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3899
3900   // Remove temporary files and directory
3901   if ( !isMultiFile )
3902     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3903
3904   INFOS( "SMESH_Gen_i::Save() completed" );
3905   return aStreamFile._retn();
3906 }
3907
3908 //=============================================================================
3909 /*!
3910  *  SMESH_Gen_i::SaveASCII
3911  *
3912  *  Save SMESH module's data in ASCII format
3913  */
3914 //=============================================================================
3915
3916 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3917                                            const char*              theURL,
3918                                            bool                     isMultiFile ) {
3919   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3920   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3921   return aStreamFile._retn();
3922
3923   //after usual saving needs to encipher binary to text string
3924   //Any binary symbol will be represent as "|xx" () hexadecimal format number
3925   int size = aStreamFile.in().length();
3926   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3927   for ( int i = 0; i < size; i++ )
3928     sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3929
3930   buffer[size * 3] = '\0';
3931
3932   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3933
3934   return anAsciiStreamFile._retn();
3935 }
3936
3937 //=============================================================================
3938 /*!
3939  *  SMESH_Gen_i::loadGeomData
3940  *
3941  *  Load GEOM module data
3942  */
3943 //=============================================================================
3944
3945 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3946 {
3947   if ( theCompRoot->_is_nil() )
3948     return;
3949
3950   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3951   if ( aStudy->_is_nil() )
3952     return;
3953
3954   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
3955   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3956 }
3957
3958 //=============================================================================
3959 /*!
3960  *  SMESH_Gen_i::Load
3961  *
3962  *  Load SMESH module's data
3963  */
3964 //=============================================================================
3965
3966 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3967                         const SALOMEDS::TMPFile& theStream,
3968                         const char*              theURL,
3969                         bool                     isMultiFile )
3970 {
3971   INFOS( "SMESH_Gen_i::Load" );
3972
3973   if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
3974     SetCurrentStudy( theComponent->GetStudy() );
3975
3976   /*  if( !theComponent->_is_nil() )
3977       {
3978       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
3979       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
3980       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
3981       }*/
3982
3983   StudyContext* myStudyContext = GetCurrentStudyContext();
3984
3985   // Get temporary files location
3986   TCollection_AsciiString tmpDir =
3987     ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
3988
3989   INFOS( "THE URL++++++++++++++" );
3990   INFOS( theURL );
3991   INFOS( "THE TMP PATH+++++++++" );
3992   INFOS( tmpDir );
3993
3994   // Convert the stream into sequence of files to process
3995   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
3996                                                                             tmpDir.ToCString(),
3997                                                                             isMultiFile );
3998   TCollection_AsciiString aStudyName( "" );
3999   if ( isMultiFile ) {
4000     CORBA::String_var url = myCurrentStudy->URL();
4001     aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( url.in() ).c_str();
4002   }
4003   // Set names of temporary files
4004   TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4005   TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4006
4007   int size;
4008   HDFfile*    aFile;
4009   HDFdataset* aDataset;
4010   HDFgroup*   aTopGroup;
4011   HDFgroup*   aGroup;
4012   HDFgroup*   aSubGroup;
4013   HDFgroup*   aSubSubGroup;
4014
4015   // Read data
4016   // ---> open HDF file
4017   aFile = new HDFfile( (char*) filename.ToCString() );
4018   try {
4019     aFile->OpenOnDisk( HDF_RDONLY );
4020   }
4021   catch ( HDFexception ) {
4022     INFOS( "Load(): " << filename << " not found!" );
4023     return false;
4024   }
4025
4026   TPythonDump pd; // prevent dump during loading
4027
4028   // DriverMED_R_SMESHDS_Mesh myReader;
4029   // myReader.SetFile( meshfile.ToCString() );
4030
4031   // For PAL13473 ("Repetitive mesh") implementation.
4032   // New dependencies between SMESH objects are established:
4033   // now hypotheses can refer to meshes, shapes and other hypotheses.
4034   // To keep data consistent, the following order of data restoration
4035   // imposed:
4036   // 1. Create hypotheses
4037   // 2. Create all meshes
4038   // 3. Load hypotheses' data
4039   // 4. All the rest
4040
4041   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
4042   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
4043   list< SMESH::Filter_var >                      filters;
4044
4045   // get total number of top-level groups
4046   int aNbGroups = aFile->nInternalObjects();
4047   if ( aNbGroups > 0 ) {
4048     // --> in first turn we should read&create hypotheses
4049     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4050       // open hypotheses root HDF group
4051       aTopGroup = new HDFgroup( "Hypotheses", aFile );
4052       aTopGroup->OpenOnDisk();
4053
4054       // get number of hypotheses
4055       int aNbObjects = aTopGroup->nInternalObjects();
4056       for ( int j = 0; j < aNbObjects; j++ ) {
4057         // try to identify hypothesis
4058         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4059         aTopGroup->InternalObjectIndentify( j, hypGrpName );
4060
4061         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4062           // open hypothesis group
4063           aGroup = new HDFgroup( hypGrpName, aTopGroup );
4064           aGroup->OpenOnDisk();
4065
4066           // --> get hypothesis id
4067           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4068           string hypname;
4069           string libname;
4070           string hypdata;
4071
4072           // get number of datasets
4073           int aNbSubObjects = aGroup->nInternalObjects();
4074           for ( int k = 0; k < aNbSubObjects; k++ ) {
4075             // identify dataset
4076             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4077             aGroup->InternalObjectIndentify( k, name_of_subgroup );
4078             // --> get hypothesis name
4079             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
4080               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4081               aDataset->OpenOnDisk();
4082               size = aDataset->GetSize();
4083               char* hypname_str = new char[ size ];
4084               aDataset->ReadFromDisk( hypname_str );
4085               hypname = string( hypname_str );
4086               delete [] hypname_str;
4087               aDataset->CloseOnDisk();
4088             }
4089             // --> get hypothesis plugin library name
4090             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
4091               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4092               aDataset->OpenOnDisk();
4093               size = aDataset->GetSize();
4094               char* libname_str = new char[ size ];
4095               aDataset->ReadFromDisk( libname_str );
4096               if(MYDEBUG) SCRUTE( libname_str );
4097               libname = string( libname_str );
4098               delete [] libname_str;
4099               aDataset->CloseOnDisk();
4100             }
4101             // --> get hypothesis data
4102             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
4103               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4104               aDataset->OpenOnDisk();
4105               size = aDataset->GetSize();
4106               char* hypdata_str = new char[ size ];
4107               aDataset->ReadFromDisk( hypdata_str );
4108               hypdata = string( hypdata_str );
4109               delete [] hypdata_str;
4110               aDataset->CloseOnDisk();
4111             }
4112           }
4113           // close hypothesis HDF group
4114           aGroup->CloseOnDisk();
4115
4116           // --> restore hypothesis from data
4117           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4118             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4119                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4120             SMESH::SMESH_Hypothesis_var myHyp;
4121
4122             try { // protect persistence mechanism against exceptions
4123               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4124             }
4125             catch (...) {
4126               INFOS( "Exception during hypothesis creation" );
4127             }
4128
4129             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4130             if ( myImpl ) {
4131               // myImpl->LoadFrom( hypdata.c_str() );
4132               hypDataList.push_back( make_pair( myImpl, hypdata ));
4133               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4134               int newId = myStudyContext->findId( iorString.in() );
4135               myStudyContext->mapOldToNew( id, newId );
4136             }
4137             else
4138               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4139           }
4140         }
4141       }
4142       // close hypotheses root HDF group
4143       aTopGroup->CloseOnDisk();
4144       aTopGroup = 0;
4145     }
4146
4147     // --> then we should read&create algorithms
4148     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4149       // open algorithms root HDF group
4150       aTopGroup = new HDFgroup( "Algorithms", aFile );
4151       aTopGroup->OpenOnDisk();
4152
4153       // get number of algorithms
4154       int aNbObjects = aTopGroup->nInternalObjects();
4155       for ( int j = 0; j < aNbObjects; j++ ) {
4156         // try to identify algorithm
4157         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4158         aTopGroup->InternalObjectIndentify( j, hypGrpName );
4159
4160         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4161           // open algorithm group
4162           aGroup = new HDFgroup( hypGrpName, aTopGroup );
4163           aGroup->OpenOnDisk();
4164
4165           // --> get algorithm id
4166           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4167           string hypname;
4168           string libname;
4169           string hypdata;
4170
4171           // get number of datasets
4172           int aNbSubObjects = aGroup->nInternalObjects();
4173           for ( int k = 0; k < aNbSubObjects; k++ ) {
4174             // identify dataset
4175             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4176             aGroup->InternalObjectIndentify( k, name_of_subgroup );
4177             // --> get algorithm name
4178             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
4179               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4180               aDataset->OpenOnDisk();
4181               size = aDataset->GetSize();
4182               char* hypname_str = new char[ size ];
4183               aDataset->ReadFromDisk( hypname_str );
4184               hypname = string( hypname_str );
4185               delete [] hypname_str;
4186               aDataset->CloseOnDisk();
4187             }
4188             // --> get algorithm plugin library name
4189             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
4190               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4191               aDataset->OpenOnDisk();
4192               size = aDataset->GetSize();
4193               char* libname_str = new char[ size ];
4194               aDataset->ReadFromDisk( libname_str );
4195               if(MYDEBUG) SCRUTE( libname_str );
4196               libname = string( libname_str );
4197               delete [] libname_str;
4198               aDataset->CloseOnDisk();
4199             }
4200             // --> get algorithm data
4201             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
4202               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4203               aDataset->OpenOnDisk();
4204               size = aDataset->GetSize();
4205               char* hypdata_str = new char[ size ];
4206               aDataset->ReadFromDisk( hypdata_str );
4207               if(MYDEBUG) SCRUTE( hypdata_str );
4208               hypdata = string( hypdata_str );
4209               delete [] hypdata_str;
4210               aDataset->CloseOnDisk();
4211             }
4212           }
4213           // close algorithm HDF group
4214           aGroup->CloseOnDisk();
4215
4216           // --> restore algorithm from data
4217           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4218             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4219                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4220             SMESH::SMESH_Hypothesis_var myHyp;
4221
4222             try { // protect persistence mechanism against exceptions
4223               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4224             }
4225             catch (...) {
4226               INFOS( "Exception during hypothesis creation" );
4227             }
4228
4229             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4230             if ( myImpl ) {
4231               //myImpl->LoadFrom( hypdata.c_str() );
4232               hypDataList.push_back( make_pair( myImpl, hypdata ));
4233               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4234               int newId = myStudyContext->findId( iorString.in() );
4235               myStudyContext->mapOldToNew( id, newId );
4236             }
4237             else
4238               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4239           }
4240         }
4241       }
4242       // close algorithms root HDF group
4243       aTopGroup->CloseOnDisk();
4244       aTopGroup = 0;
4245     }
4246
4247     // --> the rest groups should be meshes
4248     for ( int i = 0; i < aNbGroups; i++ ) {
4249       // identify next group
4250       char meshName[ HDF_NAME_MAX_LEN+1 ];
4251       aFile->InternalObjectIndentify( i, meshName );
4252
4253       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4254         // --> get mesh id
4255         int id = atoi( string( meshName ).substr( 4 ).c_str() );
4256         if ( id <= 0 )
4257           continue;
4258
4259         // open mesh HDF group
4260         aTopGroup = new HDFgroup( meshName, aFile );
4261         aTopGroup->OpenOnDisk();
4262
4263         // get number of child HDF objects
4264         int aNbObjects = aTopGroup->nInternalObjects();
4265         if ( aNbObjects > 0 ) {
4266           // create mesh
4267           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4268           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4269           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4270           if ( !myNewMeshImpl )
4271             continue;
4272           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4273
4274           CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4275           int newId = myStudyContext->findId( iorString.in() );
4276           myStudyContext->mapOldToNew( id, newId );
4277
4278           // ouv : NPAL12872
4279           // try to read and set auto color flag
4280           char aMeshAutoColorName[ 30 ];
4281           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4282           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4283           {
4284             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4285             aDataset->OpenOnDisk();
4286             size = aDataset->GetSize();
4287             int* anAutoColor = new int[ size ];
4288             aDataset->ReadFromDisk( anAutoColor );
4289             aDataset->CloseOnDisk();
4290             myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4291             delete [] anAutoColor;
4292           }
4293
4294           // try to read and set reference to shape
4295           GEOM::GEOM_Object_var aShapeObject;
4296           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4297             // load mesh "Ref on shape" - it's an entry to SObject
4298             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4299             aDataset->OpenOnDisk();
4300             size = aDataset->GetSize();
4301             char* refFromFile = new char[ size ];
4302             aDataset->ReadFromDisk( refFromFile );
4303             aDataset->CloseOnDisk();
4304             if ( strlen( refFromFile ) > 0 ) {
4305               SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4306
4307               // Make sure GEOM data are loaded first
4308               //loadGeomData( shapeSO->GetFatherComponent() );
4309
4310               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4311               if ( !CORBA::is_nil( shapeObject ) ) {
4312                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4313                 if ( !aShapeObject->_is_nil() )
4314                   myNewMeshImpl->SetShape( aShapeObject );
4315               }
4316             }
4317             delete [] refFromFile;
4318           }
4319
4320           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4321           if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4322           {
4323             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4324             aDataset->OpenOnDisk();
4325             size = aDataset->GetSize();
4326             int* meshPersistentId = new int[ size ];
4327             aDataset->ReadFromDisk( meshPersistentId );
4328             aDataset->CloseOnDisk();
4329             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4330             delete [] meshPersistentId;
4331           }
4332         }
4333       }
4334     } // reading MESHes
4335
4336     // As all object that can be referred by hypothesis are created,
4337     // we can restore hypothesis data
4338
4339     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4340     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4341     {
4342       SMESH_Hypothesis_i* hyp  = hyp_data->first;
4343       string &            data = hyp_data->second;
4344       hyp->LoadFrom( data.c_str() );
4345     }
4346
4347     // Restore the rest mesh data
4348
4349     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4350     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4351     {
4352       aTopGroup                   = meshi_group->second;
4353       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4354       //::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
4355       //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4356
4357       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4358       bool hasData = false;
4359
4360       // get mesh old id
4361       CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4362       int newId = myStudyContext->findId( iorString.in() );
4363       int id = myStudyContext->getOldId( newId );
4364
4365       // try to find mesh data dataset
4366       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4367         // load mesh "has data" flag
4368         aDataset = new HDFdataset( "Has data", aTopGroup );
4369         aDataset->OpenOnDisk();
4370         size = aDataset->GetSize();
4371         char* strHasData = new char[ size ];
4372         aDataset->ReadFromDisk( strHasData );
4373         aDataset->CloseOnDisk();
4374         if ( strcmp( strHasData, "1") == 0 ) {
4375           // read mesh data from MED file
4376           // myReader.SetMesh( mySMESHDSMesh );
4377           // myReader.SetMeshId( id );
4378           // myReader.Perform();
4379           hasData = true;
4380         }
4381         delete [] strHasData;
4382       }
4383
4384       // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4385       // nodes and elements are not yet put into sub-meshes)
4386       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4387         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4388         aGroup->OpenOnDisk();
4389         // get number of applied algorithms
4390         int aNbSubObjects = aGroup->nInternalObjects();
4391         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4392         for ( int j = 0; j < aNbSubObjects; j++ ) {
4393           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4394           aGroup->InternalObjectIndentify( j, name_dataset );
4395           // check if it is an algorithm
4396           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4397             aDataset = new HDFdataset( name_dataset, aGroup );
4398             aDataset->OpenOnDisk();
4399             size = aDataset->GetSize();
4400             char* refFromFile = new char[ size ];
4401             aDataset->ReadFromDisk( refFromFile );
4402             aDataset->CloseOnDisk();
4403             // san - it is impossible to recover applied algorithms using their entries within Load() method
4404             //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4405             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4406             int id = atoi( refFromFile );
4407             delete [] refFromFile;
4408             string anIOR = myStudyContext->getIORbyOldId( id );
4409             if ( !anIOR.empty() ) {
4410               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4411               if ( !CORBA::is_nil( hypObject ) ) {
4412                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4413                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4414                                            || !myNewMeshImpl->HasShapeToMesh()) )
4415                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4416               }
4417             }
4418           }
4419         }
4420         aGroup->CloseOnDisk();
4421       }
4422
4423       // try to get applied hypotheses
4424       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4425         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4426         aGroup->OpenOnDisk();
4427         // get number of applied hypotheses
4428         int aNbSubObjects = aGroup->nInternalObjects();
4429         for ( int j = 0; j < aNbSubObjects; j++ ) {
4430           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4431           aGroup->InternalObjectIndentify( j, name_dataset );
4432           // check if it is a hypothesis
4433           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4434             aDataset = new HDFdataset( name_dataset, aGroup );
4435             aDataset->OpenOnDisk();
4436             size = aDataset->GetSize();
4437             char* refFromFile = new char[ size ];
4438             aDataset->ReadFromDisk( refFromFile );
4439             aDataset->CloseOnDisk();
4440             // san - it is impossible to recover applied hypotheses using their entries within Load() method
4441             //SALOMEDS::SObject_wrap hypSO = myCurrentStudy->FindObjectID( refFromFile );
4442             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4443             int id = atoi( refFromFile );
4444             delete [] refFromFile;
4445             string anIOR = myStudyContext->getIORbyOldId( id );
4446             if ( !anIOR.empty() ) {
4447               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4448               if ( !CORBA::is_nil( hypObject ) ) {
4449                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4450                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4451                                            || !myNewMeshImpl->HasShapeToMesh()) )
4452                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4453               }
4454             }
4455           }
4456         }
4457         aGroup->CloseOnDisk();
4458       }
4459
4460       // --> try to find SUB-MESHES containers for each type of submesh
4461       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4462         const char* name_meshgroup;
4463         if ( j == GetSubMeshOnVertexTag() )
4464           name_meshgroup = "SubMeshes On Vertex";
4465         else if ( j == GetSubMeshOnEdgeTag() )
4466           name_meshgroup = "SubMeshes On Edge";
4467         else if ( j == GetSubMeshOnWireTag() )
4468           name_meshgroup = "SubMeshes On Wire";
4469         else if ( j == GetSubMeshOnFaceTag() )
4470           name_meshgroup = "SubMeshes On Face";
4471         else if ( j == GetSubMeshOnShellTag() )
4472           name_meshgroup = "SubMeshes On Shell";
4473         else if ( j == GetSubMeshOnSolidTag() )
4474           name_meshgroup = "SubMeshes On Solid";
4475         else if ( j == GetSubMeshOnCompoundTag() )
4476           name_meshgroup = "SubMeshes On Compound";
4477
4478         // try to get submeshes container HDF group
4479         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4480           // open submeshes containers HDF group
4481           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4482           aGroup->OpenOnDisk();
4483
4484           // get number of submeshes
4485           int aNbSubMeshes = aGroup->nInternalObjects();
4486           for ( int k = 0; k < aNbSubMeshes; k++ ) {
4487             // identify submesh
4488             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4489             aGroup->InternalObjectIndentify( k, name_submeshgroup );
4490             if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4491               // --> get submesh id
4492               int subid = atoi( name_submeshgroup + 7 );
4493               if ( subid <= 0 )
4494                 continue;
4495               // open submesh HDF group
4496               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4497               aSubGroup->OpenOnDisk();
4498
4499               // try to read and set reference to subshape
4500               GEOM::GEOM_Object_var aSubShapeObject;
4501               SMESH::SMESH_subMesh_var aSubMesh;
4502
4503               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4504                 // load submesh "Ref on shape" - it's an entry to SObject
4505                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4506                 aDataset->OpenOnDisk();
4507                 size = aDataset->GetSize();
4508                 char* refFromFile = new char[ size ];
4509                 aDataset->ReadFromDisk( refFromFile );
4510                 aDataset->CloseOnDisk();
4511                 if ( strlen( refFromFile ) > 0 ) {
4512                   SALOMEDS::SObject_wrap subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4513                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4514                   if ( !CORBA::is_nil( subShapeObject ) ) {
4515                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4516                     if ( !aSubShapeObject->_is_nil() )
4517                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
4518                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4519                     if ( aSubMesh->_is_nil() )
4520                       continue;
4521                     string iorSubString = GetORB()->object_to_string( aSubMesh );
4522                     int newSubId = myStudyContext->findId( iorSubString );
4523                     myStudyContext->mapOldToNew( subid, newSubId );
4524                   }
4525                 }
4526               }
4527
4528               if ( aSubMesh->_is_nil() )
4529                 continue;
4530
4531               // try to get applied algorithms
4532               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4533                 // open "applied algorithms" HDF group
4534                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4535                 aSubSubGroup->OpenOnDisk();
4536                 // get number of applied algorithms
4537                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4538                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4539                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4540                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4541                   // check if it is an algorithm
4542                   if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4543                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4544                     aDataset->OpenOnDisk();
4545                     size = aDataset->GetSize();
4546                     char* refFromFile = new char[ size ];
4547                     aDataset->ReadFromDisk( refFromFile );
4548                     aDataset->CloseOnDisk();
4549
4550                     int id = atoi( refFromFile );
4551                     string anIOR = myStudyContext->getIORbyOldId( id );
4552                     if ( !anIOR.empty() ) {
4553                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4554                       if ( !CORBA::is_nil( hypObject ) ) {
4555                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4556                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4557                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4558                       }
4559                     }
4560                   }
4561                 }
4562                 // close "applied algorithms" HDF group
4563                 aSubSubGroup->CloseOnDisk();
4564               }
4565
4566               // try to get applied hypotheses
4567               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4568                 // open "applied hypotheses" HDF group
4569                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4570                 aSubSubGroup->OpenOnDisk();
4571                 // get number of applied hypotheses
4572                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4573                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4574                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4575                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4576                   // check if it is a hypothesis
4577                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4578                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4579                     aDataset->OpenOnDisk();
4580                     size = aDataset->GetSize();
4581                     char* refFromFile = new char[ size ];
4582                     aDataset->ReadFromDisk( refFromFile );
4583                     aDataset->CloseOnDisk();
4584
4585                     int id = atoi( refFromFile );
4586                     string anIOR = myStudyContext->getIORbyOldId( id );
4587                     if ( !anIOR.empty() ) {
4588                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4589                       if ( !CORBA::is_nil( hypObject ) ) {
4590                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4591                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4592                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4593                       }
4594                     }
4595                   }
4596                 }
4597                 // close "APPLIED HYPOTHESES" hdf group
4598                 aSubSubGroup->CloseOnDisk();
4599               }
4600
4601               // close SUB-MESH hdf group
4602               aSubGroup->CloseOnDisk();
4603             }
4604           }
4605           // close SUB-MESHES containers hdf group
4606           aGroup->CloseOnDisk();
4607         }
4608       }
4609
4610       // try to get GROUPS
4611       for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4612         char name_group[ 30 ];
4613         if ( ii == GetNodeGroupsTag() )
4614           strcpy( name_group, "Groups of Nodes" );
4615         else if ( ii == GetEdgeGroupsTag() )
4616           strcpy( name_group, "Groups of Edges" );
4617         else if ( ii == GetFaceGroupsTag() )
4618           strcpy( name_group, "Groups of Faces" );
4619         else if ( ii == GetVolumeGroupsTag() )
4620           strcpy( name_group, "Groups of Volumes" );
4621         else if ( ii == Get0DElementsGroupsTag() )
4622           strcpy( name_group, "Groups of 0D Elements" );
4623         else if ( ii == GetBallElementsGroupsTag() )
4624           strcpy( name_group, "Groups of Balls" );
4625
4626         if ( aTopGroup->ExistInternalObject( name_group ) ) {
4627           aGroup = new HDFgroup( name_group, aTopGroup );
4628           aGroup->OpenOnDisk();
4629           // get number of groups
4630           int aNbSubObjects = aGroup->nInternalObjects();
4631           for ( int j = 0; j < aNbSubObjects; j++ ) {
4632             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4633             aGroup->InternalObjectIndentify( j, name_dataset );
4634             // check if it is an group
4635             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4636               // --> get group id
4637               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4638               if ( subid <= 0 )
4639                 continue;
4640               aDataset = new HDFdataset( name_dataset, aGroup );
4641               aDataset->OpenOnDisk();
4642
4643               // Retrieve actual group name
4644               size = aDataset->GetSize();
4645               char* nameFromFile = new char[ size ];
4646               aDataset->ReadFromDisk( nameFromFile );
4647               aDataset->CloseOnDisk();
4648
4649               // Try to find a shape reference
4650               TopoDS_Shape aShape;
4651               char aRefName[ 30 ];
4652               sprintf( aRefName, "Ref on shape %d", subid);
4653               if ( aGroup->ExistInternalObject( aRefName ) ) {
4654                 // load mesh "Ref on shape" - it's an entry to SObject
4655                 aDataset = new HDFdataset( aRefName, aGroup );
4656                 aDataset->OpenOnDisk();
4657                 size = aDataset->GetSize();
4658                 char* refFromFile = new char[ size ];
4659                 aDataset->ReadFromDisk( refFromFile );
4660                 aDataset->CloseOnDisk();
4661                 if ( strlen( refFromFile ) > 0 ) {
4662                   SALOMEDS::SObject_wrap shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4663                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4664                   if ( !CORBA::is_nil( shapeObject ) ) {
4665                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4666                     if ( !aShapeObject->_is_nil() )
4667                       aShape = GeomObjectToShape( aShapeObject );
4668                   }
4669                 }
4670               }
4671               // Try to read a filter of SMESH_GroupOnFilter
4672               SMESH::Filter_var filter;
4673               SMESH_PredicatePtr predicate;
4674               std::string hdfGrpName = "Filter " + SMESH_Comment(subid);
4675               if ( aGroup->ExistInternalObject( hdfGrpName.c_str() ))
4676               {
4677                 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4678                 aDataset->OpenOnDisk();
4679                 size = aDataset->GetSize();
4680                 char* persistStr = new char[ size ];
4681                 aDataset->ReadFromDisk( persistStr );
4682                 aDataset->CloseOnDisk();
4683                 if ( strlen( persistStr ) > 0 ) {
4684                   filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4685                   predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4686                   filters.push_back( filter );
4687                 }
4688               }
4689
4690               // Create group servant
4691               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4692               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4693                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4694               // Obtain a SMESHDS_Group object
4695               if ( aNewGroup->_is_nil() )
4696                 continue;
4697
4698               string iorSubString = GetORB()->object_to_string( aNewGroup );
4699               int        newSubId = myStudyContext->findId( iorSubString );
4700               myStudyContext->mapOldToNew( subid, newSubId );
4701
4702               SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4703               if ( !aGroupImpl )
4704                 continue;
4705
4706               if ( SMESH_GroupOnFilter_i* aFilterGroup =
4707                    dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4708               {
4709                 aFilterGroup->SetFilter( filter );
4710                 filter->UnRegister();
4711               }
4712               SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4713               if ( !aGroupBaseDS )
4714                 continue;
4715
4716               aGroupBaseDS->SetStoreName( name_dataset );
4717
4718               // ouv : NPAL12872
4719               // Read color of the group
4720               char aGroupColorName[ 30 ];
4721               sprintf( aGroupColorName, "ColorGroup %d", subid);
4722               if ( aGroup->ExistInternalObject( aGroupColorName ) )
4723               {
4724                 aDataset = new HDFdataset( aGroupColorName, aGroup );
4725                 aDataset->OpenOnDisk();
4726                 size = aDataset->GetSize();
4727                 double* anRGB = new double[ size ];
4728                 aDataset->ReadFromDisk( anRGB );
4729                 aDataset->CloseOnDisk();
4730                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4731                 aGroupBaseDS->SetColor( aColor );
4732               }
4733             }
4734           }
4735           aGroup->CloseOnDisk();
4736         }
4737       } // reading GROUPs
4738
4739       // instead of reading mesh data, we read only brief information of all
4740       // objects: mesh, groups, sub-meshes (issue 0021208 )
4741       if ( hasData )
4742       {
4743         SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4744                                          meshfile.ToCString(), filename.ToCString(),
4745                                          !isMultiFile );
4746       }
4747
4748       // read Sub-Mesh ORDER if any
4749       if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4750         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4751         aDataset->OpenOnDisk();
4752         size = aDataset->GetSize();
4753         int* smIDs = new int[ size ];
4754         aDataset->ReadFromDisk( smIDs );
4755         aDataset->CloseOnDisk();
4756         TListOfListOfInt anOrderIds;
4757         anOrderIds.push_back( TListOfInt() );
4758         for ( int i = 0; i < size; i++ )
4759           if ( smIDs[ i ] < 0 ) // is separator
4760             anOrderIds.push_back( TListOfInt() );
4761           else
4762             anOrderIds.back().push_back(smIDs[ i ]);
4763
4764         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4765       }
4766     } // loop on meshes
4767
4768     // update hyps needing full mesh data restored (issue 20918)
4769     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4770     {
4771       SMESH_Hypothesis_i* hyp  = hyp_data->first;
4772       hyp->UpdateAsMeshesRestored();
4773     }
4774
4775     // notify algos on completed restoration to set sub-mesh event listeners
4776     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4777     {
4778       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4779       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
4780
4781       TopoDS_Shape myLocShape;
4782       if(myLocMesh.HasShapeToMesh())
4783         myLocShape = myLocMesh.GetShapeToMesh();
4784       else
4785         myLocShape = SMESH_Mesh::PseudoShape();
4786
4787       myLocMesh.GetSubMesh(myLocShape)->
4788         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4789     }
4790
4791     // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4792     list< SMESH::Filter_var >::iterator f = filters.begin();
4793     for ( ; f != filters.end(); ++f )
4794       if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4795         fi->FindBaseObjects();
4796
4797
4798     // close mesh group
4799     if(aTopGroup)
4800       aTopGroup->CloseOnDisk();
4801   }
4802   // close HDF file
4803   aFile->CloseOnDisk();
4804   delete aFile;
4805
4806   // Remove temporary files created from the stream
4807   if ( !isMultiFile )
4808   {
4809     SMESH_File meshFile( meshfile.ToCString() );
4810     if ( !meshFile ) // no meshfile exists
4811     {
4812       SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4813     }
4814     else
4815     {
4816       Engines::Container_var container = GetContainerRef();
4817       if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4818       {
4819         container_i->registerTemporaryFile( filename.ToCString() );
4820         container_i->registerTemporaryFile( meshfile.ToCString() );
4821         container_i->registerTemporaryFile( tmpDir.ToCString() );
4822       }
4823     }
4824   }
4825   pd << ""; // prevent optimizing pd out
4826
4827   // creation of tree nodes for all data objects in the study
4828   // to support tree representation customization and drag-n-drop:
4829   SALOMEDS::Study_var                    study = theComponent->GetStudy();
4830   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = study->GetUseCaseBuilder();
4831   if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4832     useCaseBuilder->SetRootCurrent();
4833     useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4834     SALOMEDS::ChildIterator_wrap it = study->NewChildIterator( theComponent );
4835     for (it->InitEx(true); it->More(); it->Next()) {
4836       useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4837     }
4838   }
4839
4840   INFOS( "SMESH_Gen_i::Load completed" );
4841   return true;
4842 }
4843
4844 //=============================================================================
4845 /*!
4846  *  SMESH_Gen_i::LoadASCII
4847  *
4848  *  Load SMESH module's data in ASCII format
4849  */
4850 //=============================================================================
4851
4852 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4853                              const SALOMEDS::TMPFile& theStream,
4854                              const char*              theURL,
4855                              bool                     isMultiFile ) {
4856   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4857   return Load( theComponent, theStream, theURL, isMultiFile );
4858
4859   //before call main ::Load method it's need for decipher text format to
4860   //binary ( "|xx" => x' )
4861   int size = theStream.length();
4862   if ( int((size / 3 )*3) != size ) //error size of buffer
4863     return false;
4864
4865   int real_size = int(size / 3);
4866
4867   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4868   char tmp[3];
4869   tmp[2]='\0';
4870   int c = -1;
4871   for ( int i = 0; i < real_size; i++ )
4872   {
4873     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4874     sscanf( tmp, "%x", &c );
4875     sprintf( (char*)&(buffer[i]), "%c", (char)c );
4876   }
4877
4878   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4879
4880   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4881 }
4882
4883 //=============================================================================
4884 /*!
4885  *  SMESH_Gen_i::Close
4886  *
4887  *  Clears study-connected data when it is closed
4888  */
4889 //=============================================================================
4890
4891 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4892 {
4893   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4894
4895   // set correct current study
4896   SALOMEDS::Study_var study = theComponent->GetStudy();
4897   if ( study->StudyId() != GetCurrentStudyID())
4898     setCurrentStudy( study, /*IsBeingClosed=*/true );
4899
4900   // Clear study contexts data
4901   int studyId = GetCurrentStudyID();
4902   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4903     delete myStudyContextMap[ studyId ];
4904     myStudyContextMap.erase( studyId );
4905   }
4906
4907   // remove the tmp files meshes are loaded from
4908   SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4909
4910   myCurrentStudy = SALOMEDS::Study::_nil();
4911   return;
4912 }
4913
4914 //=============================================================================
4915 /*!
4916  *  SMESH_Gen_i::ComponentDataType
4917  *
4918  *  Get component data type
4919  */
4920 //=============================================================================
4921
4922 char* SMESH_Gen_i::ComponentDataType()
4923 {
4924   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4925   return CORBA::string_dup( "SMESH" );
4926 }
4927
4928
4929 //=============================================================================
4930 /*!
4931  *  SMESH_Gen_i::IORToLocalPersistentID
4932  *
4933  *  Transform data from transient form to persistent
4934  */
4935 //=============================================================================
4936
4937 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4938                                            const char*           IORString,
4939                                            CORBA::Boolean        /*isMultiFile*/,
4940                                            CORBA::Boolean        /*isASCII*/ )
4941 {
4942   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4943   StudyContext* myStudyContext = GetCurrentStudyContext();
4944
4945   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4946     int anId = myStudyContext->findId( IORString );
4947     if ( anId ) {
4948       if(MYDEBUG) MESSAGE( "VSR " << anId )
4949       char strId[ 20 ];
4950       sprintf( strId, "%d", anId );
4951       return  CORBA::string_dup( strId );
4952     }
4953   }
4954   return CORBA::string_dup( "" );
4955 }
4956
4957 //=============================================================================
4958 /*!
4959  *  SMESH_Gen_i::LocalPersistentIDToIOR
4960  *
4961  *  Transform data from persistent form to transient
4962  */
4963 //=============================================================================
4964
4965 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4966                                            const char*           aLocalPersistentID,
4967                                            CORBA::Boolean        /*isMultiFile*/,
4968                                            CORBA::Boolean        /*isASCII*/ )
4969 {
4970   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4971   StudyContext* myStudyContext = GetCurrentStudyContext();
4972
4973   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4974     int anId = atoi( aLocalPersistentID );
4975     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4976   }
4977   return CORBA::string_dup( "" );
4978 }
4979
4980 //=======================================================================
4981 //function : RegisterObject
4982 //purpose  :
4983 //=======================================================================
4984
4985 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4986 {
4987   StudyContext* myStudyContext = GetCurrentStudyContext();
4988   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4989     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4990     return myStudyContext->addObject( string( iorString.in() ) );
4991   }
4992   return 0;
4993 }
4994
4995 //================================================================================
4996 /*!
4997  * \brief Return id of registered object
4998   * \param theObject - the Object
4999   * \retval int - Object id
5000  */
5001 //================================================================================
5002
5003 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5004 {
5005   StudyContext* myStudyContext = GetCurrentStudyContext();
5006   if ( myStudyContext && !CORBA::is_nil( theObject )) {
5007     string iorString = GetORB()->object_to_string( theObject );
5008     return myStudyContext->findId( iorString );
5009   }
5010   return 0;
5011 }
5012
5013 //=============================================================================
5014 /*!
5015  *  SMESH_Gen_i::SetName
5016  *
5017  *  Set a new object name
5018  */
5019 //=============================================================================
5020 void SMESH_Gen_i::SetName(const char* theIOR,
5021                           const char* theName)
5022 {
5023   if ( theIOR && strcmp( theIOR, "" ) ) {
5024     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5025     SALOMEDS::SObject_wrap aSO = ObjectToSObject( myCurrentStudy, anObject );
5026     if ( !aSO->_is_nil() ) {
5027       SetName( aSO, theName );
5028     }
5029   }
5030 }
5031
5032 int SMESH_Gen_i::GetCurrentStudyID()
5033 {
5034   return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
5035 }
5036
5037 // Version information
5038 char* SMESH_Gen_i::getVersion()
5039 {
5040 #if SMESH_DEVELOPMENT
5041   return CORBA::string_dup(SMESH_VERSION_STR"dev");
5042 #else
5043   return CORBA::string_dup(SMESH_VERSION_STR);
5044 #endif
5045 }
5046
5047 //=================================================================================
5048 // function : Move()
5049 // purpose  : Moves objects to the specified position.
5050 //            Is used in the drag-n-drop functionality.
5051 //=================================================================================
5052 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5053                         SALOMEDS::SObject_ptr where,
5054                         CORBA::Long row )
5055 {
5056   if ( CORBA::is_nil( where ) ) return;
5057
5058   SALOMEDS::Study_var study = where->GetStudy();
5059   SALOMEDS::StudyBuilder_var studyBuilder = study->NewBuilder();
5060   SALOMEDS::UseCaseBuilder_var useCaseBuilder = study->GetUseCaseBuilder();
5061   SALOMEDS::SComponent_var father = where->GetFatherComponent();
5062   std::string dataType = father->ComponentDataType();
5063   if ( dataType != "SMESH" ) return; // not a SMESH component
5064
5065   SALOMEDS::SObject_var objAfter;
5066   if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5067     // insert at given row -> find insertion position
5068     SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5069     int i;
5070     for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5071     if ( i == row && useCaseIt->More() ) {
5072       objAfter = useCaseIt->Value();
5073     }
5074   }
5075
5076   for ( int i = 0; i < what.length(); i++ ) {
5077     SALOMEDS::SObject_var sobj = what[i];
5078     if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5079     // insert the object to the use case tree
5080     if ( !CORBA::is_nil( objAfter ) )
5081       useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5082     else
5083       useCaseBuilder->AppendTo( where, sobj );        // append to the end of list
5084   }
5085 }
5086 //================================================================================
5087 /*!
5088  * \brief Returns true if algorithm can be used to mesh a given geometry
5089  *  \param [in] theAlgoType - the algorithm type
5090  *  \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5091  *  \param [in] theGeomObject - the geometry to mesh
5092  *  \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5093  *         else, returns \c True if at least one shape is meshable
5094  *  \return CORBA::Boolean - can or can't
5095  */
5096 //================================================================================
5097
5098 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char*           theAlgoType,
5099                                            const char*           theLibName,
5100                                            GEOM::GEOM_Object_ptr theGeomObject,
5101                                            CORBA::Boolean        toCheckAll)
5102 {
5103   SMESH_TRY;
5104
5105   std::string aPlatformLibName;
5106   typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5107   GenericHypothesisCreator_i* aCreator =
5108     getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5109   if (aCreator)
5110   {
5111     TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5112     return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5113   }
5114   else
5115   {
5116     return false;
5117   }
5118
5119   SMESH_CATCH( SMESH::doNothing );
5120
5121 #ifdef _DEBUG_
5122   cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5123 #endif
5124   return true;
5125 }
5126
5127 //=================================================================================
5128 // function : GetInsideSphere
5129 // purpose  : Collect indices of elements, which are located inside the sphere
5130 //=================================================================================
5131 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
5132                                                  SMESH::ElementType     theElemType,
5133                                                  CORBA::Double         theX,
5134                                                  CORBA::Double         theY,
5135                                                  CORBA::Double         theZ,
5136                                                  CORBA::Double         theR) {
5137   SMESH::long_array_var aResult = new SMESH::long_array();
5138   if(meshPart->_is_nil())
5139     return aResult._retn();
5140
5141   // 1. Create geometrical object
5142   gp_Pnt aP( theX, theY, theZ );
5143   TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
5144
5145   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5146
5147   if( lst.size() > 0 ) {
5148     aResult->length( lst.size() );
5149     for ( long i = 0; i < lst.size(); i++ ) {
5150       aResult[i] = lst[i];
5151     }
5152   }
5153   return aResult._retn();
5154 }
5155
5156 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
5157                                               SMESH::ElementType        theElemType,
5158                                               CORBA::Double             theX1,
5159                                               CORBA::Double             theY1,
5160                                               CORBA::Double             theZ1,
5161                                               CORBA::Double             theX2,
5162                                               CORBA::Double             theY2,
5163                                               CORBA::Double             theZ2) {
5164   SMESH::long_array_var aResult = new SMESH::long_array();
5165   if( meshPart->_is_nil() )
5166     return aResult._retn();
5167
5168   TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
5169
5170   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5171
5172   if( lst.size() > 0 ) {
5173     aResult->length( lst.size() );
5174     for ( long i = 0; i < lst.size(); i++ ) {
5175       aResult[i] = lst[i];
5176     }
5177   }
5178   return aResult._retn();
5179 }
5180
5181 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
5182                                                    SMESH::ElementType        theElemType,
5183                                                    CORBA::Double             theX,
5184                                                    CORBA::Double             theY,
5185                                                    CORBA::Double             theZ,
5186                                                    CORBA::Double             theDX,
5187                                                    CORBA::Double             theDY,
5188                                                    CORBA::Double             theDZ,
5189                                                    CORBA::Double             theH,
5190                                                    CORBA::Double             theR ){
5191   SMESH::long_array_var aResult = new SMESH::long_array();
5192   if( meshPart->_is_nil() )
5193     return aResult._retn();
5194
5195   gp_Pnt aP( theX, theY, theZ );
5196   gp_Vec aV( theDX, theDY, theDZ );
5197   gp_Ax2 anAxes (aP, aV);
5198
5199   TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
5200
5201   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5202
5203   if( lst.size() > 0 ) {
5204     aResult->length( lst.size() );
5205     for ( long i = 0; i < lst.size(); i++ ) {
5206       aResult[i] = lst[i];
5207     }
5208   }
5209   return aResult._retn();
5210 }
5211
5212 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5213                                            SMESH::ElementType        theElemType,
5214                                            GEOM::GEOM_Object_ptr     theGeom,
5215                                            CORBA::Double             theTolerance ) {
5216   SMESH::long_array_var aResult = new SMESH::long_array();
5217   if( meshPart->_is_nil() || theGeom->_is_nil() )
5218     return aResult._retn();
5219
5220   TopoDS_Shape aShape = GeomObjectToShape( theGeom );
5221
5222   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
5223
5224   if( lst.size() > 0 ) {
5225     aResult->length( lst.size() );
5226     for ( long i = 0; i < lst.size(); i++ ) {
5227       aResult[i] = lst[i];
5228     }
5229   }
5230   return aResult._retn();
5231 }
5232
5233
5234
5235 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5236                                            SMESH::ElementType theElemType,
5237                                            TopoDS_Shape& aShape,
5238                                            double* theTolerance) {
5239
5240   std::vector<long> res;
5241   SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
5242
5243   if ( mesh->_is_nil() )
5244     return res;
5245
5246   SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5247   if ( !anImpl )
5248     return res;
5249
5250   const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
5251
5252   if ( !meshDS )
5253     return res;
5254
5255   SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
5256   SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
5257   anElementsOnShape->SetAllNodes( true );
5258   anElementsOnShape->SetMesh( meshDS );
5259   anElementsOnShape->SetShape( aShape, aType );
5260
5261   if(theTolerance)
5262     anElementsOnShape->SetTolerance(*theTolerance);
5263
5264   SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
5265   if ( !msource->_is_nil() ) { // Mesh case
5266     SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
5267     if ( elemIt ) {
5268       while ( elemIt->more() ) {
5269         const SMDS_MeshElement* anElem = elemIt->next();
5270         long anId = anElem->GetID();
5271         if ( anElementsOnShape->IsSatisfy( anId ) )
5272           res.push_back( anId );
5273       }
5274     }
5275   }
5276   SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
5277   if ( !gsource->_is_nil() ) {
5278     if(theElemType == SMESH::NODE) {
5279       SMESH::long_array_var nodes = gsource->GetNodeIDs();
5280       for ( int i = 0; i < nodes->length(); ++i ) {
5281         if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] ) ) {
5282           long anId = node->GetID();
5283           if ( anElementsOnShape->IsSatisfy( anId ) )
5284             res.push_back( anId );
5285         }
5286       }
5287     } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
5288       SMESH::long_array_var elems = gsource->GetListOfID();
5289       for ( int i = 0; i < elems->length(); ++i ) {
5290         if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] ) ) {
5291           long anId = elem->GetID();
5292           if ( anElementsOnShape->IsSatisfy( anId ) )
5293             res.push_back( anId );
5294         }
5295       }
5296     }
5297   }
5298   SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
5299   if ( !smsource->_is_nil() ) {
5300     SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
5301     for ( int i = 0; i < elems->length(); ++i ) {
5302       const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
5303       if (elem) {
5304         long anId = elem->GetID();
5305         if ( anElementsOnShape->IsSatisfy( anId ) )
5306           res.push_back( anId );
5307       }
5308     }
5309   }
5310   return res;
5311 }
5312
5313
5314 //=============================================================================
5315 /*!
5316  *  SMESHEngine_factory
5317  *
5318  *  C factory, accessible with dlsym, after dlopen
5319  */
5320 //=============================================================================
5321
5322 extern "C"
5323 { SMESH_I_EXPORT
5324   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
5325                                                  PortableServer::POA_ptr   poa,
5326                                                  PortableServer::ObjectId* contId,
5327                                                  const char*               instanceName,
5328                                                  const char*               interfaceName )
5329   {
5330     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5331     if(MYDEBUG) SCRUTE(interfaceName);
5332     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5333     return aSMESHGen->getId() ;
5334   }
5335 }