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