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