Salome HOME
BUG SWP13062
[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
95 #include CORBA_SERVER_HEADER(SMESH_Group)
96 #include CORBA_SERVER_HEADER(SMESH_Filter)
97
98 #include "DriverMED_W_SMESHDS_Mesh.h"
99 #include "DriverMED_R_SMESHDS_Mesh.h"
100
101 #include "SALOMEDS_Tool.hxx"
102 #include "SALOME_NamingService.hxx"
103 #include "SALOME_LifeCycleCORBA.hxx"
104 #include "Utils_SINGLETON.hxx"
105 #include "OpUtil.hxx"
106
107 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
108
109 #include "GEOM_Client.hxx"
110 #include "Utils_ExceptHandlers.hxx"
111
112 #include <map>
113
114 using namespace std;
115 using SMESH::TPythonDump;
116
117 #define NUM_TMP_FILES 2
118
119 #ifdef _DEBUG_
120 static int MYDEBUG = 1;
121 #else
122 static int MYDEBUG = 0;
123 #endif
124
125 // Static variables definition
126 CORBA::ORB_var          SMESH_Gen_i::myOrb;
127 PortableServer::POA_var SMESH_Gen_i::myPoa;
128 SALOME_NamingService*   SMESH_Gen_i::myNS  = NULL;
129 SALOME_LifeCycleCORBA*  SMESH_Gen_i::myLCC = NULL;
130 SMESH_Gen_i*            SMESH_Gen_i::mySMESHGen = NULL;
131
132 //=============================================================================
133 /*!
134  *  GetServant [ static ]
135  *
136  *  Get servant of the CORBA object
137  */
138 //=============================================================================
139
140 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
141 {
142   if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
143     return NULL;
144   try {
145     PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
146     return aServant;
147   } 
148   catch (...) {
149     INFOS( "GetServant - Unknown exception was caught!!!" ); 
150     return NULL;
151   }
152 }
153
154 //=============================================================================
155 /*!
156  *  SObjectToObject [ static ]
157  *
158  *  Get CORBA object corresponding to the SALOMEDS::SObject
159  */
160 //=============================================================================
161
162 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
163 {
164   SALOMEDS::GenericAttribute_var anAttr;
165   CORBA::Object_var anObj;
166   if ( !theSObject->_is_nil() ) {
167     try {
168       if( theSObject->FindAttribute( anAttr, "AttributeIOR" ) ) {
169         SALOMEDS::AttributeIOR_var anIOR  = SALOMEDS::AttributeIOR::_narrow( anAttr );
170         CORBA::String_var aValue = anIOR->Value();
171         if( strcmp( aValue, "" ) != 0 )
172           anObj = GetORB()->string_to_object( aValue );
173         }
174     }
175     catch( ... ) {
176       INFOS( "SObjectToObject - Unknown exception was caught!!!" );
177     }
178   }
179   return anObj;
180 }
181
182 //=============================================================================
183 /*!
184  *  GetNS [ static ]
185  *
186  *  Get SALOME_NamingService object 
187  */
188 //=============================================================================
189
190 SALOME_NamingService* SMESH_Gen_i::GetNS()
191 {
192   if ( myNS == NULL ) {
193     myNS = SINGLETON_<SALOME_NamingService>::Instance();
194     ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
195     myNS->init_orb( GetORB() );
196   }
197   return myNS;
198 }
199
200 //=============================================================================
201 /*!
202  *  GetLCC [ static ]
203  *
204  *  Get SALOME_LifeCycleCORBA object
205  */
206 //=============================================================================     
207 SALOME_LifeCycleCORBA*  SMESH_Gen_i::GetLCC() {
208   if ( myLCC == NULL ) {
209     myLCC = new SALOME_LifeCycleCORBA( GetNS() );
210   }
211   return myLCC;
212 }
213
214
215 //=============================================================================
216 /*!
217  *  GetGeomEngine [ static ]
218  *
219  *  Get GEOM::GEOM_Gen reference
220  */
221 //=============================================================================     
222 GEOM::GEOM_Gen_ptr SMESH_Gen_i::GetGeomEngine() {
223   GEOM::GEOM_Gen_var aGeomEngine =
224     GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
225   return aGeomEngine._retn();
226 }
227
228 //=============================================================================
229 /*!
230  *  SMESH_Gen_i::SMESH_Gen_i
231  *
232  *  Default constructor: not for use
233  */
234 //=============================================================================
235
236 SMESH_Gen_i::SMESH_Gen_i()
237 {
238   INFOS( "SMESH_Gen_i::SMESH_Gen_i : default constructor" );
239 }
240
241 //=============================================================================
242 /*!
243  *  SMESH_Gen_i::SMESH_Gen_i 
244  *
245  *  Standard constructor, used with Container
246  */
247 //=============================================================================
248
249 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr            orb,
250                           PortableServer::POA_ptr   poa,
251                           PortableServer::ObjectId* contId, 
252                           const char*               instanceName, 
253                           const char*               interfaceName )
254      : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
255 {
256   INFOS( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
257
258   myOrb = CORBA::ORB::_duplicate(orb);
259   myPoa = PortableServer::POA::_duplicate(poa);
260   
261   _thisObj = this ;
262   _id = myPoa->activate_object( _thisObj );
263   
264   myIsEmbeddedMode = false;
265   myShapeReader = NULL;  // shape reader
266   mySMESHGen = this;
267
268   // set it in standalone mode only
269   //OSD::SetSignal( true );
270 }
271
272 //=============================================================================
273 /*!
274  *  SMESH_Gen_i::~SMESH_Gen_i
275  *
276  *  Destructor
277  */
278 //=============================================================================
279
280 SMESH_Gen_i::~SMESH_Gen_i()
281 {
282   INFOS( "SMESH_Gen_i::~SMESH_Gen_i" );
283
284   // delete hypothesis creators
285   map<string, GenericHypothesisCreator_i*>::iterator itHyp;
286   for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
287   {
288     delete (*itHyp).second;
289   }
290   myHypCreatorMap.clear();
291
292   // Clear study contexts data
293   map<int, StudyContext*>::iterator it;
294   for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
295     delete it->second;
296   }
297   myStudyContextMap.clear();
298   // delete shape reader
299   if ( !myShapeReader ) 
300     delete myShapeReader;
301 }
302   
303 //=============================================================================
304 /*!
305  *  SMESH_Gen_i::createHypothesis
306  *
307  *  Create hypothesis of given type
308  */
309 //=============================================================================
310 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
311                                                           const char* theLibName)
312      throw (SALOME::SALOME_Exception)
313 {
314   /* It's Need to tranlate lib name for WIN32 or X platform */
315   char* aPlatformLibName = 0;
316   if ( theLibName && theLibName[0] != '\0'  )
317   {
318 #ifdef WNT
319     aPlatformLibName = new char[ strlen(theLibName) + 5 ];
320     aPlatformLibName[0] = '\0';
321     aPlatformLibName = strcat( aPlatformLibName, theLibName );
322     aPlatformLibName = strcat( aPlatformLibName, ".dll" );
323 #else
324     aPlatformLibName = new char[ strlen(theLibName) + 7 ];
325     aPlatformLibName[0] = '\0';
326     aPlatformLibName = strcat( aPlatformLibName, "lib" );
327     aPlatformLibName = strcat( aPlatformLibName, theLibName );
328     aPlatformLibName = strcat( aPlatformLibName, ".so" );
329 #endif
330   }
331   
332
333
334   Unexpect aCatch(SALOME_SalomeException);
335   if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName/*theLibName*/);
336
337   // create a new hypothesis object servant
338   SMESH_Hypothesis_i* myHypothesis_i = 0;
339   SMESH::SMESH_Hypothesis_var hypothesis_i;
340
341   try
342   {
343     // check, if creator for this hypothesis type already exists
344     if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
345     {
346       // load plugin library
347       if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
348       LibHandle libHandle = LoadLib( aPlatformLibName/*theLibName*/ );
349       if (!libHandle)
350       {
351         // report any error, if occured
352 #ifndef WNT
353         const char* anError = dlerror();
354         throw(SALOME_Exception(anError));
355 #else
356         throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
357 #endif
358       }
359
360       // get method, returning hypothesis creator
361       if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
362       typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* theHypName);
363       GetHypothesisCreator procHandle =
364         (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
365       if (!procHandle)
366       {
367         throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
368         UnLoadLib(libHandle);
369       }
370
371       // get hypothesis creator
372       if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
373       GenericHypothesisCreator_i* aCreator = procHandle(theHypName);
374       if (!aCreator)
375       {
376         throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
377       }
378
379       // map hypothesis creator to a hypothesis name
380       myHypCreatorMap[string(theHypName)] = aCreator;
381     }
382
383     // create a new hypothesis object, store its ref. in studyContext
384     if(MYDEBUG) MESSAGE("Create Hypothesis " << theHypName);
385     myHypothesis_i =
386       myHypCreatorMap[string(theHypName)]->Create (myPoa, GetCurrentStudyID(), &myGen);
387     myHypothesis_i->SetLibName(aPlatformLibName/*theLibName*/); // for persistency assurance
388   }
389   catch (SALOME_Exception& S_ex)
390   {
391     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
392   }
393
394   if ( aPlatformLibName )
395     delete[] aPlatformLibName;
396
397   if (!myHypothesis_i)
398     return hypothesis_i._retn();
399
400   // activate the CORBA servant of hypothesis
401   hypothesis_i = SMESH::SMESH_Hypothesis::_narrow( myHypothesis_i->_this() );
402   int nextId = RegisterObject( hypothesis_i );
403   if(MYDEBUG) MESSAGE( "Add hypo to map with id = "<< nextId );  
404
405   return hypothesis_i._retn();
406 }
407   
408 //=============================================================================
409 /*!
410  *  SMESH_Gen_i::createMesh
411  *
412  *  Create empty mesh on shape
413  */
414 //=============================================================================
415 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
416      throw ( SALOME::SALOME_Exception )
417 {
418   Unexpect aCatch(SALOME_SalomeException);
419   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
420
421   // Get or create the GEOM_Client instance
422   try {
423     // create a new mesh object servant, store it in a map in study context
424     SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
425     // create a new mesh object
426     meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
427
428     // activate the CORBA servant of Mesh
429     SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
430     int nextId = RegisterObject( mesh );
431     if(MYDEBUG) MESSAGE( "Add mesh to map with id = "<< nextId);
432     return mesh._retn();
433   }
434   catch (SALOME_Exception& S_ex) {
435     THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
436   }
437   return SMESH::SMESH_Mesh::_nil();
438 }
439
440 //=============================================================================
441 /*!
442  *  SMESH_Gen_i::GetShapeReader
443  *
444  *  Get shape reader
445  */
446 //=============================================================================
447 GEOM_Client* SMESH_Gen_i::GetShapeReader()
448 {
449   // create shape reader if necessary
450   if ( !myShapeReader ) 
451     myShapeReader = new GEOM_Client(GetContainerRef());
452   ASSERT( myShapeReader );
453   return myShapeReader;
454 }
455
456 //=============================================================================
457 /*!
458  *  SMESH_Gen_i::SetEmbeddedMode
459  *
460  *  Set current mode
461  */
462 //=============================================================================
463
464 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
465 {
466   myIsEmbeddedMode = theMode;
467
468   if ( !myIsEmbeddedMode ) {
469     bool raiseFPE;
470 #ifdef _DEBUG_
471     raiseFPE = true;
472     char* envDisableFPE = getenv("DISABLE_FPE");
473     if (envDisableFPE && atoi(envDisableFPE))
474       raiseFPE = false;
475 #else
476     raiseFPE = false;
477 #endif
478     OSD::SetSignal( raiseFPE );
479   }
480   // else OSD::SetSignal() is called in GUI
481 }
482
483 //=============================================================================
484 /*!
485  *  SMESH_Gen_i::IsEmbeddedMode
486  *
487  *  Get current mode
488  */
489 //=============================================================================
490
491 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
492 {
493   return myIsEmbeddedMode;
494 }
495
496 //=============================================================================
497 /*!
498  *  SMESH_Gen_i::SetCurrentStudy
499  *
500  *  Set current study
501  */
502 //=============================================================================
503
504 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
505 {
506   //if(MYDEBUG)
507   //MESSAGE( "SMESH_Gen_i::SetCurrentStudy" );
508   myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
509   // create study context, if it doesn't exist and set current study
510   int studyId = GetCurrentStudyID();
511   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SetCurrentStudy: study Id = " << studyId );
512   if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() ) {
513     myStudyContextMap[ studyId ] = new StudyContext;      
514   }
515
516   // myCurrentStudy may be nil
517   if ( !CORBA::is_nil( myCurrentStudy ) ) {
518     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder(); 
519     if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
520       aStudyBuilder->LoadWith( myCurrentStudy->FindComponent( "GEOM" ), GetGeomEngine() );
521
522   // set current study for geom engine
523   //if ( !CORBA::is_nil( GetGeomEngine() ) )
524   //  GetGeomEngine()->GetCurrentStudy( myCurrentStudy->StudyId() );
525   }
526 }
527
528 //=============================================================================
529 /*!
530  *  SMESH_Gen_i::GetCurrentStudy
531  *
532  *  Get current study
533  */
534 //=============================================================================
535
536 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
537 {
538   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
539   return SALOMEDS::Study::_duplicate( myCurrentStudy );
540 }
541
542 //=============================================================================
543 /*!
544  *  SMESH_Gen_i::GetCurrentStudyContext 
545  *
546  *  Get current study context
547  */
548 //=============================================================================
549 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
550 {
551   if ( !CORBA::is_nil( myCurrentStudy ) &&
552       myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
553     return myStudyContextMap[ myCurrentStudy->StudyId() ];
554   else
555     return 0;
556 }
557
558 //=============================================================================
559 /*!
560  *  SMESH_Gen_i::CreateHypothesis 
561  *
562  *  Create hypothesis/algorothm of given type and publish it in the study
563  */
564 //=============================================================================
565
566 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
567                                                            const char* theLibName )
568      throw ( SALOME::SALOME_Exception )
569 {
570   Unexpect aCatch(SALOME_SalomeException);
571   // Create hypothesis/algorithm
572   SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
573
574   // Publish hypothesis/algorithm in the study
575   if ( CanPublishInStudy( hyp ) ) {
576     SALOMEDS::SObject_var aSO = PublishHypothesis( myCurrentStudy, hyp );
577     if ( !aSO->_is_nil() ) {
578       // Update Python script
579       TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
580                     << theHypName << "', '" << theLibName << "')";
581     }
582   }
583
584   return hyp._retn();
585 }
586
587 //================================================================================
588 /*!
589  * \brief Return hypothesis of given type holding parameter values of the existing mesh
590   * \param theHypType - hypothesis type name
591   * \param theLibName - plugin library name
592   * \param theMesh - The mesh of interest
593   * \param theGeom - The shape to get parameter values from
594   * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
595   *    in a study and used to compute the mesh, or a temporary one created just to pass
596   *    parameter values
597  */
598 //================================================================================
599
600 SMESH::SMESH_Hypothesis_ptr
601 SMESH_Gen_i::GetHypothesisParameterValues (const char*           theHypType,
602                                            const char*           theLibName,
603                                            SMESH::SMESH_Mesh_ptr theMesh,
604                                            GEOM::GEOM_Object_ptr theGeom)
605     throw ( SALOME::SALOME_Exception )
606 {
607   Unexpect aCatch(SALOME_SalomeException);
608   if ( CORBA::is_nil( theMesh ) )
609     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
610   if ( CORBA::is_nil( theGeom ) )
611     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
612
613   // -----------------------------------------------
614   // find hypothesis used to mesh theGeom
615   // -----------------------------------------------
616
617   // get mesh and shape
618   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
619   TopoDS_Shape shape = GeomObjectToShape( theGeom );
620   if ( !meshServant || shape.IsNull() )
621     return SMESH::SMESH_Hypothesis::_nil();
622   ::SMESH_Mesh& mesh = meshServant->GetImpl();
623
624   if ( mesh.NbNodes() == 0 ) // empty mesh
625     return SMESH::SMESH_Hypothesis::_nil();
626
627   // create a temporary hypothesis to know its dimention
628   SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
629   SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
630   if ( !hypServant )
631     return SMESH::SMESH_Hypothesis::_nil();
632   ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
633
634   // look for a hypothesis of theHypType used to mesh the shape
635   if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
636   {
637     // check local shape
638     SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
639     int nbLocalHyps = aHypList->length();
640     for ( int i = 0; i < nbLocalHyps; i++ )
641       if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND local!
642         return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
643     // check super shapes
644     TopTools_ListIteratorOfListOfShape itShape( mesh.GetAncestors( shape ));
645     while ( nbLocalHyps == 0 && itShape.More() ) {
646       GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
647       if ( ! CORBA::is_nil( geomObj )) {
648         SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
649         nbLocalHyps = aHypList->length();
650         for ( int i = 0; i < nbLocalHyps; i++ )
651           if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
652             return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
653       }
654       itShape.Next();
655     }
656   }
657
658   // let the temporary hypothesis find out some how parameter values
659   if ( hyp->SetParametersByMesh( &mesh, shape ))
660     return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
661     
662   return SMESH::SMESH_Hypothesis::_nil();
663 }
664
665 //=============================================================================
666 /*!
667  *  SMESH_Gen_i::CreateMesh
668  *
669  *  Create empty mesh on a shape and publish it in the study
670  */
671 //=============================================================================
672
673 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
674      throw ( SALOME::SALOME_Exception )
675 {
676   Unexpect aCatch(SALOME_SalomeException);
677   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
678   // create mesh
679   SMESH::SMESH_Mesh_var mesh = this->createMesh();
680   // set shape
681   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
682   ASSERT( meshServant );
683   meshServant->SetShape( theShapeObject );
684
685   // publish mesh in the study
686   if ( CanPublishInStudy( mesh ) ) {
687     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
688     aStudyBuilder->NewCommand();  // There is a transaction
689     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
690     aStudyBuilder->CommitCommand();
691     if ( !aSO->_is_nil() ) {
692       // Update Python script
693       TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
694     }
695   }
696
697   return mesh._retn();
698 }
699
700 //=============================================================================
701 /*!
702  *  SMESH_Gen_i::CreateEmptyMesh
703  *
704  *  Create empty mesh
705  */
706 //=============================================================================
707
708 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
709      throw ( SALOME::SALOME_Exception )
710 {
711   Unexpect aCatch(SALOME_SalomeException);
712   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
713   // create mesh
714   SMESH::SMESH_Mesh_var mesh = this->createMesh();
715
716   // publish mesh in the study
717   if ( CanPublishInStudy( mesh ) ) {
718     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
719     aStudyBuilder->NewCommand();  // There is a transaction
720     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
721     aStudyBuilder->CommitCommand();
722     if ( !aSO->_is_nil() ) {
723       // Update Python script
724       TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
725     }
726   }
727
728   return mesh._retn();
729 }
730
731 //=============================================================================
732 /*!
733  *  SMESH_Gen_i::CreateMeshFromUNV
734  *
735  *  Create mesh and import data from UNV file
736  */
737 //=============================================================================
738
739 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
740   throw ( SALOME::SALOME_Exception )
741 {
742   Unexpect aCatch(SALOME_SalomeException);
743   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromUNV" );
744
745   SMESH::SMESH_Mesh_var aMesh = createMesh();
746   string aFileName;
747   // publish mesh in the study
748   if ( CanPublishInStudy( aMesh ) ) {
749     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
750     aStudyBuilder->NewCommand();  // There is a transaction
751     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
752     aStudyBuilder->CommitCommand();
753     if ( !aSO->_is_nil() ) {
754       // Update Python script
755       TPythonDump() << aSO << " = smeshgen.CreateMeshesFromUNV('" << theFileName << "')";
756     }
757   }
758
759   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
760   ASSERT( aServant );
761   aServant->ImportUNVFile( theFileName );
762
763   // Dump creation of groups
764   aServant->GetGroups();
765
766   return aMesh._retn();
767 }
768
769 //=============================================================================
770 /*!
771  *  SMESH_Gen_i::CreateMeshFromMED
772  *
773  *  Create mesh and import data from MED file
774  */
775 //=============================================================================
776
777 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
778                                                      SMESH::DriverMED_ReadStatus& theStatus)
779      throw ( SALOME::SALOME_Exception )
780 {
781   Unexpect aCatch(SALOME_SalomeException);
782   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshFromMED" );
783
784   // Retrieve mesh names from the file
785   DriverMED_R_SMESHDS_Mesh myReader;
786   myReader.SetFile( theFileName );
787   myReader.SetMeshId( -1 );
788   Driver_Mesh::Status aStatus;
789   list<string> aNames = myReader.GetMeshNames(aStatus);
790   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
791   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
792
793   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
794
795   // Python Dump
796   TPythonDump aPythonDump;
797   aPythonDump << "([";
798   //TCollection_AsciiString aStr ("([");
799
800   if (theStatus == SMESH::DRS_OK) {
801     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
802     aStudyBuilder->NewCommand();  // There is a transaction
803     aResult->length( aNames.size() );
804     int i = 0;
805     
806     // Iterate through all meshes and create mesh objects
807     for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ ) {
808       // Python Dump
809       //if (i > 0) aStr += ", ";
810       if (i > 0) aPythonDump << ", ";
811
812       // create mesh
813       SMESH::SMESH_Mesh_var mesh = createMesh();
814       
815       // publish mesh in the study
816       SALOMEDS::SObject_var aSO;
817       if ( CanPublishInStudy( mesh ) )
818         aSO = PublishMesh( myCurrentStudy, mesh.in(), (*it).c_str() );
819       if ( !aSO->_is_nil() ) {
820         // Python Dump
821         aPythonDump << aSO;
822         //aStr += aSO->GetID();
823       } else {
824         // Python Dump
825         aPythonDump << "mesh_" << i;
826 //         aStr += "mesh_";
827 //         aStr += TCollection_AsciiString(i);
828       }
829
830       // Read mesh data (groups are published automatically by ImportMEDFile())
831       SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
832       ASSERT( meshServant );
833       SMESH::DriverMED_ReadStatus status1 =
834         meshServant->ImportMEDFile( theFileName, (*it).c_str() );
835       if (status1 > theStatus)
836         theStatus = status1;
837
838       aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
839     }
840     aStudyBuilder->CommitCommand();
841   }
842
843   // Update Python script
844   aPythonDump << "], status) = " << this << ".CreateMeshesFromMED('" << theFileName << "')";
845   }
846   // Dump creation of groups
847   for ( int i = 0; i < aResult->length(); ++i )
848     aResult[ i ]->GetGroups();
849
850   return aResult._retn();
851 }
852
853 //=============================================================================
854 /*!
855  *  SMESH_Gen_i::CreateMeshFromSTL
856  *
857  *  Create mesh and import data from STL file
858  */
859 //=============================================================================
860
861 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
862   throw ( SALOME::SALOME_Exception )
863 {
864   Unexpect aCatch(SALOME_SalomeException);
865   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromSTL" );
866
867   SMESH::SMESH_Mesh_var aMesh = createMesh();
868   string aFileName;
869   // publish mesh in the study
870   if ( CanPublishInStudy( aMesh ) ) {
871     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
872     aStudyBuilder->NewCommand();  // There is a transaction
873     SALOMEDS::SObject_var aSO = PublishInStudy
874       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
875     aStudyBuilder->CommitCommand();
876     if ( !aSO->_is_nil() ) {
877       // Update Python script
878       TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL('" << theFileName << "')";
879     }
880   }
881
882   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
883   ASSERT( aServant );
884   aServant->ImportSTLFile( theFileName );
885   return aMesh._retn();
886 }
887
888 //=============================================================================
889 /*!
890  *  SMESH_Gen_i::IsReadyToCompute
891  *
892  *  Returns true if mesh contains enough data to be computed
893  */
894 //=============================================================================
895
896 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
897                                               GEOM::GEOM_Object_ptr theShapeObject )
898   throw ( SALOME::SALOME_Exception )
899 {
900   Unexpect aCatch(SALOME_SalomeException);
901   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
902
903   if ( CORBA::is_nil( theShapeObject ) )
904     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
905                                   SALOME::BAD_PARAM );
906
907   if ( CORBA::is_nil( theMesh ) )
908     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
909                                   SALOME::BAD_PARAM );
910
911   try {
912     // get mesh servant
913     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
914     ASSERT( meshServant );
915     if ( meshServant ) {
916       // get local TopoDS_Shape
917       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
918       // call implementation
919       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
920       return myGen.CheckAlgoState( myLocMesh, myLocShape );
921     }
922   }
923   catch ( SALOME_Exception& S_ex ) {
924     INFOS( "catch exception "<< S_ex.what() );
925   }
926   return false;
927 }
928
929 //================================================================================
930 /*!
931  * \brief Returns errors of hypotheses definintion
932   * \param theMesh - the mesh
933   * \param theSubObject - the main or sub- shape
934   * \retval SMESH::algo_error_array* - sequence of errors
935  */
936 //================================================================================
937
938 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh, 
939                                                     GEOM::GEOM_Object_ptr theSubObject )
940       throw ( SALOME::SALOME_Exception )
941 {
942   Unexpect aCatch(SALOME_SalomeException);
943   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
944
945   if ( CORBA::is_nil( theSubObject ) )
946     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
947
948   if ( CORBA::is_nil( theMesh ) )
949     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
950
951   SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
952   try {
953     SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
954     ASSERT( meshServant );
955     if ( meshServant ) {
956       TopoDS_Shape myLocShape = GeomObjectToShape( theSubObject );
957       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
958       list< ::SMESH_Gen::TAlgoStateError > error_list;
959       list< ::SMESH_Gen::TAlgoStateError >::iterator error;
960       // call ::SMESH_Gen::GetAlgoState()
961       myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
962       error_array->length( error_list.size() );
963       int i = 0;
964       for ( error = error_list.begin(); error != error_list.end(); ++error )
965       {
966         // error name
967         SMESH::AlgoStateErrorName errName;
968         switch ( error->_name ) {
969         case ::SMESH_Gen::MISSING_ALGO:     errName = SMESH::MISSING_ALGO; break;
970         case ::SMESH_Gen::MISSING_HYPO:     errName = SMESH::MISSING_HYPO; break;
971         case ::SMESH_Gen::NOT_CONFORM_MESH: errName = SMESH::NOT_CONFORM_MESH; break;
972         default:
973           THROW_SALOME_CORBA_EXCEPTION( "bad error name",SALOME::BAD_PARAM );
974         }
975         // algo name
976         CORBA::String_var algoName;
977         if ( error->_algo ) {
978           if ( !myCurrentStudy->_is_nil() ) {
979             // find algo in the study
980             SALOMEDS::SComponent_var father = SALOMEDS::SComponent::_narrow
981               ( myCurrentStudy->FindComponent( ComponentDataType() ) );
982             if ( !father->_is_nil() ) {
983               SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( father );
984               for ( ; itBig->More(); itBig->Next() ) {
985                 SALOMEDS::SObject_var gotBranch = itBig->Value();
986                 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
987                   SALOMEDS::ChildIterator_var algoIt = myCurrentStudy->NewChildIterator( gotBranch );
988                   for ( ; algoIt->More(); algoIt->Next() ) {
989                     SALOMEDS::SObject_var algoSO = algoIt->Value();
990                     CORBA::Object_var    algoIOR = SObjectToObject( algoSO );
991                     if ( !CORBA::is_nil( algoIOR )) {
992                       SMESH_Hypothesis_i* myImpl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
993                       if ( myImpl && myImpl->GetImpl() == error->_algo ) {
994                         algoName = algoSO->GetName();
995                         break;
996                       }
997                     }
998                   } // loop on algo SO's
999                   break;
1000                 } // if algo tag
1001               } // SMESH component iterator
1002             }
1003           }
1004           if ( algoName.in() == 0 )
1005             // use algo type name
1006             algoName = CORBA::string_dup( error->_algo->GetName() );
1007         }
1008         // fill AlgoStateError structure
1009         SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1010         errStruct.name         = errName;
1011         errStruct.algoName     = algoName;
1012         errStruct.algoDim      = error->_algoDim;
1013         errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1014       }
1015     }
1016   }
1017   catch ( SALOME_Exception& S_ex ) {
1018     INFOS( "catch exception "<< S_ex.what() );
1019   }
1020   return error_array._retn();
1021 }
1022
1023 //=============================================================================
1024 /*!
1025  *  SMESH_Gen_i::GetSubShapesId
1026  *
1027  *  Get sub-shapes unique ID's list
1028  */
1029 //=============================================================================
1030
1031 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1032                                             const SMESH::object_array& theListOfSubShapeObject )
1033      throw ( SALOME::SALOME_Exception )
1034 {
1035   Unexpect aCatch(SALOME_SalomeException);
1036   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1037
1038   SMESH::long_array_var shapesId = new SMESH::long_array;
1039   set<int> setId;
1040
1041   if ( CORBA::is_nil( theMainShapeObject ) )
1042     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1043                                   SALOME::BAD_PARAM );
1044
1045   try
1046     {
1047       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1048       TopTools_IndexedMapOfShape myIndexToShape;      
1049       TopExp::MapShapes(myMainShape,myIndexToShape);
1050
1051       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1052         {
1053           GEOM::GEOM_Object_var aShapeObject
1054             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1055           if ( CORBA::is_nil( aShapeObject ) )
1056             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1057                                         SALOME::BAD_PARAM );
1058
1059           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
1060           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1061             {
1062               const TopoDS_Face& F = TopoDS::Face(exp.Current());
1063               setId.insert(myIndexToShape.FindIndex(F));
1064               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1065             }
1066           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1067             {
1068               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1069               setId.insert(myIndexToShape.FindIndex(E));
1070               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1071             }
1072           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1073             {
1074               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1075               setId.insert(myIndexToShape.FindIndex(V));
1076               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1077             }
1078         }
1079       shapesId->length(setId.size());
1080       set<int>::iterator iind;
1081       int i=0;
1082       for (iind = setId.begin(); iind != setId.end(); iind++)
1083         {
1084           if(MYDEBUG) SCRUTE((*iind));
1085           shapesId[i] = (*iind);
1086           if(MYDEBUG) SCRUTE(shapesId[i]);
1087           i++;
1088         }
1089     }
1090   catch (SALOME_Exception& S_ex)
1091     {
1092       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1093     }
1094
1095   return shapesId._retn();
1096 }
1097
1098 //=============================================================================
1099 /*!
1100  *  SMESH_Gen_i::Compute
1101  *
1102  *  Compute mesh on a shape
1103  */
1104 //=============================================================================
1105
1106 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1107                                      GEOM::GEOM_Object_ptr theShapeObject )
1108      throw ( SALOME::SALOME_Exception )
1109 {
1110   Unexpect aCatch(SALOME_SalomeException);
1111   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1112
1113   if ( CORBA::is_nil( theShapeObject ) )
1114     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
1115                                   SALOME::BAD_PARAM );
1116
1117   if ( CORBA::is_nil( theMesh ) )
1118     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1119                                   SALOME::BAD_PARAM );
1120
1121   // Update Python script
1122   TPythonDump() << "isDone = " << this << ".Compute( "
1123                 << theMesh << ", " << theShapeObject << ")";
1124   TPythonDump() << "if not isDone: print 'Mesh " << theMesh << " : computation failed'";
1125
1126   try {
1127     // get mesh servant
1128     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1129     ASSERT( meshServant );
1130     if ( meshServant ) {
1131       // get local TopoDS_Shape
1132       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1133       // call implementation compute
1134       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1135       return myGen.Compute( myLocMesh, myLocShape);
1136     }
1137   }
1138   catch ( SALOME_Exception& S_ex ) {
1139     INFOS( "Compute(): catch exception "<< S_ex.what() );
1140   }
1141   catch ( ... ) {
1142     INFOS( "Compute(): unknown exception " );
1143   }
1144   return false;
1145 }
1146
1147 //================================================================================
1148 /*!
1149  * \brief Return geometrical object the given element is built on
1150  *  \param theMesh - the mesh the element is in
1151  *  \param theElementID - the element ID
1152  *  \param theGeomName - the name of the result geom object if it is not yet published
1153  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object
1154  */
1155 //================================================================================
1156
1157 GEOM::GEOM_Object_ptr
1158 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
1159                                        CORBA::Long            theElementID,
1160                                        const char*            theGeomName)
1161   throw ( SALOME::SALOME_Exception )
1162 {
1163   Unexpect aCatch(SALOME_SalomeException);
1164   if ( CORBA::is_nil( theMesh ) )
1165     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
1166
1167   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1168   GEOM::GEOM_Gen_var    geomGen   = GetGeomEngine();
1169
1170   // get a core mesh DS
1171   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1172   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
1173   {
1174     ::SMESH_Mesh & mesh = meshServant->GetImpl();
1175     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
1176     // find the element in mesh
1177     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) )
1178       // find a shape id by the element
1179       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
1180         // get a geom object by the shape id
1181         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
1182         if ( geom->_is_nil() ) {
1183           GEOM::GEOM_IShapesOperations_var op =
1184             geomGen->GetIShapesOperations( GetCurrentStudyID() );
1185           if ( !op->_is_nil() )
1186             geom = op->GetSubShape( mainShape, shapeID );
1187         }
1188         if ( !geom->_is_nil() ) {
1189           // try to find the corresponding SObject
1190           GeomObjectToShape( geom ); // geom client remembers the found shape
1191           SALOMEDS::SObject_var SObj = ObjectToSObject( myCurrentStudy, geom.in() );
1192           if ( SObj->_is_nil() )
1193             // publish a new subshape
1194             SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
1195           // return only published geometry
1196           if ( !SObj->_is_nil() )
1197             return geom._retn();
1198         }
1199       }
1200   }
1201   return GEOM::GEOM_Object::_nil();
1202 }
1203
1204 //=============================================================================
1205 /*!
1206  *  SMESH_Gen_i::Save
1207  *
1208  *  Save SMESH module's data
1209  */
1210 //=============================================================================
1211 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
1212                                       const char*              theURL,
1213                                       bool                     isMultiFile )
1214 {
1215   INFOS( "SMESH_Gen_i::Save" );
1216
1217 //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
1218   // san -- in case <myCurrentStudy> differs from theComponent's study,
1219   // use that of the component
1220   if ( myCurrentStudy->_is_nil() || 
1221        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
1222     SetCurrentStudy( theComponent->GetStudy() );
1223
1224   // Store study contents as a set of python commands
1225   SavePython(myCurrentStudy);
1226
1227   StudyContext* myStudyContext = GetCurrentStudyContext();
1228   
1229   // Declare a byte stream
1230   SALOMEDS::TMPFile_var aStreamFile;
1231   
1232   // Obtain a temporary dir
1233   TCollection_AsciiString tmpDir =
1234     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
1235
1236   // Create a sequence of files processed
1237   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
1238   aFileSeq->length( NUM_TMP_FILES );
1239
1240   TCollection_AsciiString aStudyName( "" );
1241   if ( isMultiFile ) 
1242     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
1243
1244   // Set names of temporary files
1245   TCollection_AsciiString filename =
1246     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
1247   TCollection_AsciiString meshfile =
1248     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
1249   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
1250   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
1251   filename = tmpDir + filename;
1252   meshfile = tmpDir + meshfile;
1253
1254   HDFfile*    aFile;
1255   HDFdataset* aDataset;
1256   HDFgroup*   aTopGroup;
1257   HDFgroup*   aGroup;
1258   HDFgroup*   aSubGroup;
1259   HDFgroup*   aSubSubGroup;
1260   hdf_size    aSize[ 1 ];
1261
1262
1263   //Remove the files if they exist: BugID: 11225
1264   TCollection_AsciiString cmd("rm -f \"");
1265   cmd+=filename;
1266   cmd+="\" \"";
1267   cmd+=meshfile;
1268   cmd+="\"";
1269   system(cmd.ToCString());
1270
1271   // MED writer to be used by storage process
1272   DriverMED_W_SMESHDS_Mesh myWriter;
1273   myWriter.SetFile( meshfile.ToCString() );
1274
1275   // Write data
1276   // ---> create HDF file
1277   aFile = new HDFfile( filename.ToCString() );
1278   aFile->CreateOnDisk();
1279
1280   // --> iterator for top-level objects
1281   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
1282   for ( ; itBig->More(); itBig->Next() ) {
1283     SALOMEDS::SObject_var gotBranch = itBig->Value();
1284
1285     // --> hypotheses root branch (only one for the study)
1286     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
1287       // create hypotheses root HDF group
1288       aTopGroup = new HDFgroup( "Hypotheses", aFile );
1289       aTopGroup->CreateOnDisk();
1290
1291       // iterator for all hypotheses
1292       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1293       for ( ; it->More(); it->Next() ) {
1294         SALOMEDS::SObject_var mySObject = it->Value();
1295         CORBA::Object_var anObject = SObjectToObject( mySObject );
1296         if ( !CORBA::is_nil( anObject ) ) {
1297           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1298           if ( !myHyp->_is_nil() ) {
1299             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1300             if ( myImpl ) {
1301               string hypname = string( myHyp->GetName() );
1302         string libname = string( myHyp->GetLibName() );
1303 // BUG SWP13062
1304 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
1305 // WNT and ".so" for X-system) must be deleted
1306               int libname_len = libname.length();
1307 #ifdef WNT
1308         if( libname_len > 4 )
1309           libname.resize( libname_len - 4 );
1310 #else
1311         if( libname_len > 3 )
1312           libname.resize( libname_len - 3 );
1313 #endif
1314         CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1315               int    id      = myStudyContext->findId( string( objStr.in() ) );
1316               string hypdata = string( myImpl->SaveTo() );
1317
1318               // for each hypothesis create HDF group basing on its id
1319               char hypGrpName[30];
1320               sprintf( hypGrpName, "Hypothesis %d", id );
1321               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1322               aGroup->CreateOnDisk();
1323               // --> type name of hypothesis
1324               aSize[ 0 ] = hypname.length() + 1;
1325               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1326               aDataset->CreateOnDisk();
1327               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1328               aDataset->CloseOnDisk();
1329               // --> server plugin library name of hypothesis
1330               aSize[ 0 ] = libname.length() + 1;
1331               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1332               aDataset->CreateOnDisk();
1333               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1334               aDataset->CloseOnDisk();
1335               // --> persistent data of hypothesis
1336               aSize[ 0 ] = hypdata.length() + 1;
1337               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1338               aDataset->CreateOnDisk();
1339               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1340               aDataset->CloseOnDisk();
1341               // close hypothesis HDF group
1342               aGroup->CloseOnDisk();
1343             }
1344           }
1345         }
1346       }
1347       // close hypotheses root HDF group
1348       aTopGroup->CloseOnDisk();
1349     }
1350     // --> algorithms root branch (only one for the study)
1351     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1352       // create algorithms root HDF group
1353       aTopGroup = new HDFgroup( "Algorithms", aFile );
1354       aTopGroup->CreateOnDisk();
1355
1356       // iterator for all algorithms
1357       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1358       for ( ; it->More(); it->Next() ) {
1359         SALOMEDS::SObject_var mySObject = it->Value();
1360         CORBA::Object_var anObject = SObjectToObject( mySObject );
1361         if ( !CORBA::is_nil( anObject ) ) {
1362           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1363           if ( !myHyp->_is_nil() ) {
1364             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1365             if ( myImpl ) {
1366               string hypname = string( myHyp->GetName() );
1367               string libname = string( myHyp->GetLibName() );
1368 // BUG SWP13062
1369 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
1370 // WNT and ".so" for X-system) must be deleted
1371               int libname_len = libname.length();
1372 #ifdef WNT
1373         if( libname_len > 4 )
1374           libname.resize( libname_len - 4 );
1375 #else
1376         if( libname_len > 3 )
1377           libname.resize( libname_len - 3 );
1378 #endif
1379         CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1380               int    id      = myStudyContext->findId( string( objStr.in() ) );
1381               string hypdata = string( myImpl->SaveTo() );
1382
1383               // for each algorithm create HDF group basing on its id
1384               char hypGrpName[30];
1385               sprintf( hypGrpName, "Algorithm %d", id );
1386               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1387               aGroup->CreateOnDisk();
1388               // --> type name of algorithm
1389               aSize[0] = hypname.length() + 1;
1390               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1391               aDataset->CreateOnDisk();
1392               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1393               aDataset->CloseOnDisk();
1394               // --> server plugin library name of hypothesis
1395               aSize[0] = libname.length() + 1;
1396               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1397               aDataset->CreateOnDisk();
1398               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1399               aDataset->CloseOnDisk();
1400               // --> persistent data of algorithm
1401               aSize[0] = hypdata.length() + 1;
1402               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1403               aDataset->CreateOnDisk();
1404               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1405               aDataset->CloseOnDisk();
1406               // close algorithm HDF group
1407               aGroup->CloseOnDisk();
1408             }
1409           }
1410         }
1411       }
1412       // close algorithms root HDF group
1413       aTopGroup->CloseOnDisk();
1414     }
1415     // --> mesh objects roots branches
1416     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
1417       CORBA::Object_var anObject = SObjectToObject( gotBranch );
1418       if ( !CORBA::is_nil( anObject ) ) {
1419         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
1420         if ( !myMesh->_is_nil() ) {
1421           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
1422           if ( myImpl ) {
1423       CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1424       int id = myStudyContext->findId( string( objStr.in() ) );
1425             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
1426             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
1427
1428             // for each mesh open the HDF group basing on its id
1429             char meshGrpName[ 30 ];
1430             sprintf( meshGrpName, "Mesh %d", id );
1431             aTopGroup = new HDFgroup( meshGrpName, aFile );
1432             aTopGroup->CreateOnDisk();
1433
1434             // --> put dataset to hdf file which is a flag that mesh has data
1435             string strHasData = "0";
1436             // check if the mesh is not empty
1437             if ( mySMESHDSMesh->NbNodes() > 0 ) {
1438               // write mesh data to med file
1439               myWriter.SetMesh( mySMESHDSMesh );
1440               myWriter.SetMeshId( id );
1441               strHasData = "1";
1442             }
1443             aSize[ 0 ] = strHasData.length() + 1;
1444             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
1445             aDataset->CreateOnDisk();
1446             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
1447             aDataset->CloseOnDisk();
1448             
1449             // write reference on a shape if exists
1450             SALOMEDS::SObject_var myRef;
1451             bool shapeRefFound = false;
1452             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
1453             if ( found ) {
1454               SALOMEDS::SObject_var myShape;
1455               bool ok = myRef->ReferencedObject( myShape );
1456               if ( ok ) {
1457                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
1458                 string myRefOnObject = myShape->GetID();
1459                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
1460                   aSize[ 0 ] = myRefOnObject.length() + 1;
1461                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
1462                   aDataset->CreateOnDisk();
1463                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1464                   aDataset->CloseOnDisk();
1465                 }
1466               }
1467             }
1468
1469             // write applied hypotheses if exist
1470             SALOMEDS::SObject_var myHypBranch;
1471             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
1472             if ( found && !shapeRefFound ) { // remove applied hyps
1473               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
1474             }
1475             if ( found && shapeRefFound ) {
1476               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
1477               aGroup->CreateOnDisk();
1478
1479               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
1480               int hypNb = 0;
1481               for ( ; it->More(); it->Next() ) {
1482                 SALOMEDS::SObject_var mySObject = it->Value();
1483                 SALOMEDS::SObject_var myRefOnHyp;
1484                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
1485                 if ( ok ) {
1486                   // san - it is impossible to recover applied hypotheses
1487                   //       using their entries within Load() method,
1488                   // for there are no AttributeIORs in the study when Load() is working. 
1489                   // Hence, it is better to store persistent IDs of hypotheses as references to them
1490
1491                   //string myRefOnObject = myRefOnHyp->GetID();
1492                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1493       CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1494       int id = myStudyContext->findId( string( objStr.in() ) );
1495                   //if ( myRefOnObject.length() > 0 ) {
1496                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1497                   char hypName[ 30 ], hypId[ 30 ];
1498                   sprintf( hypName, "Hyp %d", ++hypNb );
1499                   sprintf( hypId, "%d", id );
1500                   aSize[ 0 ] = strlen( hypId ) + 1;
1501                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
1502                   aDataset->CreateOnDisk();
1503                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1504                   aDataset->WriteOnDisk( hypId );
1505                   aDataset->CloseOnDisk();
1506                   //}
1507                 }
1508               }
1509               aGroup->CloseOnDisk();
1510             }
1511
1512             // write applied algorithms if exist
1513             SALOMEDS::SObject_var myAlgoBranch;
1514             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
1515             if ( found && !shapeRefFound ) { // remove applied algos
1516               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
1517             }
1518             if ( found && shapeRefFound ) {
1519               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
1520               aGroup->CreateOnDisk();
1521
1522               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
1523               int algoNb = 0;
1524               for ( ; it->More(); it->Next() ) {
1525                 SALOMEDS::SObject_var mySObject = it->Value();
1526                 SALOMEDS::SObject_var myRefOnAlgo;
1527                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
1528                 if ( ok ) {
1529                   // san - it is impossible to recover applied algorithms
1530                   //       using their entries within Load() method,
1531                   // for there are no AttributeIORs in the study when Load() is working. 
1532                   // Hence, it is better to store persistent IDs of algorithms as references to them
1533
1534                   //string myRefOnObject = myRefOnAlgo->GetID();
1535                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1536       CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1537       int id = myStudyContext->findId( string( objStr.in() ) );
1538                   //if ( myRefOnObject.length() > 0 ) {
1539                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1540                   char algoName[ 30 ], algoId[ 30 ];
1541                   sprintf( algoName, "Algo %d", ++algoNb );
1542                   sprintf( algoId, "%d", id );
1543                   aSize[ 0 ] = strlen( algoId ) + 1;
1544                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
1545                   aDataset->CreateOnDisk();
1546                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1547                   aDataset->WriteOnDisk( algoId );
1548                   aDataset->CloseOnDisk();
1549                   //}
1550                 }
1551               }
1552               aGroup->CloseOnDisk();
1553             }
1554
1555             // --> submesh objects sub-branches
1556
1557             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
1558               SALOMEDS::SObject_var mySubmeshBranch;
1559               found = gotBranch->FindSubObject( i, mySubmeshBranch );
1560
1561               if ( found ) // check if there is shape reference in submeshes
1562               {
1563                 bool hasShapeRef = false;
1564                 SALOMEDS::ChildIterator_var itSM =
1565                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
1566                 for ( ; itSM->More(); itSM->Next() ) {
1567                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
1568                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1569                     mySubRef->ReferencedObject( myShape );
1570                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
1571                     hasShapeRef = true;
1572                   else
1573                   { // remove one submesh
1574                     if ( shapeRefFound )
1575                     { // unassign hypothesis
1576                       SMESH::SMESH_subMesh_var mySubMesh =
1577                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
1578                       if ( !mySubMesh->_is_nil() ) {
1579                         int shapeID = mySubMesh->GetId();
1580                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
1581                         const list<const SMESHDS_Hypothesis*>& hypList =
1582                           mySMESHDSMesh->GetHypothesis( S );
1583                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
1584                         while ( hyp != hypList.end() ) {
1585                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
1586                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
1587                         }
1588                       }
1589                     }
1590                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
1591                   }
1592                 } // loop on submeshes of a type
1593                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
1594                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
1595                   found = false;
1596                 }
1597               }  // end check if there is shape reference in submeshes
1598               if ( found ) {
1599                 char name_meshgroup[ 30 ];
1600                 if ( i == GetSubMeshOnVertexTag() )
1601                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
1602                 else if ( i == GetSubMeshOnEdgeTag() )
1603                   strcpy( name_meshgroup, "SubMeshes On Edge" );
1604                 else if ( i == GetSubMeshOnWireTag() )
1605                   strcpy( name_meshgroup, "SubMeshes On Wire" );
1606                 else if ( i == GetSubMeshOnFaceTag() )
1607                   strcpy( name_meshgroup, "SubMeshes On Face" );
1608                 else if ( i == GetSubMeshOnShellTag() )
1609                   strcpy( name_meshgroup, "SubMeshes On Shell" );
1610                 else if ( i == GetSubMeshOnSolidTag() )
1611                   strcpy( name_meshgroup, "SubMeshes On Solid" );
1612                 else if ( i == GetSubMeshOnCompoundTag() )
1613                   strcpy( name_meshgroup, "SubMeshes On Compound" );
1614                 
1615                 // for each type of submeshes create container HDF group
1616                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
1617                 aGroup->CreateOnDisk();
1618             
1619                 // iterator for all submeshes of given type
1620                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
1621                 for ( ; itSM->More(); itSM->Next() ) {
1622                   SALOMEDS::SObject_var mySObject = itSM->Value();
1623                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
1624                   if ( !CORBA::is_nil( anSubObject ))
1625                   {
1626                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
1627         CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
1628         int subid = myStudyContext->findId( string( objStr.in() ) );
1629                       
1630                     // for each mesh open the HDF group basing on its id
1631                     char submeshGrpName[ 30 ];
1632                     sprintf( submeshGrpName, "SubMesh %d", subid );
1633                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
1634                     aSubGroup->CreateOnDisk();
1635
1636                     // write reference on a shape, already checked if it exists
1637                     SALOMEDS::SObject_var mySubRef, myShape;
1638                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1639                       mySubRef->ReferencedObject( myShape );
1640                     string myRefOnObject = myShape->GetID();
1641                     if ( myRefOnObject.length() > 0 ) {
1642                       aSize[ 0 ] = myRefOnObject.length() + 1;
1643                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
1644                       aDataset->CreateOnDisk();
1645                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1646                       aDataset->CloseOnDisk();
1647                     }
1648
1649                     // write applied hypotheses if exist
1650                     SALOMEDS::SObject_var mySubHypBranch;
1651                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
1652                     if ( found ) {
1653                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
1654                       aSubSubGroup->CreateOnDisk();
1655
1656                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
1657                       int hypNb = 0;
1658                       for ( ; it->More(); it->Next() ) {
1659                         SALOMEDS::SObject_var mySubSObject = it->Value();
1660                         SALOMEDS::SObject_var myRefOnHyp;
1661                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
1662                         if ( ok ) {
1663                           //string myRefOnObject = myRefOnHyp->GetID();
1664                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1665         CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1666         int id = myStudyContext->findId( string( objStr.in() ) );
1667                           //if ( myRefOnObject.length() > 0 ) {
1668                           //aSize[ 0 ] = myRefOnObject.length() + 1;
1669                           char hypName[ 30 ], hypId[ 30 ];
1670                           sprintf( hypName, "Hyp %d", ++hypNb );
1671                           sprintf( hypId, "%d", id );
1672                           aSize[ 0 ] = strlen( hypId ) + 1;
1673                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
1674                           aDataset->CreateOnDisk();
1675                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1676                           aDataset->WriteOnDisk( hypId );
1677                           aDataset->CloseOnDisk();
1678                           //}
1679                         }
1680                       }
1681                       aSubSubGroup->CloseOnDisk();
1682                     }
1683                     
1684                     // write applied algorithms if exist
1685                     SALOMEDS::SObject_var mySubAlgoBranch;
1686                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
1687                     if ( found ) {
1688                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
1689                       aSubSubGroup->CreateOnDisk();
1690
1691                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
1692                       int algoNb = 0;
1693                       for ( ; it->More(); it->Next() ) {
1694                         SALOMEDS::SObject_var mySubSObject = it->Value();
1695                         SALOMEDS::SObject_var myRefOnAlgo;
1696                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
1697                         if ( ok ) {
1698                           //string myRefOnObject = myRefOnAlgo->GetID();
1699                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1700         CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1701         int id = myStudyContext->findId( string( objStr.in() ) );
1702                           //if ( myRefOnObject.length() > 0 ) {
1703                           //aSize[ 0 ] = myRefOnObject.length() + 1;
1704                           char algoName[ 30 ], algoId[ 30 ];
1705                           sprintf( algoName, "Algo %d", ++algoNb );
1706                           sprintf( algoId, "%d", id );
1707                           aSize[ 0 ] = strlen( algoId ) + 1;
1708                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
1709                           aDataset->CreateOnDisk();
1710                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1711                           aDataset->WriteOnDisk( algoId );
1712                           aDataset->CloseOnDisk();
1713                           //}
1714                         }
1715                       }
1716                       aSubSubGroup->CloseOnDisk();
1717                     }
1718                     // close submesh HDF group
1719                     aSubGroup->CloseOnDisk();
1720                   }
1721                 }
1722                 // close container of submeshes by type HDF group
1723                 aGroup->CloseOnDisk();
1724               }
1725             }
1726             // All sub-meshes will be stored in MED file
1727             if ( shapeRefFound )
1728               myWriter.AddAllSubMeshes();
1729
1730             // groups root sub-branch
1731             SALOMEDS::SObject_var myGroupsBranch;
1732             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
1733               found = gotBranch->FindSubObject( i, myGroupsBranch );
1734               if ( found ) {
1735                 char name_group[ 30 ];
1736                 if ( i == GetNodeGroupsTag() )
1737                   strcpy( name_group, "Groups of Nodes" );
1738                 else if ( i == GetEdgeGroupsTag() )
1739                   strcpy( name_group, "Groups of Edges" );
1740                 else if ( i == GetFaceGroupsTag() )
1741                   strcpy( name_group, "Groups of Faces" );
1742                 else if ( i == GetVolumeGroupsTag() )
1743                   strcpy( name_group, "Groups of Volumes" );
1744
1745                 aGroup = new HDFgroup( name_group, aTopGroup );
1746                 aGroup->CreateOnDisk();
1747
1748                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
1749                 for ( ; it->More(); it->Next() ) {
1750                   SALOMEDS::SObject_var mySObject = it->Value();
1751                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
1752                   if ( !CORBA::is_nil( aSubObject ) ) {
1753                     SMESH_GroupBase_i* myGroupImpl =
1754                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
1755                     if ( !myGroupImpl )
1756                       continue;
1757
1758         CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
1759         int anId = myStudyContext->findId( string( objStr.in() ) );
1760                     
1761                     // For each group, create a dataset named "Group <group_persistent_id>"
1762                     // and store the group's user name into it
1763                     char grpName[ 30 ];
1764                     sprintf( grpName, "Group %d", anId );
1765                     char* aUserName = myGroupImpl->GetName();
1766                     aSize[ 0 ] = strlen( aUserName ) + 1;
1767
1768                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
1769                     aDataset->CreateOnDisk();
1770                     aDataset->WriteOnDisk( aUserName );
1771                     aDataset->CloseOnDisk();
1772
1773                     // Store the group contents into MED file
1774                     if ( myLocMesh.GetGroup( myGroupImpl->GetLocalID() ) ) {
1775
1776                       if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen_i::Save(): saving group with StoreName = "
1777                               << grpName << " to MED file" );
1778                       SMESHDS_GroupBase* aGrpBaseDS =
1779                         myLocMesh.GetGroup( myGroupImpl->GetLocalID() )->GetGroupDS();
1780                       aGrpBaseDS->SetStoreName( grpName );
1781
1782                       // Pass SMESHDS_Group to MED writer 
1783                       SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
1784                       if ( aGrpDS )
1785                         myWriter.AddGroup( aGrpDS );
1786
1787                       // write reference on a shape if exists
1788                       SMESHDS_GroupOnGeom* aGeomGrp =
1789                         dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
1790                       if ( aGeomGrp ) {
1791                         SALOMEDS::SObject_var mySubRef, myShape;
1792                         if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
1793                             mySubRef->ReferencedObject( myShape ) &&
1794                             !CORBA::is_nil( myShape->GetObject() ))
1795                         {
1796                           string myRefOnObject = myShape->GetID();
1797                           if ( myRefOnObject.length() > 0 ) {
1798                             char aRefName[ 30 ];
1799                             sprintf( aRefName, "Ref on shape %d", anId);
1800                             aSize[ 0 ] = myRefOnObject.length() + 1;
1801                             aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
1802                             aDataset->CreateOnDisk();
1803                             aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1804                             aDataset->CloseOnDisk();
1805                           }
1806                         }
1807                         else // shape ref is invalid:
1808                         {
1809                           // save a group on geometry as ordinary group
1810                           myWriter.AddGroup( aGeomGrp );
1811                         }
1812                       }
1813                     }
1814                   }
1815                 }
1816                 aGroup->CloseOnDisk();
1817               }
1818             } // loop on groups 
1819
1820             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
1821             {
1822               // Flush current mesh information into MED file
1823               myWriter.Perform();
1824
1825               // maybe a shape was deleted in the study
1826               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() ) {
1827                 TopoDS_Shape nullShape;
1828                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
1829               }
1830
1831               // Store node positions on sub-shapes (SMDS_Position):
1832
1833               if ( !mySMESHDSMesh->SubMeshes().empty() )
1834               {
1835                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
1836                 aGroup->CreateOnDisk();
1837
1838                 // in aGroup, create 5 datasets to contain:
1839                 // "Nodes on Edges" - ID of node on edge
1840                 // "Edge positions" - U parameter on node on edge
1841                 // "Nodes on Faces" - ID of node on face
1842                 // "Face U positions" - U parameter of node on face
1843                 // "Face V positions" - V parameter of node on face
1844
1845                 // Find out nb of nodes on edges and faces
1846                 // Collect corresponing sub-meshes
1847                 int nbEdgeNodes = 0, nbFaceNodes = 0;
1848                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
1849                 // loop on SMESHDS_SubMesh'es
1850                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
1851                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
1852                 for ( ; itSubM != aSubMeshes.end() ; itSubM++ )
1853                 {
1854                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
1855                   if ( aSubMesh->IsComplexSubmesh() )
1856                     continue; // submesh containing other submeshs
1857                   int nbNodes = aSubMesh->NbNodes();
1858                   if ( nbNodes == 0 ) continue;
1859
1860                   int aShapeID = (*itSubM).first;
1861                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
1862                   // write only SMDS_FacePosition and SMDS_EdgePosition
1863                   switch ( aShapeType ) {
1864                   case TopAbs_FACE:
1865                     nbFaceNodes += nbNodes;
1866                     aFaceSM.push_back( aSubMesh );
1867                     break;
1868                   case TopAbs_EDGE:
1869                     nbEdgeNodes += nbNodes;
1870                     aEdgeSM.push_back( aSubMesh );
1871                     break;
1872                   default:
1873                     continue;
1874                   }
1875                 }
1876                 // Treat positions on edges or faces
1877                 for ( int onFace = 0; onFace < 2; onFace++ )
1878                 {
1879                   // Create arrays to store in datasets
1880                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
1881                   if (!nbNodes) continue;
1882                   int* aNodeIDs = new int [ nbNodes ];
1883                   double* aUPos = new double [ nbNodes ];
1884                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
1885
1886                   // Fill arrays
1887                   // loop on sub-meshes
1888                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
1889                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
1890                   for ( ; itSM != pListSM->end(); itSM++ )
1891                   {
1892                     SMESHDS_SubMesh* aSubMesh = (*itSM);
1893                     if ( aSubMesh->IsComplexSubmesh() )
1894                       continue; // submesh containing other submeshs
1895
1896                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
1897                     // loop on nodes in aSubMesh
1898                     while ( itNode->more() )
1899                     {
1900                       //node ID
1901                       const SMDS_MeshNode* node = itNode->next();
1902                       aNodeIDs [ iNode ] = node->GetID();
1903
1904                       // Position
1905                       const SMDS_PositionPtr pos = node->GetPosition();
1906                       if ( onFace ) { // on FACE
1907                         const SMDS_FacePosition* fPos =
1908                           dynamic_cast<const SMDS_FacePosition*>( pos.get() );
1909                         if ( fPos ) {
1910                           aUPos[ iNode ] = fPos->GetUParameter();
1911                           aVPos[ iNode ] = fPos->GetVParameter();
1912                           iNode++;
1913                         }
1914                         else
1915                           nbNodes--;
1916                       }
1917                       else { // on EDGE
1918                         const SMDS_EdgePosition* ePos =
1919                           dynamic_cast<const SMDS_EdgePosition*>( pos.get() );
1920                         if ( ePos ) {
1921                           aUPos[ iNode ] = ePos->GetUParameter();
1922                           iNode++;
1923                         }
1924                         else
1925                           nbNodes--;
1926                       }
1927                     } // loop on nodes in aSubMesh
1928                   } // loop on sub-meshes
1929
1930                   // Write datasets
1931                   if ( nbNodes )
1932                   {
1933                     aSize[ 0 ] = nbNodes;
1934                     // IDS
1935                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
1936                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
1937                     aDataset->CreateOnDisk();
1938                     aDataset->WriteOnDisk( aNodeIDs );
1939                     aDataset->CloseOnDisk();
1940
1941                     // U Positions
1942                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
1943                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
1944                     aDataset->CreateOnDisk();
1945                     aDataset->WriteOnDisk( aUPos );
1946                     aDataset->CloseOnDisk();
1947                     // V Positions
1948                     if ( onFace ) {
1949                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
1950                       aDataset->CreateOnDisk();
1951                       aDataset->WriteOnDisk( aVPos );
1952                       aDataset->CloseOnDisk();
1953                     }
1954                   }
1955                   delete [] aNodeIDs;
1956                   delete [] aUPos;
1957                   if ( aVPos ) delete [] aVPos;
1958
1959                 } // treat positions on edges or faces
1960
1961                 // close "Node Positions" group
1962                 aGroup->CloseOnDisk(); 
1963
1964               } // if ( there are submeshes in SMESHDS_Mesh )
1965             } // if ( hasData )
1966
1967             // close mesh HDF group
1968             aTopGroup->CloseOnDisk();
1969           }
1970         }
1971       }
1972     }
1973   }
1974
1975   // close HDF file
1976   aFile->CloseOnDisk();
1977   delete aFile;
1978
1979   // Convert temporary files to stream
1980   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
1981
1982   // Remove temporary files and directory
1983   if ( !isMultiFile ) 
1984     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
1985
1986   INFOS( "SMESH_Gen_i::Save() completed" );
1987   return aStreamFile._retn();
1988 }
1989
1990 //=============================================================================
1991 /*!
1992  *  SMESH_Gen_i::SaveASCII
1993  *
1994  *  Save SMESH module's data in ASCII format (not implemented yet)
1995  */
1996 //=============================================================================
1997
1998 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
1999                                            const char*              theURL,
2000                                            bool                     isMultiFile ) {
2001   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
2002   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
2003   return aStreamFile._retn();
2004 }
2005
2006 //=============================================================================
2007 /*!
2008  *  SMESH_Gen_i::loadGeomData
2009  *
2010  *  Load GEOM module data
2011  */
2012 //=============================================================================
2013
2014 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
2015 {
2016   if ( theCompRoot->_is_nil() )
2017     return;
2018
2019   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
2020   if ( aStudy->_is_nil() )
2021     return;
2022
2023   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
2024   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
2025 }
2026
2027 //=============================================================================
2028 /*!
2029  *  SMESH_Gen_i::Load
2030  *
2031  *  Load SMESH module's data
2032  */
2033 //=============================================================================
2034
2035 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
2036                         const SALOMEDS::TMPFile& theStream,
2037                         const char*              theURL,
2038                         bool                     isMultiFile )
2039 {
2040   INFOS( "SMESH_Gen_i::Load" );
2041
2042   if ( myCurrentStudy->_is_nil() || 
2043        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2044     SetCurrentStudy( theComponent->GetStudy() );
2045
2046 /*  if( !theComponent->_is_nil() )
2047   {
2048     //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
2049     if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
2050       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
2051   }*/
2052
2053   StudyContext* myStudyContext = GetCurrentStudyContext();
2054   
2055   // Get temporary files location
2056   TCollection_AsciiString tmpDir =
2057     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2058
2059   // Convert the stream into sequence of files to process
2060   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
2061                                                                             tmpDir.ToCString(),
2062                                                                             isMultiFile );
2063   TCollection_AsciiString aStudyName( "" );
2064   if ( isMultiFile ) 
2065     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2066
2067   // Set names of temporary files
2068   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
2069   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
2070
2071   int size;
2072   HDFfile*    aFile;
2073   HDFdataset* aDataset;
2074   HDFgroup*   aTopGroup;
2075   HDFgroup*   aGroup;
2076   HDFgroup*   aSubGroup;
2077   HDFgroup*   aSubSubGroup;
2078
2079   // Read data
2080   // ---> open HDF file
2081   aFile = new HDFfile( filename.ToCString() );
2082   try {
2083     aFile->OpenOnDisk( HDF_RDONLY );
2084   }
2085   catch ( HDFexception ) {
2086     INFOS( "Load(): " << filename << " not found!" );
2087     return false;
2088   }
2089
2090   DriverMED_R_SMESHDS_Mesh myReader;
2091   myReader.SetFile( meshfile.ToCString() );
2092
2093   // get total number of top-level groups
2094   int aNbGroups = aFile->nInternalObjects(); 
2095   if ( aNbGroups > 0 ) {
2096     // --> in first turn we should read&create hypotheses
2097     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
2098       // open hypotheses root HDF group
2099       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
2100       aTopGroup->OpenOnDisk();
2101
2102       // get number of hypotheses
2103       int aNbObjects = aTopGroup->nInternalObjects(); 
2104       for ( int j = 0; j < aNbObjects; j++ ) {
2105         // try to identify hypothesis
2106         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2107         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2108
2109         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
2110           // open hypothesis group
2111           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2112           aGroup->OpenOnDisk();
2113
2114           // --> get hypothesis id
2115           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
2116           string hypname;
2117           string libname;
2118           string hypdata;
2119
2120           // get number of datasets
2121           int aNbSubObjects = aGroup->nInternalObjects();
2122           for ( int k = 0; k < aNbSubObjects; k++ ) {
2123             // identify dataset
2124             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2125             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2126             // --> get hypothesis name
2127             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2128               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2129               aDataset->OpenOnDisk();
2130               size = aDataset->GetSize();
2131               char* hypname_str = new char[ size ];
2132               aDataset->ReadFromDisk( hypname_str );
2133               hypname = string( hypname_str );
2134               delete [] hypname_str;
2135               aDataset->CloseOnDisk();
2136             }
2137             // --> get hypothesis plugin library name
2138             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2139               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2140               aDataset->OpenOnDisk();
2141               size = aDataset->GetSize();
2142               char* libname_str = new char[ size ];
2143               aDataset->ReadFromDisk( libname_str );
2144               if(MYDEBUG) SCRUTE( libname_str );
2145               libname = string( libname_str );
2146               delete [] libname_str;
2147               aDataset->CloseOnDisk();
2148             }
2149             // --> get hypothesis data
2150             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2151               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2152               aDataset->OpenOnDisk();
2153               size = aDataset->GetSize();
2154               char* hypdata_str = new char[ size ];
2155               aDataset->ReadFromDisk( hypdata_str );
2156               hypdata = string( hypdata_str );
2157               delete [] hypdata_str;
2158               aDataset->CloseOnDisk();
2159             }
2160           }
2161           // close hypothesis HDF group
2162           aGroup->CloseOnDisk();
2163
2164           // --> restore hypothesis from data
2165           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2166             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
2167                     ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2168             SMESH::SMESH_Hypothesis_var myHyp;
2169             
2170             try { // protect persistence mechanism against exceptions
2171               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2172             }
2173             catch (...) {
2174               INFOS( "Exception during hypothesis creation" );
2175             }
2176
2177             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2178             if ( myImpl ) {
2179               myImpl->LoadFrom( hypdata.c_str() );
2180         CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
2181               int newId = myStudyContext->findId( string( iorString.in() ) );
2182               myStudyContext->mapOldToNew( id, newId );
2183             }
2184             else
2185               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2186           }
2187         }
2188       }
2189       // close hypotheses root HDF group
2190       aTopGroup->CloseOnDisk();
2191     }
2192
2193     // --> then we should read&create algorithms
2194     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
2195       // open algorithms root HDF group
2196       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
2197       aTopGroup->OpenOnDisk();
2198
2199       // get number of algorithms
2200       int aNbObjects = aTopGroup->nInternalObjects(); 
2201       for ( int j = 0; j < aNbObjects; j++ ) {
2202         // try to identify algorithm
2203         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2204         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2205
2206         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
2207           // open algorithm group
2208           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2209           aGroup->OpenOnDisk();
2210
2211           // --> get algorithm id
2212           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
2213           string hypname;
2214           string libname;
2215           string hypdata;
2216
2217           // get number of datasets
2218           int aNbSubObjects = aGroup->nInternalObjects();
2219           for ( int k = 0; k < aNbSubObjects; k++ ) {
2220             // identify dataset
2221             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2222             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2223             // --> get algorithm name
2224             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2225               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2226               aDataset->OpenOnDisk();
2227               size = aDataset->GetSize();
2228               char* hypname_str = new char[ size ];
2229               aDataset->ReadFromDisk( hypname_str );
2230               hypname = string( hypname_str );
2231               delete [] hypname_str;
2232               aDataset->CloseOnDisk();
2233             }
2234             // --> get algorithm plugin library name
2235             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2236               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2237               aDataset->OpenOnDisk();
2238               size = aDataset->GetSize();
2239               char* libname_str = new char[ size ];
2240               aDataset->ReadFromDisk( libname_str );
2241               if(MYDEBUG) SCRUTE( libname_str );
2242               libname = string( libname_str );
2243               delete [] libname_str;
2244               aDataset->CloseOnDisk();
2245             }
2246             // --> get algorithm data
2247             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2248               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2249               aDataset->OpenOnDisk();
2250               size = aDataset->GetSize();
2251               char* hypdata_str = new char[ size ];
2252               aDataset->ReadFromDisk( hypdata_str );
2253               if(MYDEBUG) SCRUTE( hypdata_str );
2254               hypdata = string( hypdata_str );
2255               delete [] hypdata_str;
2256               aDataset->CloseOnDisk();
2257             }
2258           }
2259           // close algorithm HDF group
2260           aGroup->CloseOnDisk();
2261           
2262           // --> restore algorithm from data
2263           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2264             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
2265                     ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2266             SMESH::SMESH_Hypothesis_var myHyp;
2267                     
2268             try { // protect persistence mechanism against exceptions
2269               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2270             }
2271             catch (...) {
2272               INFOS( "Exception during hypothesis creation" );
2273             }
2274             
2275             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2276             if ( myImpl ) {
2277               myImpl->LoadFrom( hypdata.c_str() );
2278         CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
2279               int newId = myStudyContext->findId( string( iorString.in() ) );
2280               myStudyContext->mapOldToNew( id, newId );
2281             }
2282             else
2283               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2284           }
2285         }
2286       }
2287       // close algorithms root HDF group
2288       aTopGroup->CloseOnDisk();
2289     }
2290
2291     // --> the rest groups should be meshes
2292     for ( int i = 0; i < aNbGroups; i++ ) {
2293       // identify next group
2294       char meshName[ HDF_NAME_MAX_LEN+1 ];
2295       aFile->InternalObjectIndentify( i, meshName );
2296
2297       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
2298         // --> get mesh id
2299         int id = atoi( string( meshName ).substr( 4 ).c_str() );
2300         if ( id <= 0 )
2301           continue;
2302
2303         bool hasData = false;
2304
2305         // open mesh HDF group
2306         aTopGroup = new HDFgroup( meshName, aFile ); 
2307         aTopGroup->OpenOnDisk();
2308
2309         // get number of child HDF objects
2310         int aNbObjects = aTopGroup->nInternalObjects(); 
2311         if ( aNbObjects > 0 ) {
2312           // create mesh
2313           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
2314           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
2315           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
2316           if ( !myNewMeshImpl )
2317             continue;
2318           CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
2319           int newId = myStudyContext->findId( string( iorString.in() ) );
2320           myStudyContext->mapOldToNew( id, newId );
2321           
2322           ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
2323           SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2324
2325           // try to find mesh data dataset
2326           if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
2327             // load mesh "has data" flag
2328             aDataset = new HDFdataset( "Has data", aTopGroup );
2329             aDataset->OpenOnDisk();
2330             size = aDataset->GetSize();
2331             char* strHasData = new char[ size ];
2332             aDataset->ReadFromDisk( strHasData );
2333             aDataset->CloseOnDisk();
2334             if ( strcmp( strHasData, "1") == 0 ) {
2335               // read mesh data from MED file
2336               myReader.SetMesh( mySMESHDSMesh );
2337               myReader.SetMeshId( id );
2338               myReader.Perform();
2339               hasData = true;
2340             }
2341           }
2342
2343           // try to read and set reference to shape
2344           GEOM::GEOM_Object_var aShapeObject;
2345           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
2346             // load mesh "Ref on shape" - it's an entry to SObject
2347             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
2348             aDataset->OpenOnDisk();
2349             size = aDataset->GetSize();
2350             char* refFromFile = new char[ size ];
2351             aDataset->ReadFromDisk( refFromFile );
2352             aDataset->CloseOnDisk();
2353             if ( strlen( refFromFile ) > 0 ) {
2354               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
2355
2356               // Make sure GEOM data are loaded first
2357               //loadGeomData( shapeSO->GetFatherComponent() );
2358
2359               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
2360               if ( !CORBA::is_nil( shapeObject ) ) {
2361                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
2362                 if ( !aShapeObject->_is_nil() )
2363                   myNewMeshImpl->SetShape( aShapeObject );
2364               }
2365             }
2366           }
2367
2368           // try to get applied algorithms
2369           if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
2370             aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
2371             aGroup->OpenOnDisk();
2372             // get number of applied algorithms
2373             int aNbSubObjects = aGroup->nInternalObjects(); 
2374             if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
2375             for ( int j = 0; j < aNbSubObjects; j++ ) {
2376               char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2377               aGroup->InternalObjectIndentify( j, name_dataset );
2378               // check if it is an algorithm
2379               if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
2380                 aDataset = new HDFdataset( name_dataset, aGroup );
2381                 aDataset->OpenOnDisk();
2382                 size = aDataset->GetSize();
2383                 char* refFromFile = new char[ size ];
2384                 aDataset->ReadFromDisk( refFromFile );
2385                 aDataset->CloseOnDisk();
2386
2387                 // san - it is impossible to recover applied algorithms using their entries within Load() method
2388                 
2389                 //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2390                 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2391                 int id = atoi( refFromFile );
2392                 string anIOR = myStudyContext->getIORbyOldId( id );
2393                 if ( !anIOR.empty() ) {
2394                   CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2395                   if ( !CORBA::is_nil( hypObject ) ) {
2396                     SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2397                     if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2398                       myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2399                   }
2400                 }
2401               }
2402             }
2403             aGroup->CloseOnDisk();
2404           }
2405
2406           // try to get applied hypotheses
2407           if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2408             aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2409             aGroup->OpenOnDisk();
2410             // get number of applied hypotheses
2411             int aNbSubObjects = aGroup->nInternalObjects(); 
2412             for ( int j = 0; j < aNbSubObjects; j++ ) {
2413               char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2414               aGroup->InternalObjectIndentify( j, name_dataset );
2415               // check if it is a hypothesis
2416               if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2417                 aDataset = new HDFdataset( name_dataset, aGroup );
2418                 aDataset->OpenOnDisk();
2419                 size = aDataset->GetSize();
2420                 char* refFromFile = new char[ size ];
2421                 aDataset->ReadFromDisk( refFromFile );
2422                 aDataset->CloseOnDisk();
2423
2424                 // san - it is impossible to recover applied hypotheses using their entries within Load() method
2425                 
2426                 //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2427                 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2428                 int id = atoi( refFromFile );
2429                 string anIOR = myStudyContext->getIORbyOldId( id );
2430                 if ( !anIOR.empty() ) {
2431                   CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2432                   if ( !CORBA::is_nil( hypObject ) ) {
2433                     SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2434                     if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2435                       myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2436                   }
2437                 }
2438               }
2439             }
2440             aGroup->CloseOnDisk();
2441           }
2442
2443           // --> try to find submeshes containers for each type of submesh
2444           for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
2445             char name_meshgroup[ 30 ];
2446             if ( j == GetSubMeshOnVertexTag() )
2447               strcpy( name_meshgroup, "SubMeshes On Vertex" );
2448             else if ( j == GetSubMeshOnEdgeTag() )
2449               strcpy( name_meshgroup, "SubMeshes On Edge" );
2450             else if ( j == GetSubMeshOnWireTag() )
2451               strcpy( name_meshgroup, "SubMeshes On Wire" );
2452             else if ( j == GetSubMeshOnFaceTag() )
2453               strcpy( name_meshgroup, "SubMeshes On Face" );
2454             else if ( j == GetSubMeshOnShellTag() )
2455               strcpy( name_meshgroup, "SubMeshes On Shell" );
2456             else if ( j == GetSubMeshOnSolidTag() )
2457               strcpy( name_meshgroup, "SubMeshes On Solid" );
2458             else if ( j == GetSubMeshOnCompoundTag() )
2459               strcpy( name_meshgroup, "SubMeshes On Compound" );
2460             
2461             // try to get submeshes container HDF group
2462             if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
2463               // open submeshes containers HDF group
2464               aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2465               aGroup->OpenOnDisk();
2466               
2467               // get number of submeshes
2468               int aNbSubMeshes = aGroup->nInternalObjects(); 
2469               for ( int k = 0; k < aNbSubMeshes; k++ ) {
2470                 // identify submesh
2471                 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
2472                 aGroup->InternalObjectIndentify( k, name_submeshgroup );
2473                 if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
2474                   // --> get submesh id
2475                   int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
2476                   if ( subid <= 0 )
2477                     continue;
2478                   // open submesh HDF group
2479                   aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
2480                   aSubGroup->OpenOnDisk();
2481                   
2482                   // try to read and set reference to subshape
2483                   GEOM::GEOM_Object_var aSubShapeObject;
2484                   SMESH::SMESH_subMesh_var aSubMesh;
2485
2486                   if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
2487                     // load submesh "Ref on shape" - it's an entry to SObject
2488                     aDataset = new HDFdataset( "Ref on shape", aSubGroup );
2489                     aDataset->OpenOnDisk();
2490                     size = aDataset->GetSize();
2491                     char* refFromFile = new char[ size ];
2492                     aDataset->ReadFromDisk( refFromFile );
2493                     aDataset->CloseOnDisk();
2494                     if ( strlen( refFromFile ) > 0 ) {
2495                       SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
2496                       CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
2497                       if ( !CORBA::is_nil( subShapeObject ) ) {
2498                         aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
2499                         if ( !aSubShapeObject->_is_nil() )
2500                           aSubMesh = SMESH::SMESH_subMesh::_duplicate
2501                             ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
2502                         if ( aSubMesh->_is_nil() )
2503                           continue;
2504       CORBA::String_var iorSubString = GetORB()->object_to_string( aSubMesh );
2505                         int newSubId = myStudyContext->findId( string( iorSubString.in() ) );
2506                         myStudyContext->mapOldToNew( subid, newSubId );
2507                       }
2508                     }
2509                   }
2510                   
2511                   if ( aSubMesh->_is_nil() )
2512                     continue;
2513
2514                   // VSR: Get submesh data from MED convertor
2515 //                int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
2516 //                if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
2517 //                  if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
2518 //                            subid << " for subshape # " << anInternalSubmeshId);
2519 //                  SMESHDS_SubMesh* aSubMeshDS =
2520 //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
2521 //                  if ( !aSubMeshDS ) {
2522 //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
2523 //                              anInternalSubmeshId << " in current mesh!");
2524 //                  }
2525 //                  else
2526 //                    myReader.GetSubMesh( aSubMeshDS, subid );
2527 //                }
2528                     
2529                   // try to get applied algorithms
2530                   if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
2531                     // open "applied algorithms" HDF group
2532                     aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
2533                     aSubSubGroup->OpenOnDisk();
2534                     // get number of applied algorithms
2535                     int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
2536                     for ( int l = 0; l < aNbSubObjects; l++ ) {
2537                       char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2538                       aSubSubGroup->InternalObjectIndentify( l, name_dataset );
2539                       // check if it is an algorithm
2540                       if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
2541                         aDataset = new HDFdataset( name_dataset, aSubSubGroup );
2542                         aDataset->OpenOnDisk();
2543                         size = aDataset->GetSize();
2544                         char* refFromFile = new char[ size ];
2545                         aDataset->ReadFromDisk( refFromFile );
2546                         aDataset->CloseOnDisk();
2547
2548                         //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2549                         //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2550                         int id = atoi( refFromFile );
2551                         string anIOR = myStudyContext->getIORbyOldId( id );
2552                         if ( !anIOR.empty() ) {
2553                           CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2554                           if ( !CORBA::is_nil( hypObject ) ) {
2555                             SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2556                             if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2557                               myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
2558                           }
2559                         }
2560                       }
2561                     }
2562                     // close "applied algorithms" HDF group
2563                     aSubSubGroup->CloseOnDisk();
2564                   }
2565                   
2566                   // try to get applied hypotheses
2567                   if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2568                     // open "applied hypotheses" HDF group
2569                     aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
2570                     aSubSubGroup->OpenOnDisk();
2571                     // get number of applied hypotheses
2572                     int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
2573                     for ( int l = 0; l < aNbSubObjects; l++ ) {
2574                       char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2575                       aSubSubGroup->InternalObjectIndentify( l, name_dataset );
2576                       // check if it is a hypothesis
2577                       if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2578                         aDataset = new HDFdataset( name_dataset, aSubSubGroup );
2579                         aDataset->OpenOnDisk();
2580                         size = aDataset->GetSize();
2581                         char* refFromFile = new char[ size ];
2582                         aDataset->ReadFromDisk( refFromFile );
2583                         aDataset->CloseOnDisk();
2584                         
2585                         //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2586                         //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2587                         int id = atoi( refFromFile );
2588                         string anIOR = myStudyContext->getIORbyOldId( id );
2589                         if ( !anIOR.empty() ) {
2590                           CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2591                           if ( !CORBA::is_nil( hypObject ) ) {
2592                             SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2593                             if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2594                               myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
2595                           }
2596                         }
2597                       }
2598                     }
2599                     // close "applied hypotheses" HDF group
2600                     aSubSubGroup->CloseOnDisk();
2601                   }
2602
2603                   // close submesh HDF group
2604                   aSubGroup->CloseOnDisk();
2605                 }
2606               }
2607               // close submeshes containers HDF group
2608               aGroup->CloseOnDisk();
2609             }
2610           }
2611
2612           if(hasData) {
2613             // Read sub-meshes from MED
2614             if(MYDEBUG) MESSAGE("Create all sub-meshes");
2615             myReader.CreateAllSubMeshes();
2616
2617
2618             // Read node positions on sub-shapes (SMDS_Position)
2619
2620             if ( aTopGroup->ExistInternalObject( "Node Positions" ))
2621             {
2622               // There are 5 datasets to read:
2623               // "Nodes on Edges" - ID of node on edge
2624               // "Edge positions" - U parameter on node on edge
2625               // "Nodes on Faces" - ID of node on face
2626               // "Face U positions" - U parameter of node on face
2627               // "Face V positions" - V parameter of node on face
2628               char* aEid_DSName = "Nodes on Edges";
2629               char* aEu_DSName  = "Edge positions";
2630               char* aFu_DSName  = "Face U positions";
2631               //char* aFid_DSName = "Nodes on Faces";
2632               //char* aFv_DSName  = "Face V positions";
2633
2634               // data to retrieve
2635               int nbEids = 0, nbFids = 0;
2636               int *aEids = 0, *aFids  = 0;
2637               double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
2638
2639               // open a group
2640               aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
2641               aGroup->OpenOnDisk();
2642
2643               // loop on 5 data sets
2644               int aNbObjects = aGroup->nInternalObjects();
2645               for ( int i = 0; i < aNbObjects; i++ )
2646               {
2647                 // identify dataset
2648                 char aDSName[ HDF_NAME_MAX_LEN+1 ];
2649                 aGroup->InternalObjectIndentify( i, aDSName );
2650                 // read data
2651                 aDataset = new HDFdataset( aDSName, aGroup );
2652                 aDataset->OpenOnDisk();
2653                 if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
2654                 {
2655                   double* pos = new double [ aDataset->GetSize() ];
2656                   aDataset->ReadFromDisk( pos );
2657                   // which one?
2658                   if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
2659                     aEpos = pos;
2660                   else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
2661                     aFupos = pos;
2662                   else
2663                     aFvpos = pos;
2664                 }
2665                 else // NODE IDS
2666                 {
2667                   int aSize = aDataset->GetSize();
2668
2669                   // for reading files, created from 18.07.2005 till 10.10.2005
2670                   if (aDataset->GetType() == HDF_STRING)
2671                     aSize /= sizeof(int);
2672
2673                   int* ids = new int [aSize];
2674                   aDataset->ReadFromDisk( ids );
2675                   // on face or nodes?
2676                   if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
2677                     aEids = ids;
2678                     nbEids = aSize;
2679                   }
2680                   else {
2681                     aFids = ids;
2682                     nbFids = aSize;
2683                   }
2684                 }
2685               } // loop on 5 datasets
2686
2687               // Set node positions on edges or faces
2688               for ( int onFace = 0; onFace < 2; onFace++ )
2689               {
2690                 int nbNodes = ( onFace ? nbFids : nbEids );
2691                 if ( nbNodes == 0 ) continue;
2692                 int* aNodeIDs = ( onFace ? aFids : aEids );
2693                 double* aUPos = ( onFace ? aFupos : aEpos );
2694                 double* aVPos = ( onFace ? aFvpos : 0 );
2695                 // loop on node IDs
2696                 for ( int iNode = 0; iNode < nbNodes; iNode++ )
2697                 {
2698                   const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
2699                   ASSERT( node );
2700                   SMDS_PositionPtr aPos = node->GetPosition();
2701                   ASSERT( aPos )
2702                   if ( onFace ) {
2703                     ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );
2704                     SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
2705                       ( static_cast<const SMDS_FacePosition*>( aPos.get() ));
2706                     fPos->SetUParameter( aUPos[ iNode ]);
2707                     fPos->SetVParameter( aVPos[ iNode ]);
2708                   }
2709                   else {
2710                     ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );
2711                     SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
2712                       ( static_cast<const SMDS_EdgePosition*>( aPos.get() ));
2713                     fPos->SetUParameter( aUPos[ iNode ]);
2714                   }
2715                 }
2716               }
2717               if ( aEids ) delete [] aEids;
2718               if ( aFids ) delete [] aFids;
2719               if ( aEpos ) delete [] aEpos;
2720               if ( aFupos ) delete [] aFupos;
2721               if ( aFvpos ) delete [] aFvpos;
2722               
2723               aGroup->CloseOnDisk();
2724
2725             } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
2726           } // if ( hasData )
2727
2728           // Recompute State (as computed sub-meshes are restored from MED)
2729           if ( !aShapeObject->_is_nil() ) {
2730             MESSAGE("Compute State Engine ...");
2731             TopoDS_Shape myLocShape = GeomObjectToShape( aShapeObject );
2732             myNewMeshImpl->GetImpl().GetSubMesh(myLocShape)->ComputeStateEngine
2733               (SMESH_subMesh::SUBMESH_RESTORED);
2734             MESSAGE("Compute State Engine finished");
2735           }
2736
2737           // try to get groups
2738           for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
2739             char name_group[ 30 ];
2740             if ( ii == GetNodeGroupsTag() )
2741               strcpy( name_group, "Groups of Nodes" );
2742             else if ( ii == GetEdgeGroupsTag() )
2743               strcpy( name_group, "Groups of Edges" );
2744             else if ( ii == GetFaceGroupsTag() )
2745               strcpy( name_group, "Groups of Faces" );
2746             else if ( ii == GetVolumeGroupsTag() )
2747               strcpy( name_group, "Groups of Volumes" );
2748
2749             if ( aTopGroup->ExistInternalObject( name_group ) ) {
2750               aGroup = new HDFgroup( name_group, aTopGroup );
2751               aGroup->OpenOnDisk();
2752               // get number of groups
2753               int aNbSubObjects = aGroup->nInternalObjects(); 
2754               for ( int j = 0; j < aNbSubObjects; j++ ) {
2755                 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2756                 aGroup->InternalObjectIndentify( j, name_dataset );
2757                 // check if it is an group
2758                 if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
2759                   // --> get group id
2760                   int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
2761                   if ( subid <= 0 )
2762                     continue;
2763                   aDataset = new HDFdataset( name_dataset, aGroup );
2764                   aDataset->OpenOnDisk();
2765
2766                   // Retrieve actual group name
2767                   size = aDataset->GetSize();
2768                   char* nameFromFile = new char[ size ];
2769                   aDataset->ReadFromDisk( nameFromFile );
2770                   aDataset->CloseOnDisk();
2771
2772                   // Try to find a shape reference
2773                   TopoDS_Shape aShape;
2774                   char aRefName[ 30 ];
2775                   sprintf( aRefName, "Ref on shape %d", subid);
2776                   if ( aGroup->ExistInternalObject( aRefName ) ) {
2777                     // load mesh "Ref on shape" - it's an entry to SObject
2778                     aDataset = new HDFdataset( aRefName, aGroup );
2779                     aDataset->OpenOnDisk();
2780                     size = aDataset->GetSize();
2781                     char* refFromFile = new char[ size ];
2782                     aDataset->ReadFromDisk( refFromFile );
2783                     aDataset->CloseOnDisk();
2784                     if ( strlen( refFromFile ) > 0 ) {
2785                       SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
2786                       CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
2787                       if ( !CORBA::is_nil( shapeObject ) ) {
2788                         aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
2789                         if ( !aShapeObject->_is_nil() )
2790                           aShape = GeomObjectToShape( aShapeObject );
2791                       }
2792                     }
2793                   }
2794                   // Create group servant
2795                   SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
2796                   SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
2797                     ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
2798                   // Obtain a SMESHDS_Group object 
2799                   if ( aNewGroup->_is_nil() )
2800                     continue;
2801
2802       CORBA::String_var iorSubString = GetORB()->object_to_string( aNewGroup );
2803                   int newSubId = myStudyContext->findId( string( iorSubString.in() ) );
2804                   myStudyContext->mapOldToNew( subid, newSubId );
2805
2806                   SMESH_GroupBase_i* aGroupImpl =
2807                     dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
2808                   if ( !aGroupImpl )
2809                     continue;
2810
2811                   SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
2812                   if ( !aLocalGroup )
2813                     continue;
2814
2815                   SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
2816                   aGroupBaseDS->SetStoreName( name_dataset );
2817
2818                   // Fill group with contents from MED file
2819                   SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
2820                   if ( aGrp )
2821                     myReader.GetGroup( aGrp );
2822                 }
2823               }
2824               aGroup->CloseOnDisk();
2825             }
2826           }
2827         }
2828         // close mesh group
2829         aTopGroup->CloseOnDisk();       
2830       }
2831     }
2832   }
2833   // close HDF file
2834   aFile->CloseOnDisk();
2835   delete aFile;
2836
2837   // Remove temporary files created from the stream
2838   if ( !isMultiFile ) 
2839     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
2840
2841   INFOS( "SMESH_Gen_i::Load completed" );
2842   return true;
2843 }
2844
2845 //=============================================================================
2846 /*!
2847  *  SMESH_Gen_i::LoadASCII
2848  *
2849  *  Load SMESH module's data in ASCII format (not implemented yet)
2850  */
2851 //=============================================================================
2852
2853 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
2854                              const SALOMEDS::TMPFile& theStream,
2855                              const char*              theURL,
2856                              bool                     isMultiFile ) {
2857   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
2858   return Load( theComponent, theStream, theURL, isMultiFile );
2859 }
2860
2861 //=============================================================================
2862 /*!
2863  *  SMESH_Gen_i::Close
2864  *
2865  *  Clears study-connected data when it is closed
2866  */
2867 //=============================================================================
2868
2869 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
2870 {
2871   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
2872
2873   // Clear study contexts data
2874   int studyId = GetCurrentStudyID();
2875   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
2876     delete myStudyContextMap[ studyId ];
2877     myStudyContextMap.erase( studyId );
2878   }
2879   return;
2880 }
2881
2882 //=============================================================================
2883 /*!
2884  *  SMESH_Gen_i::ComponentDataType
2885  * 
2886  *  Get component data type
2887  */
2888 //=============================================================================
2889
2890 char* SMESH_Gen_i::ComponentDataType()
2891 {
2892   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
2893   return CORBA::string_dup( "SMESH" );
2894 }
2895
2896     
2897 //=============================================================================
2898 /*!
2899  *  SMESH_Gen_i::IORToLocalPersistentID
2900  *  
2901  *  Transform data from transient form to persistent
2902  */
2903 //=============================================================================
2904
2905 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
2906                                            const char*           IORString,
2907                                            CORBA::Boolean        /*isMultiFile*/,
2908                                            CORBA::Boolean        /*isASCII*/ )
2909 {
2910   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
2911   StudyContext* myStudyContext = GetCurrentStudyContext();
2912   
2913   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
2914     int anId = myStudyContext->findId( IORString );
2915     if ( anId ) {
2916       if(MYDEBUG) MESSAGE( "VSR " << anId )
2917       char strId[ 20 ];
2918       sprintf( strId, "%d", anId );
2919       return  CORBA::string_dup( strId );
2920     }
2921   }
2922   return CORBA::string_dup( "" );
2923 }
2924
2925 //=============================================================================
2926 /*!
2927  *  SMESH_Gen_i::LocalPersistentIDToIOR
2928  *
2929  *  Transform data from persistent form to transient
2930  */
2931 //=============================================================================
2932
2933 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
2934                                            const char*           aLocalPersistentID,
2935                                            CORBA::Boolean        /*isMultiFile*/,
2936                                            CORBA::Boolean        /*isASCII*/ )
2937 {
2938   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
2939   StudyContext* myStudyContext = GetCurrentStudyContext();
2940
2941   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
2942     int anId = atoi( aLocalPersistentID );
2943     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
2944   }
2945   return CORBA::string_dup( "" );
2946 }
2947
2948 //=======================================================================
2949 //function : RegisterObject
2950 //purpose  : 
2951 //=======================================================================
2952
2953 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
2954 {
2955   StudyContext* myStudyContext = GetCurrentStudyContext();
2956   if ( myStudyContext && !CORBA::is_nil( theObject )) {
2957     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
2958     return myStudyContext->addObject( string( iorString.in() ) );
2959   }
2960   return 0;
2961 }
2962       
2963 //=============================================================================
2964 /*! 
2965  *  SMESHEngine_factory
2966  *
2967  *  C factory, accessible with dlsym, after dlopen  
2968  */
2969 //=============================================================================
2970
2971 extern "C"
2972 { SMESH_I_EXPORT
2973   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
2974                                                  PortableServer::POA_ptr   poa, 
2975                                                  PortableServer::ObjectId* contId,
2976                                                  const char*               instanceName, 
2977                                                  const char*               interfaceName )
2978   {
2979     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
2980     if(MYDEBUG) SCRUTE(interfaceName);
2981     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
2982     return aSMESHGen->getId() ;
2983   }
2984 }