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