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