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