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