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