Salome HOME
e3b8630d84d1f51fa358c810e84e6ebdf11bc0f1
[modules/smesh.git] / src / SMESH_I / SMESH_Gen_i.cxx
1 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 //  File   : SMESH_Gen_i.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //  $Header$
28
29 #include <TopExp.hxx>
30 #include <TopExp_Explorer.hxx>
31 #include <TopoDS.hxx>
32 #include <TopoDS_Iterator.hxx>
33 #include <TopoDS_Compound.hxx>
34 #include <TopoDS_CompSolid.hxx>
35 #include <TopoDS_Solid.hxx>
36 #include <TopoDS_Shell.hxx>
37 #include <TopoDS_Face.hxx>
38 #include <TopoDS_Wire.hxx>
39 #include <TopoDS_Edge.hxx>
40 #include <TopoDS_Vertex.hxx>
41 #include <TopoDS_Shape.hxx>
42 #include <TopTools_MapOfShape.hxx>
43 #include <TopTools_IndexedMapOfShape.hxx>
44 #include <TopTools_ListOfShape.hxx>
45 #include <TopTools_ListIteratorOfListOfShape.hxx>
46 #include <gp_Pnt.hxx>
47 #include <BRep_Tool.hxx>
48 #include <TCollection_AsciiString.hxx>
49 #include <OSD.hxx>
50
51 #include "Utils_CorbaException.hxx"
52
53 #include "utilities.h"
54 #include <fstream>
55 #include <stdio.h>
56
57 #ifdef WNT
58  #include <windows.h>
59 #else
60  #include <dlfcn.h>
61 #endif
62
63 #ifdef WNT
64  #define LibHandle HMODULE
65  #define LoadLib( name ) LoadLibrary( name )
66  #define GetProc GetProcAddress
67  #define UnLoadLib( handle ) FreeLibrary( handle );
68 #else
69  #define LibHandle void*
70  #define LoadLib( name ) dlopen( name, RTLD_LAZY )
71  #define GetProc dlsym
72  #define UnLoadLib( handle ) dlclose( handle );
73 #endif
74
75 #include <HDFOI.hxx>
76
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_Mesh_i.hxx"
79 #include "SMESH_Hypothesis_i.hxx"
80 #include "SMESH_Algo_i.hxx"
81 #include "SMESH_Group_i.hxx"
82 #include "SMESH_PythonDump.hxx"
83
84 #include "SMESHDS_Document.hxx"
85 #include "SMESHDS_Group.hxx"
86 #include "SMESHDS_GroupOnGeom.hxx"
87 #include "SMESH_Mesh.hxx"
88 #include "SMESH_Hypothesis.hxx"
89 #include "SMESH_Group.hxx"
90 #include "SMESH_MeshEditor.hxx"
91
92 #include "SMDS_EdgePosition.hxx"
93 #include "SMDS_FacePosition.hxx"
94 #include "SMDS_VertexPosition.hxx"
95 #include "SMDS_SpacePosition.hxx"
96 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
97
98 #include CORBA_SERVER_HEADER(SMESH_Group)
99 #include CORBA_SERVER_HEADER(SMESH_Filter)
100
101 #include "DriverMED_W_SMESHDS_Mesh.h"
102 #include "DriverMED_R_SMESHDS_Mesh.h"
103
104 #include "SALOMEDS_Tool.hxx"
105 #include "SALOME_NamingService.hxx"
106 #include "SALOME_LifeCycleCORBA.hxx"
107 #include "Utils_SINGLETON.hxx"
108 #include "OpUtil.hxx"
109
110 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
111
112 #include "GEOM_Client.hxx"
113 #include "Utils_ExceptHandlers.hxx"
114
115 #include <map>
116
117 using namespace std;
118 using SMESH::TPythonDump;
119
120 #define NUM_TMP_FILES 2
121
122 #ifdef _DEBUG_
123 static int MYDEBUG = 0;
124 #else
125 static int MYDEBUG = 0;
126 #endif
127
128 // Static variables definition
129 CORBA::ORB_var          SMESH_Gen_i::myOrb;
130 PortableServer::POA_var SMESH_Gen_i::myPoa;
131 SALOME_NamingService*   SMESH_Gen_i::myNS  = NULL;
132 SALOME_LifeCycleCORBA*  SMESH_Gen_i::myLCC = NULL;
133 SMESH_Gen_i*            SMESH_Gen_i::mySMESHGen = NULL;
134
135 //=============================================================================
136 /*!
137  *  GetServant [ static ]
138  *
139  *  Get servant of the CORBA object
140  */
141 //=============================================================================
142
143 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
144 {
145   if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
146     return NULL;
147   try {
148     PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
149     return aServant;
150   } 
151   catch (...) {
152     INFOS( "GetServant - Unknown exception was caught!!!" ); 
153     return NULL;
154   }
155 }
156
157 //=============================================================================
158 /*!
159  *  SObjectToObject [ static ]
160  *
161  *  Get CORBA object corresponding to the SALOMEDS::SObject
162  */
163 //=============================================================================
164
165 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
166 {
167   SALOMEDS::GenericAttribute_var anAttr;
168   CORBA::Object_var anObj;
169   if ( !theSObject->_is_nil() ) {
170     try {
171       if( theSObject->FindAttribute( anAttr, "AttributeIOR" ) ) {
172         SALOMEDS::AttributeIOR_var anIOR  = SALOMEDS::AttributeIOR::_narrow( anAttr );
173         CORBA::String_var aValue = anIOR->Value();
174         if( strcmp( aValue, "" ) != 0 )
175           anObj = GetORB()->string_to_object( aValue );
176         }
177     }
178     catch( ... ) {
179       INFOS( "SObjectToObject - Unknown exception was caught!!!" );
180     }
181   }
182   return anObj;
183 }
184
185 //=============================================================================
186 /*!
187  *  GetNS [ static ]
188  *
189  *  Get SALOME_NamingService object 
190  */
191 //=============================================================================
192
193 SALOME_NamingService* SMESH_Gen_i::GetNS()
194 {
195   if ( myNS == NULL ) {
196     myNS = SINGLETON_<SALOME_NamingService>::Instance();
197     ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
198     myNS->init_orb( GetORB() );
199   }
200   return myNS;
201 }
202
203 //=============================================================================
204 /*!
205  *  GetLCC [ static ]
206  *
207  *  Get SALOME_LifeCycleCORBA object
208  */
209 //=============================================================================     
210 SALOME_LifeCycleCORBA*  SMESH_Gen_i::GetLCC() {
211   if ( myLCC == NULL ) {
212     myLCC = new SALOME_LifeCycleCORBA( GetNS() );
213   }
214   return myLCC;
215 }
216
217
218 //=============================================================================
219 /*!
220  *  GetGeomEngine [ static ]
221  *
222  *  Get GEOM::GEOM_Gen reference
223  */
224 //=============================================================================     
225 GEOM::GEOM_Gen_ptr SMESH_Gen_i::GetGeomEngine() {
226   GEOM::GEOM_Gen_var aGeomEngine =
227     GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
228   return aGeomEngine._retn();
229 }
230
231 //=============================================================================
232 /*!
233  *  SMESH_Gen_i::SMESH_Gen_i
234  *
235  *  Default constructor: not for use
236  */
237 //=============================================================================
238
239 SMESH_Gen_i::SMESH_Gen_i()
240 {
241   INFOS( "SMESH_Gen_i::SMESH_Gen_i : default constructor" );
242 }
243
244 //=============================================================================
245 /*!
246  *  SMESH_Gen_i::SMESH_Gen_i 
247  *
248  *  Standard constructor, used with Container
249  */
250 //=============================================================================
251
252 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr            orb,
253                           PortableServer::POA_ptr   poa,
254                           PortableServer::ObjectId* contId, 
255                           const char*               instanceName, 
256                           const char*               interfaceName )
257      : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
258 {
259   MESSAGE( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
260
261   myOrb = CORBA::ORB::_duplicate(orb);
262   myPoa = PortableServer::POA::_duplicate(poa);
263   
264   _thisObj = this ;
265   _id = myPoa->activate_object( _thisObj );
266   
267   myIsEmbeddedMode = false;
268   myShapeReader = NULL;  // shape reader
269   mySMESHGen = this;
270
271   // set it in standalone mode only
272   //OSD::SetSignal( true );
273 }
274
275 //=============================================================================
276 /*!
277  *  SMESH_Gen_i::~SMESH_Gen_i
278  *
279  *  Destructor
280  */
281 //=============================================================================
282
283 SMESH_Gen_i::~SMESH_Gen_i()
284 {
285   INFOS( "SMESH_Gen_i::~SMESH_Gen_i" );
286
287   // delete hypothesis creators
288   map<string, GenericHypothesisCreator_i*>::iterator itHyp;
289   for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
290   {
291     delete (*itHyp).second;
292   }
293   myHypCreatorMap.clear();
294
295   // Clear study contexts data
296   map<int, StudyContext*>::iterator it;
297   for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
298     delete it->second;
299   }
300   myStudyContextMap.clear();
301   // delete shape reader
302   if ( !myShapeReader ) 
303     delete myShapeReader;
304 }
305   
306 //=============================================================================
307 /*!
308  *  SMESH_Gen_i::createHypothesis
309  *
310  *  Create hypothesis of given type
311  */
312 //=============================================================================
313 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
314                                                           const char* theLibName)
315      throw (SALOME::SALOME_Exception)
316 {
317   /* It's Need to tranlate lib name for WIN32 or X platform */
318   char* aPlatformLibName = 0;
319   if ( theLibName && theLibName[0] != '\0'  )
320   {
321     int libNameLen = strlen(theLibName);
322     //check for old format "libXXXXXXX.so"
323     if( libNameLen > 7 && !strncmp( theLibName, "lib", 3 ) && !strcmp( theLibName+libNameLen-3, ".so" ) )
324       {
325         //the old format
326 #ifdef WNT
327         aPlatformLibName = new char[libNameLen - 1];
328         aPlatformLibName[0] = '\0';
329         aPlatformLibName = strncat( aPlatformLibName, theLibName+3, libNameLen-6  );
330         aPlatformLibName = strcat( aPlatformLibName, ".dll" );
331   aPlatformLibName[libNameLen - 2] = '\0';
332 #else
333         aPlatformLibName = new char[ libNameLen + 1];
334         aPlatformLibName[0] = '\0';
335         aPlatformLibName = strcat( aPlatformLibName, theLibName );
336   aPlatformLibName[libNameLen] = '\0';
337 #endif
338
339       }
340     else
341       {
342         //try to use new format 
343 #ifdef WNT
344         aPlatformLibName = new char[ libNameLen + 5 ];
345         aPlatformLibName[0] = '\0';
346         aPlatformLibName = strcat( aPlatformLibName, theLibName );
347         aPlatformLibName = strcat( aPlatformLibName, ".dll" );
348 #else
349         aPlatformLibName = new char[ libNameLen + 7 ];
350         aPlatformLibName[0] = '\0';
351         aPlatformLibName = strcat( aPlatformLibName, "lib" );
352         aPlatformLibName = strcat( aPlatformLibName, theLibName );
353         aPlatformLibName = strcat( aPlatformLibName, ".so" );
354 #endif
355       }
356   }
357   
358
359
360   Unexpect aCatch(SALOME_SalomeException);
361   if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName/*theLibName*/);
362
363   // create a new hypothesis object servant
364   SMESH_Hypothesis_i* myHypothesis_i = 0;
365   SMESH::SMESH_Hypothesis_var hypothesis_i;
366
367   try
368   {
369     // check, if creator for this hypothesis type already exists
370     if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
371     {
372       // load plugin library
373       if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
374       LibHandle libHandle = LoadLib( aPlatformLibName/*theLibName*/ );
375       if (!libHandle)
376       {
377         // report any error, if occured
378 #ifndef WNT
379         const char* anError = dlerror();
380         throw(SALOME_Exception(anError));
381 #else
382         throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
383 #endif
384       }
385
386       // get method, returning hypothesis creator
387       if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
388       typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* theHypName);
389       GetHypothesisCreator procHandle =
390         (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
391       if (!procHandle)
392       {
393         throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
394         UnLoadLib(libHandle);
395       }
396
397       // get hypothesis creator
398       if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
399       GenericHypothesisCreator_i* aCreator = procHandle(theHypName);
400       if (!aCreator)
401       {
402         throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
403       }
404
405       // map hypothesis creator to a hypothesis name
406       myHypCreatorMap[string(theHypName)] = aCreator;
407     }
408
409     // create a new hypothesis object, store its ref. in studyContext
410     if(MYDEBUG) MESSAGE("Create Hypothesis " << theHypName);
411     myHypothesis_i =
412       myHypCreatorMap[string(theHypName)]->Create (myPoa, GetCurrentStudyID(), &myGen);
413     myHypothesis_i->SetLibName(aPlatformLibName/*theLibName*/); // for persistency assurance
414   }
415   catch (SALOME_Exception& S_ex)
416   {
417     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
418   }
419
420   if ( aPlatformLibName )
421     delete[] aPlatformLibName;
422
423   if (!myHypothesis_i)
424     return hypothesis_i._retn();
425
426   // activate the CORBA servant of hypothesis
427   hypothesis_i = SMESH::SMESH_Hypothesis::_narrow( myHypothesis_i->_this() );
428   int nextId = RegisterObject( hypothesis_i );
429   if(MYDEBUG) MESSAGE( "Add hypo to map with id = "<< nextId );  
430
431   return hypothesis_i._retn();
432 }
433   
434 //=============================================================================
435 /*!
436  *  SMESH_Gen_i::createMesh
437  *
438  *  Create empty mesh on shape
439  */
440 //=============================================================================
441 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
442      throw ( SALOME::SALOME_Exception )
443 {
444   Unexpect aCatch(SALOME_SalomeException);
445   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
446
447   // Get or create the GEOM_Client instance
448   try {
449     // create a new mesh object servant, store it in a map in study context
450     SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
451     // create a new mesh object
452     meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
453
454     // activate the CORBA servant of Mesh
455     SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
456     int nextId = RegisterObject( mesh );
457     if(MYDEBUG) MESSAGE( "Add mesh to map with id = "<< nextId);
458     return mesh._retn();
459   }
460   catch (SALOME_Exception& S_ex) {
461     THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
462   }
463   return SMESH::SMESH_Mesh::_nil();
464 }
465
466 //=============================================================================
467 /*!
468  *  SMESH_Gen_i::GetShapeReader
469  *
470  *  Get shape reader
471  */
472 //=============================================================================
473 GEOM_Client* SMESH_Gen_i::GetShapeReader()
474 {
475   // create shape reader if necessary
476   if ( !myShapeReader ) 
477     myShapeReader = new GEOM_Client(GetContainerRef());
478   ASSERT( myShapeReader );
479   return myShapeReader;
480 }
481
482 //=============================================================================
483 /*!
484  *  SMESH_Gen_i::SetEmbeddedMode
485  *
486  *  Set current mode
487  */
488 //=============================================================================
489
490 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
491 {
492   myIsEmbeddedMode = theMode;
493
494   if ( !myIsEmbeddedMode ) {
495     //PAL10867: disable signals catching with "noexcepthandler" option
496     char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
497     if (!envNoCatchSignals || !atoi(envNoCatchSignals))
498     {
499       bool raiseFPE;
500 #ifdef _DEBUG_
501       raiseFPE = true;
502       char* envDisableFPE = getenv("DISABLE_FPE");
503       if (envDisableFPE && atoi(envDisableFPE))
504         raiseFPE = false;
505 #else
506       raiseFPE = false;
507 #endif
508       OSD::SetSignal( raiseFPE );
509     }
510     // else OSD::SetSignal() is called in GUI
511   }
512 }
513
514 //=============================================================================
515 /*!
516  *  SMESH_Gen_i::IsEmbeddedMode
517  *
518  *  Get current mode
519  */
520 //=============================================================================
521
522 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
523 {
524   return myIsEmbeddedMode;
525 }
526
527 //=============================================================================
528 /*!
529  *  SMESH_Gen_i::SetCurrentStudy
530  *
531  *  Set current study
532  */
533 //=============================================================================
534
535 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
536 {
537   //if(MYDEBUG)
538   //MESSAGE( "SMESH_Gen_i::SetCurrentStudy" );
539   myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
540   // create study context, if it doesn't exist and set current study
541   int studyId = GetCurrentStudyID();
542   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SetCurrentStudy: study Id = " << studyId );
543   if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() ) {
544     myStudyContextMap[ studyId ] = new StudyContext;      
545   }
546
547   // myCurrentStudy may be nil
548   if ( !CORBA::is_nil( myCurrentStudy ) ) {
549     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder(); 
550     if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
551       aStudyBuilder->LoadWith( myCurrentStudy->FindComponent( "GEOM" ), GetGeomEngine() );
552
553   // set current study for geom engine
554   //if ( !CORBA::is_nil( GetGeomEngine() ) )
555   //  GetGeomEngine()->GetCurrentStudy( myCurrentStudy->StudyId() );
556   }
557 }
558
559 //=============================================================================
560 /*!
561  *  SMESH_Gen_i::GetCurrentStudy
562  *
563  *  Get current study
564  */
565 //=============================================================================
566
567 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
568 {
569   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
570   return SALOMEDS::Study::_duplicate( myCurrentStudy );
571 }
572
573 //=============================================================================
574 /*!
575  *  SMESH_Gen_i::GetCurrentStudyContext 
576  *
577  *  Get current study context
578  */
579 //=============================================================================
580 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
581 {
582   if ( !CORBA::is_nil( myCurrentStudy ) &&
583       myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
584     return myStudyContextMap[ myCurrentStudy->StudyId() ];
585   else
586     return 0;
587 }
588
589 //=============================================================================
590 /*!
591  *  SMESH_Gen_i::CreateHypothesis 
592  *
593  *  Create hypothesis/algorothm of given type and publish it in the study
594  */
595 //=============================================================================
596
597 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
598                                                            const char* theLibName )
599      throw ( SALOME::SALOME_Exception )
600 {
601   Unexpect aCatch(SALOME_SalomeException);
602   // Create hypothesis/algorithm
603   SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
604
605   // Publish hypothesis/algorithm in the study
606   if ( CanPublishInStudy( hyp ) ) {
607     SALOMEDS::SObject_var aSO = PublishHypothesis( myCurrentStudy, hyp );
608     if ( !aSO->_is_nil() ) {
609       // Update Python script
610       TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
611                     << theHypName << "', '" << theLibName << "')";
612     }
613   }
614
615   return hyp._retn();
616 }
617
618 //================================================================================
619 /*!
620  * \brief Return hypothesis of given type holding parameter values of the existing mesh
621   * \param theHypType - hypothesis type name
622   * \param theLibName - plugin library name
623   * \param theMesh - The mesh of interest
624   * \param theGeom - The shape to get parameter values from
625   * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
626   *    in a study and used to compute the mesh, or a temporary one created just to pass
627   *    parameter values
628  */
629 //================================================================================
630
631 SMESH::SMESH_Hypothesis_ptr
632 SMESH_Gen_i::GetHypothesisParameterValues (const char*           theHypType,
633                                            const char*           theLibName,
634                                            SMESH::SMESH_Mesh_ptr theMesh,
635                                            GEOM::GEOM_Object_ptr theGeom)
636     throw ( SALOME::SALOME_Exception )
637 {
638   Unexpect aCatch(SALOME_SalomeException);
639   if ( CORBA::is_nil( theMesh ) )
640     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
641   if ( CORBA::is_nil( theGeom ) )
642     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
643
644   // -----------------------------------------------
645   // find hypothesis used to mesh theGeom
646   // -----------------------------------------------
647
648   // get mesh and shape
649   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
650   TopoDS_Shape shape = GeomObjectToShape( theGeom );
651   if ( !meshServant || shape.IsNull() )
652     return SMESH::SMESH_Hypothesis::_nil();
653   ::SMESH_Mesh& mesh = meshServant->GetImpl();
654
655   if ( mesh.NbNodes() == 0 ) // empty mesh
656     return SMESH::SMESH_Hypothesis::_nil();
657
658   // create a temporary hypothesis to know its dimention
659   SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
660   SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
661   if ( !hypServant )
662     return SMESH::SMESH_Hypothesis::_nil();
663   ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
664
665   // look for a hypothesis of theHypType used to mesh the shape
666   if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
667   {
668     // check local shape
669     SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
670     int nbLocalHyps = aHypList->length();
671     for ( int i = 0; i < nbLocalHyps; i++ )
672       if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND local!
673         return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
674     // check super shapes
675     TopTools_ListIteratorOfListOfShape itShape( mesh.GetAncestors( shape ));
676     while ( nbLocalHyps == 0 && itShape.More() ) {
677       GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
678       if ( ! CORBA::is_nil( geomObj )) {
679         SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
680         nbLocalHyps = aHypList->length();
681         for ( int i = 0; i < nbLocalHyps; i++ )
682           if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
683             return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
684       }
685       itShape.Next();
686     }
687   }
688
689   // let the temporary hypothesis find out some how parameter values
690   if ( hyp->SetParametersByMesh( &mesh, shape ))
691     return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
692     
693   return SMESH::SMESH_Hypothesis::_nil();
694 }
695
696 //=============================================================================
697 /*!
698  *  SMESH_Gen_i::CreateMesh
699  *
700  *  Create empty mesh on a shape and publish it in the study
701  */
702 //=============================================================================
703
704 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
705      throw ( SALOME::SALOME_Exception )
706 {
707   Unexpect aCatch(SALOME_SalomeException);
708   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
709   // create mesh
710   SMESH::SMESH_Mesh_var mesh = this->createMesh();
711   // set shape
712   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
713   ASSERT( meshServant );
714   meshServant->SetShape( theShapeObject );
715
716   // publish mesh in the study
717   if ( CanPublishInStudy( mesh ) ) {
718     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
719     aStudyBuilder->NewCommand();  // There is a transaction
720     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
721     aStudyBuilder->CommitCommand();
722     if ( !aSO->_is_nil() ) {
723       // Update Python script
724       TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
725     }
726   }
727
728   return mesh._retn();
729 }
730
731 //=============================================================================
732 /*!
733  *  SMESH_Gen_i::CreateEmptyMesh
734  *
735  *  Create empty mesh
736  */
737 //=============================================================================
738
739 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
740      throw ( SALOME::SALOME_Exception )
741 {
742   Unexpect aCatch(SALOME_SalomeException);
743   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
744   // create mesh
745   SMESH::SMESH_Mesh_var mesh = this->createMesh();
746
747   // publish mesh in the study
748   if ( CanPublishInStudy( mesh ) ) {
749     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
750     aStudyBuilder->NewCommand();  // There is a transaction
751     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
752     aStudyBuilder->CommitCommand();
753     if ( !aSO->_is_nil() ) {
754       // Update Python script
755       TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
756     }
757   }
758
759   return mesh._retn();
760 }
761
762 //=============================================================================
763 /*!
764  *  SMESH_Gen_i::CreateMeshFromUNV
765  *
766  *  Create mesh and import data from UNV file
767  */
768 //=============================================================================
769
770 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
771   throw ( SALOME::SALOME_Exception )
772 {
773   Unexpect aCatch(SALOME_SalomeException);
774   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromUNV" );
775
776   SMESH::SMESH_Mesh_var aMesh = createMesh();
777   string aFileName;
778   // publish mesh in the study
779   if ( CanPublishInStudy( aMesh ) ) {
780     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
781     aStudyBuilder->NewCommand();  // There is a transaction
782     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
783     aStudyBuilder->CommitCommand();
784     if ( !aSO->_is_nil() ) {
785       // Update Python script
786       TPythonDump() << aSO << " = smeshgen.CreateMeshesFromUNV('" << theFileName << "')";
787     }
788   }
789
790   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
791   ASSERT( aServant );
792   aServant->ImportUNVFile( theFileName );
793
794   // Dump creation of groups
795   aServant->GetGroups();
796
797   return aMesh._retn();
798 }
799
800 //=============================================================================
801 /*!
802  *  SMESH_Gen_i::CreateMeshFromMED
803  *
804  *  Create mesh and import data from MED file
805  */
806 //=============================================================================
807
808 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
809                                                      SMESH::DriverMED_ReadStatus& theStatus)
810      throw ( SALOME::SALOME_Exception )
811 {
812   Unexpect aCatch(SALOME_SalomeException);
813   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshFromMED" );
814
815   // Retrieve mesh names from the file
816   DriverMED_R_SMESHDS_Mesh myReader;
817   myReader.SetFile( theFileName );
818   myReader.SetMeshId( -1 );
819   Driver_Mesh::Status aStatus;
820   list<string> aNames = myReader.GetMeshNames(aStatus);
821   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
822   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
823
824   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
825
826   // Python Dump
827   TPythonDump aPythonDump;
828   aPythonDump << "([";
829   //TCollection_AsciiString aStr ("([");
830
831   if (theStatus == SMESH::DRS_OK) {
832     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
833     aStudyBuilder->NewCommand();  // There is a transaction
834     aResult->length( aNames.size() );
835     int i = 0;
836     
837     // Iterate through all meshes and create mesh objects
838     for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ ) {
839       // Python Dump
840       //if (i > 0) aStr += ", ";
841       if (i > 0) aPythonDump << ", ";
842
843       // create mesh
844       SMESH::SMESH_Mesh_var mesh = createMesh();
845       
846       // publish mesh in the study
847       SALOMEDS::SObject_var aSO;
848       if ( CanPublishInStudy( mesh ) )
849         aSO = PublishMesh( myCurrentStudy, mesh.in(), (*it).c_str() );
850       if ( !aSO->_is_nil() ) {
851         // Python Dump
852         aPythonDump << aSO;
853         //aStr += aSO->GetID();
854       } else {
855         // Python Dump
856         aPythonDump << "mesh_" << i;
857 //         aStr += "mesh_";
858 //         aStr += TCollection_AsciiString(i);
859       }
860
861       // Read mesh data (groups are published automatically by ImportMEDFile())
862       SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
863       ASSERT( meshServant );
864       SMESH::DriverMED_ReadStatus status1 =
865         meshServant->ImportMEDFile( theFileName, (*it).c_str() );
866       if (status1 > theStatus)
867         theStatus = status1;
868
869       aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
870     }
871     aStudyBuilder->CommitCommand();
872   }
873
874   // Update Python script
875   aPythonDump << "], status) = " << this << ".CreateMeshesFromMED('" << theFileName << "')";
876   }
877   // Dump creation of groups
878   for ( int i = 0; i < aResult->length(); ++i )
879     aResult[ i ]->GetGroups();
880
881   return aResult._retn();
882 }
883
884 //=============================================================================
885 /*!
886  *  SMESH_Gen_i::CreateMeshFromSTL
887  *
888  *  Create mesh and import data from STL file
889  */
890 //=============================================================================
891
892 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
893   throw ( SALOME::SALOME_Exception )
894 {
895   Unexpect aCatch(SALOME_SalomeException);
896   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromSTL" );
897
898   SMESH::SMESH_Mesh_var aMesh = createMesh();
899   string aFileName;
900   // publish mesh in the study
901   if ( CanPublishInStudy( aMesh ) ) {
902     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
903     aStudyBuilder->NewCommand();  // There is a transaction
904     SALOMEDS::SObject_var aSO = PublishInStudy
905       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
906     aStudyBuilder->CommitCommand();
907     if ( !aSO->_is_nil() ) {
908       // Update Python script
909       TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL('" << theFileName << "')";
910     }
911   }
912
913   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
914   ASSERT( aServant );
915   aServant->ImportSTLFile( theFileName );
916   return aMesh._retn();
917 }
918
919 //=============================================================================
920 /*!
921  *  SMESH_Gen_i::IsReadyToCompute
922  *
923  *  Returns true if mesh contains enough data to be computed
924  */
925 //=============================================================================
926
927 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
928                                               GEOM::GEOM_Object_ptr theShapeObject )
929   throw ( SALOME::SALOME_Exception )
930 {
931   Unexpect aCatch(SALOME_SalomeException);
932   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
933
934   if ( CORBA::is_nil( theShapeObject ) )
935     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
936                                   SALOME::BAD_PARAM );
937
938   if ( CORBA::is_nil( theMesh ) )
939     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
940                                   SALOME::BAD_PARAM );
941
942   try {
943     // get mesh servant
944     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
945     ASSERT( meshServant );
946     if ( meshServant ) {
947       // get local TopoDS_Shape
948       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
949       // call implementation
950       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
951       return myGen.CheckAlgoState( myLocMesh, myLocShape );
952     }
953   }
954   catch ( SALOME_Exception& S_ex ) {
955     INFOS( "catch exception "<< S_ex.what() );
956   }
957   return false;
958 }
959
960 //================================================================================
961 /*!
962  * \brief  Find SObject for an algo
963  */
964 //================================================================================
965
966 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
967 {
968   if ( algo ) {
969     if ( !myCurrentStudy->_is_nil() ) {
970       // find algo in the study
971       SALOMEDS::SComponent_var father = SALOMEDS::SComponent::_narrow
972         ( myCurrentStudy->FindComponent( ComponentDataType() ) );
973       if ( !father->_is_nil() ) {
974         SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( father );
975         for ( ; itBig->More(); itBig->Next() ) {
976           SALOMEDS::SObject_var gotBranch = itBig->Value();
977           if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
978             SALOMEDS::ChildIterator_var algoIt = myCurrentStudy->NewChildIterator( gotBranch );
979             for ( ; algoIt->More(); algoIt->Next() ) {
980               SALOMEDS::SObject_var algoSO = algoIt->Value();
981               CORBA::Object_var     algoIOR = SObjectToObject( algoSO );
982               if ( !CORBA::is_nil( algoIOR )) {
983                 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
984                 if ( impl && impl->GetImpl() == algo )
985                   return algoSO._retn();
986               }
987             } // loop on algo SO's
988             break;
989           } // if algo tag
990         } // SMESH component iterator
991       }
992     }
993   }
994   return SALOMEDS::SObject::_nil();
995 }
996
997 //================================================================================
998 /*!
999  * \brief Return errors of mesh computation
1000  */
1001 //================================================================================
1002
1003 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh, 
1004                                                            GEOM::GEOM_Object_ptr theSubObject )
1005   throw ( SALOME::SALOME_Exception )
1006 {
1007   Unexpect aCatch(SALOME_SalomeException);
1008   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1009
1010   if ( CORBA::is_nil( theSubObject ) )
1011     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1012
1013   if ( CORBA::is_nil( theMesh ) )
1014     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1015
1016   SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1017   try {
1018     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1019     {
1020       TopoDS_Shape shape = GeomObjectToShape( theSubObject );
1021       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1022
1023       error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1024       int nbErr = 0;
1025
1026       SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1027       const bool includeSelf = true, complexShapeFirst = true;
1028       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1029                                                                complexShapeFirst);
1030       while ( smIt->more() )
1031       {
1032         sm = smIt->next();
1033         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1034           break;
1035         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1036         if ( error && !error->IsOK() && error->myAlgo )
1037         {
1038           SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1039           errStruct.code       = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1040           errStruct.comment    = error->myComment.c_str();
1041           errStruct.subShapeID = sm->GetId();
1042           SALOMEDS::SObject_var algoSO = GetAlgoSO( error->myAlgo );
1043           if ( !algoSO->_is_nil() )
1044             errStruct.algoName   = algoSO->GetName();
1045           else
1046             errStruct.algoName   = error->myAlgo->GetName();
1047         }
1048       }
1049       error_array->length( nbErr );
1050     }
1051   }
1052   catch ( SALOME_Exception& S_ex ) {
1053     INFOS( "catch exception "<< S_ex.what() );
1054   }
1055
1056   return error_array._retn();
1057 }
1058
1059 //================================================================================
1060 /*!
1061  * \brief Returns errors of hypotheses definintion
1062   * \param theMesh - the mesh
1063   * \param theSubObject - the main or sub- shape
1064   * \retval SMESH::algo_error_array* - sequence of errors
1065  */
1066 //================================================================================
1067
1068 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh, 
1069                                                     GEOM::GEOM_Object_ptr theSubObject )
1070       throw ( SALOME::SALOME_Exception )
1071 {
1072   Unexpect aCatch(SALOME_SalomeException);
1073   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1074
1075   if ( CORBA::is_nil( theSubObject ) )
1076     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1077
1078   if ( CORBA::is_nil( theMesh ) )
1079     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1080
1081   SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1082   try {
1083     SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1084     ASSERT( meshServant );
1085     if ( meshServant ) {
1086       TopoDS_Shape myLocShape = GeomObjectToShape( theSubObject );
1087       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1088       list< ::SMESH_Gen::TAlgoStateError > error_list;
1089       list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1090       // call ::SMESH_Gen::GetAlgoState()
1091       myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1092       error_array->length( error_list.size() );
1093       int i = 0;
1094       for ( error = error_list.begin(); error != error_list.end(); ++error )
1095       {
1096         // fill AlgoStateError structure
1097         SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1098         errStruct.state        = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1099         errStruct.algoDim      = error->_algoDim;
1100         errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1101         errStruct.algoName     = "";
1102         SALOMEDS::SObject_var algoSO = GetAlgoSO( error->_algo );
1103         if ( !algoSO->_is_nil() )
1104           errStruct.algoName   = algoSO->GetName();
1105       }
1106     }
1107   }
1108   catch ( SALOME_Exception& S_ex ) {
1109     INFOS( "catch exception "<< S_ex.what() );
1110   }
1111   return error_array._retn();
1112 }
1113
1114 //=============================================================================
1115 /*!
1116  *  SMESH_Gen_i::GetSubShapesId
1117  *
1118  *  Get sub-shapes unique ID's list
1119  */
1120 //=============================================================================
1121
1122 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1123                                             const SMESH::object_array& theListOfSubShapeObject )
1124      throw ( SALOME::SALOME_Exception )
1125 {
1126   Unexpect aCatch(SALOME_SalomeException);
1127   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1128
1129   SMESH::long_array_var shapesId = new SMESH::long_array;
1130   set<int> setId;
1131
1132   if ( CORBA::is_nil( theMainShapeObject ) )
1133     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1134                                   SALOME::BAD_PARAM );
1135
1136   try
1137     {
1138       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1139       TopTools_IndexedMapOfShape myIndexToShape;      
1140       TopExp::MapShapes(myMainShape,myIndexToShape);
1141
1142       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1143         {
1144           GEOM::GEOM_Object_var aShapeObject
1145             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1146           if ( CORBA::is_nil( aShapeObject ) )
1147             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1148                                         SALOME::BAD_PARAM );
1149
1150           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
1151           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1152             {
1153               const TopoDS_Face& F = TopoDS::Face(exp.Current());
1154               setId.insert(myIndexToShape.FindIndex(F));
1155               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1156             }
1157           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1158             {
1159               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1160               setId.insert(myIndexToShape.FindIndex(E));
1161               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1162             }
1163           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1164             {
1165               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1166               setId.insert(myIndexToShape.FindIndex(V));
1167               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1168             }
1169         }
1170       shapesId->length(setId.size());
1171       set<int>::iterator iind;
1172       int i=0;
1173       for (iind = setId.begin(); iind != setId.end(); iind++)
1174         {
1175           if(MYDEBUG) SCRUTE((*iind));
1176           shapesId[i] = (*iind);
1177           if(MYDEBUG) SCRUTE(shapesId[i]);
1178           i++;
1179         }
1180     }
1181   catch (SALOME_Exception& S_ex)
1182     {
1183       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1184     }
1185
1186   return shapesId._retn();
1187 }
1188
1189 //=============================================================================
1190 /*!
1191  *  SMESH_Gen_i::Compute
1192  *
1193  *  Compute mesh on a shape
1194  */
1195 //=============================================================================
1196
1197 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1198                                      GEOM::GEOM_Object_ptr theShapeObject )
1199      throw ( SALOME::SALOME_Exception )
1200 {
1201   Unexpect aCatch(SALOME_SalomeException);
1202   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1203
1204   if ( CORBA::is_nil( theShapeObject ) )
1205     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
1206                                   SALOME::BAD_PARAM );
1207
1208   if ( CORBA::is_nil( theMesh ) )
1209     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1210                                   SALOME::BAD_PARAM );
1211
1212   // Update Python script
1213   TPythonDump() << "isDone = " << this << ".Compute( "
1214                 << theMesh << ", " << theShapeObject << ")";
1215   TPythonDump() << "if not isDone: print 'Mesh', " << theMesh << ", ': computation failed'";
1216
1217   try {
1218     // get mesh servant
1219     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1220     ASSERT( meshServant );
1221     if ( meshServant ) {
1222       // get local TopoDS_Shape
1223       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1224       // call implementation compute
1225       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1226       return myGen.Compute( myLocMesh, myLocShape);
1227     }
1228   }
1229   catch ( std::bad_alloc& exc ) {
1230     THROW_SALOME_CORBA_EXCEPTION( "Memory allocation problem",
1231                                   SALOME::INTERNAL_ERROR );
1232   }
1233   catch ( SALOME_Exception& S_ex ) {
1234     INFOS( "Compute(): catch exception "<< S_ex.what() );
1235   }
1236   catch ( ... ) {
1237     INFOS( "Compute(): unknown exception " );
1238   }
1239   return false;
1240 }
1241
1242 //================================================================================
1243 /*!
1244  * \brief Return geometrical object the given element is built on
1245  *  \param theMesh - the mesh the element is in
1246  *  \param theElementID - the element ID
1247  *  \param theGeomName - the name of the result geom object if it is not yet published
1248  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object
1249  */
1250 //================================================================================
1251
1252 GEOM::GEOM_Object_ptr
1253 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
1254                                        CORBA::Long            theElementID,
1255                                        const char*            theGeomName)
1256   throw ( SALOME::SALOME_Exception )
1257 {
1258   Unexpect aCatch(SALOME_SalomeException);
1259  
1260   GEOM::GEOM_Object_var geom = FindGeometryByMeshElement(theMesh, theElementID);
1261   if ( !geom->_is_nil() ) {
1262     GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1263     GEOM::GEOM_Gen_var    geomGen   = GetGeomEngine();
1264
1265     // try to find the corresponding SObject
1266     SALOMEDS::SObject_var SObj = ObjectToSObject( myCurrentStudy, geom.in() );
1267     if ( SObj->_is_nil() ) // submesh can be not found even if published
1268     {
1269       // try to find published submesh
1270       GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
1271       if ( !geom->IsMainShape() && list->length() == 1 ) {
1272         SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
1273         SALOMEDS::ChildIterator_var it;
1274         if ( !mainSO->_is_nil() )
1275           it = myCurrentStudy->NewChildIterator( mainSO );
1276         if ( !it->_is_nil() ) {
1277           for ( it->InitEx(true); SObj->_is_nil() && it->More(); it->Next() ) {
1278             GEOM::GEOM_Object_var subGeom =
1279               GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
1280             if ( !subGeom->_is_nil() ) {
1281               GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
1282               if ( subList->length() == 1 && list[0] == subList[0] ) {
1283                 SObj = it->Value();
1284                 geom = subGeom;
1285               }
1286             }
1287           }
1288         }
1289       }
1290     }
1291     if ( SObj->_is_nil() ) // publish a new subshape
1292       SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
1293
1294     // return only published geometry
1295     if ( !SObj->_is_nil() )
1296       return geom._retn();
1297   }
1298   return GEOM::GEOM_Object::_nil();
1299 }
1300
1301 //================================================================================
1302 /*!
1303  * \brief Return geometrical object the given element is built on.
1304  *  \param theMesh - the mesh the element is in
1305  *  \param theElementID - the element ID
1306  *  \retval GEOM::GEOM_Object_ptr - the found geom object
1307  */
1308 //================================================================================
1309
1310 GEOM::GEOM_Object_ptr
1311 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
1312                                         CORBA::Long            theElementID)
1313   throw ( SALOME::SALOME_Exception )
1314 {
1315   Unexpect aCatch(SALOME_SalomeException);
1316   if ( CORBA::is_nil( theMesh ) )
1317     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
1318
1319   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1320   GEOM::GEOM_Gen_var    geomGen   = GetGeomEngine();
1321
1322   // get a core mesh DS
1323   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1324   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
1325   {
1326     ::SMESH_Mesh & mesh = meshServant->GetImpl();
1327     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
1328     // find the element in mesh
1329     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) )
1330       // find a shape id by the element
1331       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
1332         // get a geom object by the shape id
1333         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
1334         if ( geom->_is_nil() ) {
1335           GEOM::GEOM_IShapesOperations_var op =
1336             geomGen->GetIShapesOperations( GetCurrentStudyID() );
1337           if ( !op->_is_nil() )
1338             geom = op->GetSubShape( mainShape, shapeID );
1339         }
1340         if ( !geom->_is_nil() ) {
1341           GeomObjectToShape( geom ); // let geom client remember the found shape
1342           return geom._retn();
1343         }
1344       }
1345   }
1346   return GEOM::GEOM_Object::_nil();
1347 }
1348
1349 //================================================================================
1350 /*!
1351  *  SMESH_Gen_i::Concatenate
1352  *
1353  *  Concatenate the given meshes into one mesh
1354  */
1355 //================================================================================
1356
1357 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::Concatenate(const SMESH::mesh_array& theMeshesArray,
1358                                                CORBA::Boolean           theUniteIdenticalGroups, 
1359                                                CORBA::Boolean           theMergeNodesAndElements, 
1360                                                CORBA::Double            theMergeTolerance)
1361   throw ( SALOME::SALOME_Exception )
1362 {
1363   typedef map<int, int> TIDsMap;
1364   typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
1365   typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
1366   typedef std::set<SMESHDS_GroupBase*> TGroups;
1367
1368   TPythonDump aPythonDump; // prevent dump of called methods
1369
1370   // create mesh
1371   SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
1372   
1373   if ( !aNewMesh->_is_nil() ) {
1374     SMESH_Mesh_i* aNewImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( aNewMesh ).in() );
1375     if ( aNewImpl ) {
1376       ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
1377       SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
1378
1379       TGroupsMap aGroupsMap;
1380       TListOfNewGroups aListOfNewGroups;
1381       SMESH_MeshEditor aNewEditor = ::SMESH_MeshEditor(&aLocMesh);
1382       SMESH::ListOfGroups_var aListOfGroups = new SMESH::ListOfGroups();
1383
1384       // loop on meshes
1385       for ( int i = 0; i < theMeshesArray.length(); i++) {
1386         SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i];
1387         if ( !anInitMesh->_is_nil() ) {
1388           SMESH_Mesh_i* anInitImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( anInitMesh ).in() );
1389           if ( anInitImpl ) {
1390             ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
1391             SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
1392
1393             TIDsMap nodesMap;
1394             TIDsMap elemsMap;
1395
1396             // loop on elements of mesh
1397             SMDS_ElemIteratorPtr itElems = anInitMeshDS->elementsIterator();
1398             const SMDS_MeshElement* anElem = 0;
1399             const SMDS_MeshElement* aNewElem = 0;
1400             int anElemNbNodes = 0;
1401
1402             for ( int j = 0; itElems->more(); j++) {
1403               anElem = itElems->next();
1404               SMDSAbs_ElementType anElemType = anElem->GetType();
1405               anElemNbNodes = anElem->NbNodes();
1406               std::vector<const SMDS_MeshNode*> aNodesArray (anElemNbNodes);
1407
1408               // loop on nodes of element
1409               const SMDS_MeshNode* aNode = 0;
1410               const SMDS_MeshNode* aNewNode = 0;
1411               SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
1412
1413               for ( int k = 0; itNodes->more(); k++) {
1414                 aNode = static_cast<const SMDS_MeshNode*>(itNodes->next());
1415                 if ( nodesMap.find(aNode->GetID()) == nodesMap.end() ) {
1416                   aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
1417                   nodesMap.insert( make_pair(aNode->GetID(), aNewNode->GetID()) );
1418                 }
1419                 else
1420                   aNewNode = aNewMeshDS->FindNode( nodesMap.find(aNode->GetID())->second );
1421                 aNodesArray[k] = aNewNode;
1422               }//nodes loop
1423
1424               // creates a corresponding element on existent nodes in new mesh
1425               if ( anElem->IsPoly() && anElemType == SMDSAbs_Volume )
1426                 {
1427                   const SMDS_PolyhedralVolumeOfNodes* aVolume =
1428                     dynamic_cast<const SMDS_PolyhedralVolumeOfNodes*> (anElem);
1429                   if ( aVolume ) {
1430                     aNewElem = aNewMeshDS->AddPolyhedralVolume(aNodesArray, 
1431                                                                aVolume->GetQuanities());
1432                     elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
1433                   }
1434                 }
1435               else {
1436                 
1437                 aNewElem = aNewEditor.AddElement(aNodesArray,
1438                                                  anElemType,
1439                                                  anElem->IsPoly());
1440                 elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
1441               } 
1442             }//elems loop
1443             
1444             aListOfGroups = anInitImpl->GetGroups();
1445             SMESH::SMESH_GroupBase_ptr aGroup;
1446
1447             // loop on groups of mesh
1448             SMESH::long_array_var anInitIDs = new SMESH::long_array();
1449             SMESH::long_array_var anNewIDs = new SMESH::long_array();
1450             SMESH::SMESH_Group_var aNewGroup;
1451             for (int i = 0; i < aListOfGroups->length(); i++) {
1452               aGroup = aListOfGroups[i];
1453               aListOfNewGroups.clear();
1454               SMESH::ElementType aGroupType = aGroup->GetType();
1455               CORBA::String_var aGroupName = aGroup->GetName();
1456               
1457               TGroupsMap::iterator anIter = aGroupsMap.find(make_pair(aGroupName, aGroupType));
1458
1459               // convert a list of IDs
1460               anInitIDs = aGroup->GetListOfID();
1461               anNewIDs->length(anInitIDs->length());
1462               if ( aGroupType == SMESH::NODE )
1463                 for (int j = 0; j < anInitIDs->length(); j++) {
1464                   anNewIDs[j] = nodesMap.find(anInitIDs[j])->second;
1465                 }
1466               else
1467                 for (int j = 0; j < anInitIDs->length(); j++) {
1468                   anNewIDs[j] = elemsMap.find(anInitIDs[j])->second;
1469                 }
1470               
1471               // check that current group name and type don't have identical ones in union mesh
1472               if ( anIter == aGroupsMap.end() ) {
1473                 // add a new group in the mesh
1474                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
1475                 // add elements into new group
1476                 aNewGroup->Add( anNewIDs );
1477                 
1478                 aListOfNewGroups.push_back(aNewGroup);
1479                 aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
1480               }
1481
1482               else if ( theUniteIdenticalGroups ) {
1483                 // unite identical groups
1484                 TListOfNewGroups& aNewGroups = anIter->second;
1485                 aNewGroups.front()->Add( anNewIDs );
1486               }
1487
1488               else {
1489                 // rename identical groups
1490                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
1491                 aNewGroup->Add( anNewIDs );
1492                 
1493                 TListOfNewGroups& aNewGroups = anIter->second;
1494                 string aNewGroupName;
1495                 if (aNewGroups.size() == 1) {
1496                   aNewGroupName = string(aGroupName) + "_1";
1497                   aNewGroups.front()->SetName(aNewGroupName.c_str());
1498                 }
1499                 char aGroupNum[128];
1500                 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
1501                 aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
1502                 aNewGroup->SetName(aNewGroupName.c_str());
1503                 aNewGroups.push_back(aNewGroup);
1504               }
1505             }//groups loop
1506           }
1507         }
1508       }//meshes loop
1509
1510       if (theMergeNodesAndElements) {
1511         // merge nodes
1512         set<const SMDS_MeshNode*> aMeshNodes; // no input nodes
1513         SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
1514         aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes );
1515         aNewEditor.MergeNodes( aGroupsOfNodes );
1516         // merge elements
1517         aNewEditor.MergeEqualElements();
1518       }
1519     }
1520   }
1521   
1522   // Update Python script
1523   aPythonDump << aNewMesh << " = " << this << ".Concatenate(";
1524   aPythonDump << "[";
1525   for ( int i = 0; i < theMeshesArray.length(); i++) {
1526     if (i > 0) aPythonDump << ", ";
1527     aPythonDump << theMeshesArray[i];
1528   }
1529   aPythonDump << "], ";
1530   aPythonDump << theUniteIdenticalGroups << ", "
1531               << theMergeNodesAndElements << ", "
1532               << theMergeTolerance << ")";
1533
1534   return aNewMesh._retn();
1535 }
1536
1537 //=============================================================================
1538 /*!
1539  *  SMESH_Gen_i::Save
1540  *
1541  *  Save SMESH module's data
1542  */
1543 //=============================================================================
1544 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
1545                                       const char*              theURL,
1546                                       bool                     isMultiFile )
1547 {
1548   INFOS( "SMESH_Gen_i::Save" );
1549
1550   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
1551   // san -- in case <myCurrentStudy> differs from theComponent's study,
1552   // use that of the component
1553   if ( myCurrentStudy->_is_nil() || 
1554     theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
1555     SetCurrentStudy( theComponent->GetStudy() );
1556
1557   // Store study contents as a set of python commands
1558   SavePython(myCurrentStudy);
1559
1560   StudyContext* myStudyContext = GetCurrentStudyContext();
1561
1562   // Declare a byte stream
1563   SALOMEDS::TMPFile_var aStreamFile;
1564
1565   // Obtain a temporary dir
1566   TCollection_AsciiString tmpDir =
1567     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
1568
1569   // Create a sequence of files processed
1570   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
1571   aFileSeq->length( NUM_TMP_FILES );
1572
1573   TCollection_AsciiString aStudyName( "" );
1574   if ( isMultiFile ) 
1575     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
1576
1577   // Set names of temporary files
1578   TCollection_AsciiString filename =
1579     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
1580   TCollection_AsciiString meshfile =
1581     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
1582   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
1583   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
1584   filename = tmpDir + filename;
1585   meshfile = tmpDir + meshfile;
1586
1587   HDFfile*    aFile;
1588   HDFdataset* aDataset;
1589   HDFgroup*   aTopGroup;
1590   HDFgroup*   aGroup;
1591   HDFgroup*   aSubGroup;
1592   HDFgroup*   aSubSubGroup;
1593   hdf_size    aSize[ 1 ];
1594
1595
1596   //Remove the files if they exist: BugID: 11225
1597 #ifndef WNT /* unix functionality */
1598   TCollection_AsciiString cmd("rm -f \"");
1599 #else /* windows */
1600   TCollection_AsciiString cmd("del /F \"");
1601 #endif
1602
1603   cmd+=filename;
1604   cmd+="\" \"";
1605   cmd+=meshfile;
1606   cmd+="\"";
1607   system(cmd.ToCString());
1608
1609   // MED writer to be used by storage process
1610   DriverMED_W_SMESHDS_Mesh myWriter;
1611   myWriter.SetFile( meshfile.ToCString() );
1612
1613   // Write data
1614   // ---> create HDF file
1615   aFile = new HDFfile( filename.ToCString() );
1616   aFile->CreateOnDisk();
1617
1618   // --> iterator for top-level objects
1619   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
1620   for ( ; itBig->More(); itBig->Next() ) {
1621     SALOMEDS::SObject_var gotBranch = itBig->Value();
1622
1623     // --> hypotheses root branch (only one for the study)
1624     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
1625       // create hypotheses root HDF group
1626       aTopGroup = new HDFgroup( "Hypotheses", aFile );
1627       aTopGroup->CreateOnDisk();
1628
1629       // iterator for all hypotheses
1630       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1631       for ( ; it->More(); it->Next() ) {
1632         SALOMEDS::SObject_var mySObject = it->Value();
1633         CORBA::Object_var anObject = SObjectToObject( mySObject );
1634         if ( !CORBA::is_nil( anObject ) ) {
1635           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1636           if ( !myHyp->_is_nil() ) {
1637             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1638             if ( myImpl ) {
1639               string hypname = string( myHyp->GetName() );
1640               string libname = string( myHyp->GetLibName() );
1641               // BUG SWP13062
1642               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
1643               // WNT and ".so" for X-system) must be deleted
1644               int libname_len = libname.length();
1645 #ifdef WNT
1646               if( libname_len > 4 )
1647                 libname.resize( libname_len - 4 );
1648 #else
1649               if( libname_len > 3 )
1650                 libname.resize( libname_len - 3 );
1651 #endif
1652               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1653               int    id      = myStudyContext->findId( string( objStr.in() ) );
1654               string hypdata = string( myImpl->SaveTo() );
1655
1656               // for each hypothesis create HDF group basing on its id
1657               char hypGrpName[30];
1658               sprintf( hypGrpName, "Hypothesis %d", id );
1659               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1660               aGroup->CreateOnDisk();
1661               // --> type name of hypothesis
1662               aSize[ 0 ] = hypname.length() + 1;
1663               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1664               aDataset->CreateOnDisk();
1665               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1666               aDataset->CloseOnDisk();
1667               // --> server plugin library name of hypothesis
1668               aSize[ 0 ] = libname.length() + 1;
1669               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1670               aDataset->CreateOnDisk();
1671               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1672               aDataset->CloseOnDisk();
1673               // --> persistent data of hypothesis
1674               aSize[ 0 ] = hypdata.length() + 1;
1675               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1676               aDataset->CreateOnDisk();
1677               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1678               aDataset->CloseOnDisk();
1679               // close hypothesis HDF group
1680               aGroup->CloseOnDisk();
1681             }
1682           }
1683         }
1684       }
1685       // close hypotheses root HDF group
1686       aTopGroup->CloseOnDisk();
1687     }
1688     // --> algorithms root branch (only one for the study)
1689     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1690       // create algorithms root HDF group
1691       aTopGroup = new HDFgroup( "Algorithms", aFile );
1692       aTopGroup->CreateOnDisk();
1693
1694       // iterator for all algorithms
1695       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1696       for ( ; it->More(); it->Next() ) {
1697         SALOMEDS::SObject_var mySObject = it->Value();
1698         CORBA::Object_var anObject = SObjectToObject( mySObject );
1699         if ( !CORBA::is_nil( anObject ) ) {
1700           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1701           if ( !myHyp->_is_nil() ) {
1702             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1703             if ( myImpl ) {
1704               string hypname = string( myHyp->GetName() );
1705               string libname = string( myHyp->GetLibName() );
1706               // BUG SWP13062
1707               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
1708               // WNT and ".so" for X-system) must be deleted
1709               int libname_len = libname.length();
1710 #ifdef WNT
1711               if( libname_len > 4 )
1712                 libname.resize( libname_len - 4 );
1713 #else
1714               if( libname_len > 3 )
1715                 libname.resize( libname_len - 3 );
1716 #endif
1717               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1718               int    id      = myStudyContext->findId( string( objStr.in() ) );
1719               string hypdata = string( myImpl->SaveTo() );
1720
1721               // for each algorithm create HDF group basing on its id
1722               char hypGrpName[30];
1723               sprintf( hypGrpName, "Algorithm %d", id );
1724               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1725               aGroup->CreateOnDisk();
1726               // --> type name of algorithm
1727               aSize[0] = hypname.length() + 1;
1728               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1729               aDataset->CreateOnDisk();
1730               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1731               aDataset->CloseOnDisk();
1732               // --> server plugin library name of hypothesis
1733               aSize[0] = libname.length() + 1;
1734               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1735               aDataset->CreateOnDisk();
1736               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1737               aDataset->CloseOnDisk();
1738               // --> persistent data of algorithm
1739               aSize[0] = hypdata.length() + 1;
1740               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1741               aDataset->CreateOnDisk();
1742               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1743               aDataset->CloseOnDisk();
1744               // close algorithm HDF group
1745               aGroup->CloseOnDisk();
1746             }
1747           }
1748         }
1749       }
1750       // close algorithms root HDF group
1751       aTopGroup->CloseOnDisk();
1752     }
1753     // --> mesh objects roots branches
1754     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
1755       CORBA::Object_var anObject = SObjectToObject( gotBranch );
1756       if ( !CORBA::is_nil( anObject ) ) {
1757         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
1758         if ( !myMesh->_is_nil() ) {
1759           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
1760           if ( myImpl ) {
1761             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1762             int id = myStudyContext->findId( string( objStr.in() ) );
1763             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
1764             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
1765
1766             // for each mesh open the HDF group basing on its id
1767             char meshGrpName[ 30 ];
1768             sprintf( meshGrpName, "Mesh %d", id );
1769             aTopGroup = new HDFgroup( meshGrpName, aFile );
1770             aTopGroup->CreateOnDisk();
1771
1772             // --> put dataset to hdf file which is a flag that mesh has data
1773             string strHasData = "0";
1774             // check if the mesh is not empty
1775             if ( mySMESHDSMesh->NbNodes() > 0 ) {
1776               // write mesh data to med file
1777               myWriter.SetMesh( mySMESHDSMesh );
1778               myWriter.SetMeshId( id );
1779               strHasData = "1";
1780             }
1781             aSize[ 0 ] = strHasData.length() + 1;
1782             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
1783             aDataset->CreateOnDisk();
1784             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
1785             aDataset->CloseOnDisk();
1786
1787             // write reference on a shape if exists
1788             SALOMEDS::SObject_var myRef;
1789             bool shapeRefFound = false;
1790             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
1791             if ( found ) {
1792               SALOMEDS::SObject_var myShape;
1793               bool ok = myRef->ReferencedObject( myShape );
1794               if ( ok ) {
1795                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
1796                 string myRefOnObject = myShape->GetID();
1797                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
1798                   aSize[ 0 ] = myRefOnObject.length() + 1;
1799                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
1800                   aDataset->CreateOnDisk();
1801                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1802                   aDataset->CloseOnDisk();
1803                 }
1804               }
1805             }
1806
1807             // write applied hypotheses if exist
1808             SALOMEDS::SObject_var myHypBranch;
1809             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
1810             if ( found && !shapeRefFound ) { // remove applied hyps
1811               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
1812             }
1813             if ( found && shapeRefFound ) {
1814               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
1815               aGroup->CreateOnDisk();
1816
1817               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
1818               int hypNb = 0;
1819               for ( ; it->More(); it->Next() ) {
1820                 SALOMEDS::SObject_var mySObject = it->Value();
1821                 SALOMEDS::SObject_var myRefOnHyp;
1822                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
1823                 if ( ok ) {
1824                   // san - it is impossible to recover applied hypotheses
1825                   //       using their entries within Load() method,
1826                   // for there are no AttributeIORs in the study when Load() is working. 
1827                   // Hence, it is better to store persistent IDs of hypotheses as references to them
1828
1829                   //string myRefOnObject = myRefOnHyp->GetID();
1830                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1831                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1832                   int id = myStudyContext->findId( string( objStr.in() ) );
1833                   //if ( myRefOnObject.length() > 0 ) {
1834                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1835                   char hypName[ 30 ], hypId[ 30 ];
1836                   sprintf( hypName, "Hyp %d", ++hypNb );
1837                   sprintf( hypId, "%d", id );
1838                   aSize[ 0 ] = strlen( hypId ) + 1;
1839                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
1840                   aDataset->CreateOnDisk();
1841                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1842                   aDataset->WriteOnDisk( hypId );
1843                   aDataset->CloseOnDisk();
1844                   //}
1845                 }
1846               }
1847               aGroup->CloseOnDisk();
1848             }
1849
1850             // write applied algorithms if exist
1851             SALOMEDS::SObject_var myAlgoBranch;
1852             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
1853             if ( found && !shapeRefFound ) { // remove applied algos
1854               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
1855             }
1856             if ( found && shapeRefFound ) {
1857               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
1858               aGroup->CreateOnDisk();
1859
1860               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
1861               int algoNb = 0;
1862               for ( ; it->More(); it->Next() ) {
1863                 SALOMEDS::SObject_var mySObject = it->Value();
1864                 SALOMEDS::SObject_var myRefOnAlgo;
1865                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
1866                 if ( ok ) {
1867                   // san - it is impossible to recover applied algorithms
1868                   //       using their entries within Load() method,
1869                   // for there are no AttributeIORs in the study when Load() is working. 
1870                   // Hence, it is better to store persistent IDs of algorithms as references to them
1871
1872                   //string myRefOnObject = myRefOnAlgo->GetID();
1873                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1874                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1875                   int id = myStudyContext->findId( string( objStr.in() ) );
1876                   //if ( myRefOnObject.length() > 0 ) {
1877                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1878                   char algoName[ 30 ], algoId[ 30 ];
1879                   sprintf( algoName, "Algo %d", ++algoNb );
1880                   sprintf( algoId, "%d", id );
1881                   aSize[ 0 ] = strlen( algoId ) + 1;
1882                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
1883                   aDataset->CreateOnDisk();
1884                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1885                   aDataset->WriteOnDisk( algoId );
1886                   aDataset->CloseOnDisk();
1887                   //}
1888                 }
1889               }
1890               aGroup->CloseOnDisk();
1891             }
1892
1893             // --> submesh objects sub-branches
1894
1895             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
1896               SALOMEDS::SObject_var mySubmeshBranch;
1897               found = gotBranch->FindSubObject( i, mySubmeshBranch );
1898
1899               if ( found ) // check if there is shape reference in submeshes
1900               {
1901                 bool hasShapeRef = false;
1902                 SALOMEDS::ChildIterator_var itSM =
1903                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
1904                 for ( ; itSM->More(); itSM->Next() ) {
1905                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
1906                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1907                     mySubRef->ReferencedObject( myShape );
1908                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
1909                     hasShapeRef = true;
1910                   else
1911                   { // remove one submesh
1912                     if ( shapeRefFound )
1913                     { // unassign hypothesis
1914                       SMESH::SMESH_subMesh_var mySubMesh =
1915                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
1916                       if ( !mySubMesh->_is_nil() ) {
1917                         int shapeID = mySubMesh->GetId();
1918                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
1919                         const list<const SMESHDS_Hypothesis*>& hypList =
1920                           mySMESHDSMesh->GetHypothesis( S );
1921                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
1922                         while ( hyp != hypList.end() ) {
1923                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
1924                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
1925                         }
1926                       }
1927                     }
1928                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
1929                   }
1930                 } // loop on submeshes of a type
1931                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
1932                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
1933                   found = false;
1934                 }
1935               }  // end check if there is shape reference in submeshes
1936               if ( found ) {
1937                 char name_meshgroup[ 30 ];
1938                 if ( i == GetSubMeshOnVertexTag() )
1939                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
1940                 else if ( i == GetSubMeshOnEdgeTag() )
1941                   strcpy( name_meshgroup, "SubMeshes On Edge" );
1942                 else if ( i == GetSubMeshOnWireTag() )
1943                   strcpy( name_meshgroup, "SubMeshes On Wire" );
1944                 else if ( i == GetSubMeshOnFaceTag() )
1945                   strcpy( name_meshgroup, "SubMeshes On Face" );
1946                 else if ( i == GetSubMeshOnShellTag() )
1947                   strcpy( name_meshgroup, "SubMeshes On Shell" );
1948                 else if ( i == GetSubMeshOnSolidTag() )
1949                   strcpy( name_meshgroup, "SubMeshes On Solid" );
1950                 else if ( i == GetSubMeshOnCompoundTag() )
1951                   strcpy( name_meshgroup, "SubMeshes On Compound" );
1952
1953                 // for each type of submeshes create container HDF group
1954                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
1955                 aGroup->CreateOnDisk();
1956
1957                 // iterator for all submeshes of given type
1958                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
1959                 for ( ; itSM->More(); itSM->Next() ) {
1960                   SALOMEDS::SObject_var mySObject = itSM->Value();
1961                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
1962                   if ( !CORBA::is_nil( anSubObject ))
1963                   {
1964                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
1965                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
1966                     int subid = myStudyContext->findId( string( objStr.in() ) );
1967
1968                     // for each mesh open the HDF group basing on its id
1969                     char submeshGrpName[ 30 ];
1970                     sprintf( submeshGrpName, "SubMesh %d", subid );
1971                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
1972                     aSubGroup->CreateOnDisk();
1973
1974                     // write reference on a shape, already checked if it exists
1975                     SALOMEDS::SObject_var mySubRef, myShape;
1976                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1977                       mySubRef->ReferencedObject( myShape );
1978                     string myRefOnObject = myShape->GetID();
1979                     if ( myRefOnObject.length() > 0 ) {
1980                       aSize[ 0 ] = myRefOnObject.length() + 1;
1981                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
1982                       aDataset->CreateOnDisk();
1983                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1984                       aDataset->CloseOnDisk();
1985                     }
1986
1987                     // write applied hypotheses if exist
1988                     SALOMEDS::SObject_var mySubHypBranch;
1989                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
1990                     if ( found ) {
1991                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
1992                       aSubSubGroup->CreateOnDisk();
1993
1994                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
1995                       int hypNb = 0;
1996                       for ( ; it->More(); it->Next() ) {
1997                         SALOMEDS::SObject_var mySubSObject = it->Value();
1998                         SALOMEDS::SObject_var myRefOnHyp;
1999                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
2000                         if ( ok ) {
2001                           //string myRefOnObject = myRefOnHyp->GetID();
2002                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
2003                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2004                           int id = myStudyContext->findId( string( objStr.in() ) );
2005                           //if ( myRefOnObject.length() > 0 ) {
2006                           //aSize[ 0 ] = myRefOnObject.length() + 1;
2007                           char hypName[ 30 ], hypId[ 30 ];
2008                           sprintf( hypName, "Hyp %d", ++hypNb );
2009                           sprintf( hypId, "%d", id );
2010                           aSize[ 0 ] = strlen( hypId ) + 1;
2011                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
2012                           aDataset->CreateOnDisk();
2013                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2014                           aDataset->WriteOnDisk( hypId );
2015                           aDataset->CloseOnDisk();
2016                           //}
2017                         }
2018                       }
2019                       aSubSubGroup->CloseOnDisk();
2020                     }
2021
2022                     // write applied algorithms if exist
2023                     SALOMEDS::SObject_var mySubAlgoBranch;
2024                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
2025                     if ( found ) {
2026                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
2027                       aSubSubGroup->CreateOnDisk();
2028
2029                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
2030                       int algoNb = 0;
2031                       for ( ; it->More(); it->Next() ) {
2032                         SALOMEDS::SObject_var mySubSObject = it->Value();
2033                         SALOMEDS::SObject_var myRefOnAlgo;
2034                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
2035                         if ( ok ) {
2036                           //string myRefOnObject = myRefOnAlgo->GetID();
2037                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
2038                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2039                           int id = myStudyContext->findId( string( objStr.in() ) );
2040                           //if ( myRefOnObject.length() > 0 ) {
2041                           //aSize[ 0 ] = myRefOnObject.length() + 1;
2042                           char algoName[ 30 ], algoId[ 30 ];
2043                           sprintf( algoName, "Algo %d", ++algoNb );
2044                           sprintf( algoId, "%d", id );
2045                           aSize[ 0 ] = strlen( algoId ) + 1;
2046                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
2047                           aDataset->CreateOnDisk();
2048                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2049                           aDataset->WriteOnDisk( algoId );
2050                           aDataset->CloseOnDisk();
2051                           //}
2052                         }
2053                       }
2054                       aSubSubGroup->CloseOnDisk();
2055                     }
2056                     // close submesh HDF group
2057                     aSubGroup->CloseOnDisk();
2058                   }
2059                 }
2060                 // close container of submeshes by type HDF group
2061                 aGroup->CloseOnDisk();
2062               }
2063             }
2064             // All sub-meshes will be stored in MED file
2065             // .. will NOT (PAL 12992)
2066             //if ( shapeRefFound )
2067             //myWriter.AddAllSubMeshes();
2068
2069             // groups root sub-branch
2070             SALOMEDS::SObject_var myGroupsBranch;
2071             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
2072               found = gotBranch->FindSubObject( i, myGroupsBranch );
2073               if ( found ) {
2074                 char name_group[ 30 ];
2075                 if ( i == GetNodeGroupsTag() )
2076                   strcpy( name_group, "Groups of Nodes" );
2077                 else if ( i == GetEdgeGroupsTag() )
2078                   strcpy( name_group, "Groups of Edges" );
2079                 else if ( i == GetFaceGroupsTag() )
2080                   strcpy( name_group, "Groups of Faces" );
2081                 else if ( i == GetVolumeGroupsTag() )
2082                   strcpy( name_group, "Groups of Volumes" );
2083
2084                 aGroup = new HDFgroup( name_group, aTopGroup );
2085                 aGroup->CreateOnDisk();
2086
2087                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
2088                 for ( ; it->More(); it->Next() ) {
2089                   SALOMEDS::SObject_var mySObject = it->Value();
2090                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
2091                   if ( !CORBA::is_nil( aSubObject ) ) {
2092                     SMESH_GroupBase_i* myGroupImpl =
2093                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
2094                     if ( !myGroupImpl )
2095                       continue;
2096                     
2097                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
2098                     int anId = myStudyContext->findId( string( objStr.in() ) );
2099                     
2100                     // For each group, create a dataset named "Group <group_persistent_id>"
2101                     // and store the group's user name into it
2102                     char grpName[ 30 ];
2103                     sprintf( grpName, "Group %d", anId );
2104                     char* aUserName = myGroupImpl->GetName();
2105                     aSize[ 0 ] = strlen( aUserName ) + 1;
2106                     
2107                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
2108                     aDataset->CreateOnDisk();
2109                     aDataset->WriteOnDisk( aUserName );
2110                     aDataset->CloseOnDisk();
2111
2112                     // Store the group contents into MED file
2113                     if ( myLocMesh.GetGroup( myGroupImpl->GetLocalID() ) ) {
2114                       
2115                       if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen_i::Save(): saving group with StoreName = "
2116                                           << grpName << " to MED file" );
2117                       SMESHDS_GroupBase* aGrpBaseDS =
2118                         myLocMesh.GetGroup( myGroupImpl->GetLocalID() )->GetGroupDS();
2119                       aGrpBaseDS->SetStoreName( grpName );
2120
2121                       // Pass SMESHDS_Group to MED writer 
2122                       SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
2123                       if ( aGrpDS )
2124                         myWriter.AddGroup( aGrpDS );
2125                       
2126                       // write reference on a shape if exists
2127                       SMESHDS_GroupOnGeom* aGeomGrp =
2128                         dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
2129                       if ( aGeomGrp ) {
2130                         SALOMEDS::SObject_var mySubRef, myShape;
2131                         if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
2132                             mySubRef->ReferencedObject( myShape ) &&
2133                             !CORBA::is_nil( myShape->GetObject() ))
2134                         {
2135                           string myRefOnObject = myShape->GetID();
2136                           if ( myRefOnObject.length() > 0 ) {
2137                             char aRefName[ 30 ];
2138                             sprintf( aRefName, "Ref on shape %d", anId);
2139                             aSize[ 0 ] = myRefOnObject.length() + 1;
2140                             aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
2141                             aDataset->CreateOnDisk();
2142                             aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2143                             aDataset->CloseOnDisk();
2144                           }
2145                         }
2146                         else // shape ref is invalid:
2147                         {
2148                           // save a group on geometry as ordinary group
2149                           myWriter.AddGroup( aGeomGrp );
2150                         }
2151                       }
2152                     }
2153                   }
2154                 }
2155                 aGroup->CloseOnDisk();
2156               }
2157             } // loop on groups 
2158             
2159             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
2160             {
2161               // Flush current mesh information into MED file
2162               myWriter.Perform();
2163               
2164               // maybe a shape was deleted in the study
2165               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() ) {
2166                 TopoDS_Shape nullShape;
2167                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
2168               }
2169               
2170               if ( !mySMESHDSMesh->SubMeshes().empty() )
2171               {
2172                 // Store submeshes
2173                 // ----------------
2174                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
2175                 aGroup->CreateOnDisk();
2176                 
2177                 // each element belongs to one or none submesh,
2178                 // so for each node/element, we store a submesh ID
2179                 
2180                 // Make maps of submesh IDs of elements sorted by element IDs
2181                 typedef int TElemID;
2182                 typedef int TSubMID;
2183                 map< TElemID, TSubMID > eId2smId, nId2smId;
2184                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
2185                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
2186                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
2187                 SMDS_NodeIteratorPtr itNode;
2188                 SMDS_ElemIteratorPtr itElem;
2189                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
2190                 {
2191                   TSubMID          aSubMeID = itSubM->first;
2192                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
2193                   if ( aSubMesh->IsComplexSubmesh() )
2194                     continue; // submesh containing other submeshs
2195                   // nodes
2196                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
2197                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
2198                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
2199                   // elements
2200                   hint = eId2smId.begin();
2201                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
2202                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
2203                 }
2204                 
2205                 // Care of elements that are not on submeshes
2206                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
2207                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
2208                     /*  --- stl_map.h says : */
2209                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
2210                     /*  first element (the key) is not already present in the %map.           */
2211                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
2212                 }
2213                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
2214                 if ( nbElems != eId2smId.size() ) {
2215                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
2216                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
2217                 }
2218                 
2219                 // Store submesh IDs
2220                 for ( int isNode = 0; isNode < 2; ++isNode )
2221                 {
2222                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
2223                   if ( id2smId.empty() ) continue;
2224                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
2225                   // make and fill array of submesh IDs
2226                   int* smIDs = new int [ id2smId.size() ];
2227                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
2228                     smIDs[ i ] = id_smId->second;
2229                   // write HDF group
2230                   aSize[ 0 ] = id2smId.size();
2231                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
2232                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
2233                   aDataset->CreateOnDisk();
2234                   aDataset->WriteOnDisk( smIDs );
2235                   aDataset->CloseOnDisk();
2236                   //
2237                   delete smIDs;
2238                 }
2239                 
2240                 // Store node positions on sub-shapes (SMDS_Position):
2241                 // ----------------------------------------------------
2242                 
2243                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
2244                 aGroup->CreateOnDisk();
2245                 
2246                 // in aGroup, create 5 datasets to contain:
2247                 // "Nodes on Edges" - ID of node on edge
2248                 // "Edge positions" - U parameter on node on edge
2249                 // "Nodes on Faces" - ID of node on face
2250                 // "Face U positions" - U parameter of node on face
2251                 // "Face V positions" - V parameter of node on face
2252                 
2253                 // Find out nb of nodes on edges and faces
2254                 // Collect corresponing sub-meshes
2255                 int nbEdgeNodes = 0, nbFaceNodes = 0;
2256                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
2257                 // loop on SMESHDS_SubMesh'es
2258                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
2259                 {
2260                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
2261                   if ( aSubMesh->IsComplexSubmesh() )
2262                     continue; // submesh containing other submeshs
2263                   int nbNodes = aSubMesh->NbNodes();
2264                   if ( nbNodes == 0 ) continue;
2265                   
2266                   int aShapeID = (*itSubM).first;
2267                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
2268                   // write only SMDS_FacePosition and SMDS_EdgePosition
2269                   switch ( aShapeType ) {
2270                   case TopAbs_FACE:
2271                     nbFaceNodes += nbNodes;
2272                     aFaceSM.push_back( aSubMesh );
2273                     break;
2274                   case TopAbs_EDGE:
2275                     nbEdgeNodes += nbNodes;
2276                     aEdgeSM.push_back( aSubMesh );
2277                     break;
2278                   default:
2279                     continue;
2280                   }
2281                 }
2282                 // Treat positions on edges or faces
2283                 for ( int onFace = 0; onFace < 2; onFace++ )
2284                 {
2285                   // Create arrays to store in datasets
2286                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
2287                   if (!nbNodes) continue;
2288                   int* aNodeIDs = new int [ nbNodes ];
2289                   double* aUPos = new double [ nbNodes ];
2290                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
2291                   
2292                   // Fill arrays
2293                   // loop on sub-meshes
2294                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
2295                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
2296                   for ( ; itSM != pListSM->end(); itSM++ )
2297                   {
2298                     SMESHDS_SubMesh* aSubMesh = (*itSM);
2299                     
2300                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
2301                     // loop on nodes in aSubMesh
2302                     while ( itNode->more() )
2303                     {
2304                       //node ID
2305                       const SMDS_MeshNode* node = itNode->next();
2306                       aNodeIDs [ iNode ] = node->GetID();
2307                       
2308                       // Position
2309                       const SMDS_PositionPtr pos = node->GetPosition();
2310                       if ( onFace ) { // on FACE
2311                         const SMDS_FacePosition* fPos =
2312                           dynamic_cast<const SMDS_FacePosition*>( pos.get() );
2313                         if ( fPos ) {
2314                           aUPos[ iNode ] = fPos->GetUParameter();
2315                           aVPos[ iNode ] = fPos->GetVParameter();
2316                           iNode++;
2317                         }
2318                         else
2319                           nbNodes--;
2320                       }
2321                       else { // on EDGE
2322                         const SMDS_EdgePosition* ePos =
2323                           dynamic_cast<const SMDS_EdgePosition*>( pos.get() );
2324                         if ( ePos ) {
2325                           aUPos[ iNode ] = ePos->GetUParameter();
2326                           iNode++;
2327                         }
2328                         else
2329                           nbNodes--;
2330                       }
2331                     } // loop on nodes in aSubMesh
2332                   } // loop on sub-meshes
2333                   
2334                   // Write datasets
2335                   if ( nbNodes )
2336                   {
2337                     aSize[ 0 ] = nbNodes;
2338                     // IDS
2339                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
2340                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
2341                     aDataset->CreateOnDisk();
2342                     aDataset->WriteOnDisk( aNodeIDs );
2343                     aDataset->CloseOnDisk();
2344                 
2345                     // U Positions
2346                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
2347                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
2348                     aDataset->CreateOnDisk();
2349                     aDataset->WriteOnDisk( aUPos );
2350                     aDataset->CloseOnDisk();
2351                     // V Positions
2352                     if ( onFace ) {
2353                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
2354                       aDataset->CreateOnDisk();
2355                       aDataset->WriteOnDisk( aVPos );
2356                       aDataset->CloseOnDisk();
2357                     }
2358                   }
2359                   delete [] aNodeIDs;
2360                   delete [] aUPos;
2361                   if ( aVPos ) delete [] aVPos;
2362                   
2363                 } // treat positions on edges or faces
2364                 
2365                 // close "Node Positions" group
2366                 aGroup->CloseOnDisk(); 
2367                 
2368               } // if ( there are submeshes in SMESHDS_Mesh )
2369             } // if ( hasData )
2370             
2371             // close mesh HDF group
2372             aTopGroup->CloseOnDisk();
2373           }
2374         }
2375       }
2376     }
2377   }
2378   
2379   // close HDF file
2380   aFile->CloseOnDisk();
2381   delete aFile;
2382
2383   // Convert temporary files to stream
2384   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
2385
2386   // Remove temporary files and directory
2387   if ( !isMultiFile ) 
2388     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
2389
2390   INFOS( "SMESH_Gen_i::Save() completed" );
2391   return aStreamFile._retn();
2392 }
2393
2394 //=============================================================================
2395 /*!
2396  *  SMESH_Gen_i::SaveASCII
2397  *
2398  *  Save SMESH module's data in ASCII format
2399  */
2400 //=============================================================================
2401
2402 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
2403                                            const char*              theURL,
2404                                            bool                     isMultiFile ) {
2405   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
2406   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
2407   return aStreamFile._retn();
2408
2409   //after usual saving needs to encipher binary to text string
2410   //Any binary symbol will be represent as "|xx" () hexadecimal format number
2411   int size = aStreamFile.in().length();
2412   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
2413   for ( int i = 0; i < size; i++ )
2414     sprintf( (char*)&(buffer[i*3]), "|%02x", (char*)(aStreamFile[i]) );
2415
2416   buffer[size * 3] = '\0';
2417
2418   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
2419   
2420   return anAsciiStreamFile._retn();
2421 }
2422
2423 //=============================================================================
2424 /*!
2425  *  SMESH_Gen_i::loadGeomData
2426  *
2427  *  Load GEOM module data
2428  */
2429 //=============================================================================
2430
2431 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
2432 {
2433   if ( theCompRoot->_is_nil() )
2434     return;
2435
2436   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
2437   if ( aStudy->_is_nil() )
2438     return;
2439
2440   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
2441   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
2442 }
2443 //=============================================================================
2444 /*!
2445  * \brief Creates SMDS_Position according to shape type
2446  */
2447 //=============================================================================
2448
2449 class PositionCreator {
2450 public:
2451   SMDS_PositionPtr MakePosition(const TopAbs_ShapeEnum type) {
2452     return (this->*myFuncTable[ type ])();
2453   }
2454   PositionCreator() {
2455     myFuncTable.resize( (size_t) TopAbs_SHAPE, & PositionCreator::defaultPosition );
2456     myFuncTable[ TopAbs_FACE ] = & PositionCreator::facePosition;
2457     myFuncTable[ TopAbs_EDGE ] = & PositionCreator::edgePosition;
2458     myFuncTable[ TopAbs_VERTEX ] = & PositionCreator::vertexPosition;
2459   }
2460 private:
2461   SMDS_PositionPtr edgePosition()    const { return SMDS_PositionPtr( new SMDS_EdgePosition  ); }
2462   SMDS_PositionPtr facePosition()    const { return SMDS_PositionPtr( new SMDS_FacePosition  ); }
2463   SMDS_PositionPtr vertexPosition()  const { return SMDS_PositionPtr( new SMDS_VertexPosition); }
2464   SMDS_PositionPtr defaultPosition() const { return SMDS_SpacePosition::originSpacePosition();  }
2465   typedef SMDS_PositionPtr (PositionCreator:: * FmakePos)() const;
2466   vector<FmakePos> myFuncTable;
2467 };
2468
2469 //=============================================================================
2470 /*!
2471  *  SMESH_Gen_i::Load
2472  *
2473  *  Load SMESH module's data
2474  */
2475 //=============================================================================
2476
2477 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
2478                         const SALOMEDS::TMPFile& theStream,
2479                         const char*              theURL,
2480                         bool                     isMultiFile )
2481 {
2482   INFOS( "SMESH_Gen_i::Load" );
2483
2484   if ( myCurrentStudy->_is_nil() || 
2485        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2486     SetCurrentStudy( theComponent->GetStudy() );
2487
2488   /*  if( !theComponent->_is_nil() )
2489       {
2490       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
2491       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
2492       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
2493       }*/
2494
2495   StudyContext* myStudyContext = GetCurrentStudyContext();
2496
2497   // Get temporary files location
2498   TCollection_AsciiString tmpDir =
2499     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2500     
2501     INFOS( "THE URL++++++++++++++" )
2502     INFOS( theURL );
2503     INFOS( "THE TMP PATH+++++++++" );
2504     INFOS( tmpDir );
2505
2506   // Convert the stream into sequence of files to process
2507   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
2508                                                                             tmpDir.ToCString(),
2509                                                                             isMultiFile );
2510   TCollection_AsciiString aStudyName( "" );
2511   if ( isMultiFile ) 
2512     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2513
2514   // Set names of temporary files
2515   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
2516   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
2517
2518   int size;
2519   HDFfile*    aFile;
2520   HDFdataset* aDataset;
2521   HDFgroup*   aTopGroup;
2522   HDFgroup*   aGroup;
2523   HDFgroup*   aSubGroup;
2524   HDFgroup*   aSubSubGroup;
2525
2526   // Read data
2527   // ---> open HDF file
2528   aFile = new HDFfile( filename.ToCString() );
2529   try {
2530     aFile->OpenOnDisk( HDF_RDONLY );
2531   }
2532   catch ( HDFexception ) {
2533     INFOS( "Load(): " << filename << " not found!" );
2534     return false;
2535   }
2536
2537   DriverMED_R_SMESHDS_Mesh myReader;
2538   myReader.SetFile( meshfile.ToCString() );
2539
2540   // For PAL13473 ("Repetitive mesh") implementation.
2541   // New dependencies between SMESH objects are established:
2542   // now hypotheses can refer to meshes, shapes and other hypotheses.
2543   // To keep data consistent, the following order of data restoration
2544   // imposed:
2545   // 1. Create hypotheses
2546   // 2. Create all meshes
2547   // 3. Load hypotheses' data
2548   // 4. All the rest
2549
2550   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
2551   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
2552
2553   // get total number of top-level groups
2554   int aNbGroups = aFile->nInternalObjects(); 
2555   if ( aNbGroups > 0 ) {
2556     // --> in first turn we should read&create hypotheses
2557     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
2558       // open hypotheses root HDF group
2559       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
2560       aTopGroup->OpenOnDisk();
2561
2562       // get number of hypotheses
2563       int aNbObjects = aTopGroup->nInternalObjects(); 
2564       for ( int j = 0; j < aNbObjects; j++ ) {
2565         // try to identify hypothesis
2566         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2567         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2568
2569         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
2570           // open hypothesis group
2571           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2572           aGroup->OpenOnDisk();
2573
2574           // --> get hypothesis id
2575           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
2576           string hypname;
2577           string libname;
2578           string hypdata;
2579
2580           // get number of datasets
2581           int aNbSubObjects = aGroup->nInternalObjects();
2582           for ( int k = 0; k < aNbSubObjects; k++ ) {
2583             // identify dataset
2584             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2585             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2586             // --> get hypothesis name
2587             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2588               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2589               aDataset->OpenOnDisk();
2590               size = aDataset->GetSize();
2591               char* hypname_str = new char[ size ];
2592               aDataset->ReadFromDisk( hypname_str );
2593               hypname = string( hypname_str );
2594               delete [] hypname_str;
2595               aDataset->CloseOnDisk();
2596             }
2597             // --> get hypothesis plugin library name
2598             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2599               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2600               aDataset->OpenOnDisk();
2601               size = aDataset->GetSize();
2602               char* libname_str = new char[ size ];
2603               aDataset->ReadFromDisk( libname_str );
2604               if(MYDEBUG) SCRUTE( libname_str );
2605               libname = string( libname_str );
2606               delete [] libname_str;
2607               aDataset->CloseOnDisk();
2608             }
2609             // --> get hypothesis data
2610             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2611               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2612               aDataset->OpenOnDisk();
2613               size = aDataset->GetSize();
2614               char* hypdata_str = new char[ size ];
2615               aDataset->ReadFromDisk( hypdata_str );
2616               hypdata = string( hypdata_str );
2617               delete [] hypdata_str;
2618               aDataset->CloseOnDisk();
2619             }
2620           }
2621           // close hypothesis HDF group
2622           aGroup->CloseOnDisk();
2623
2624           // --> restore hypothesis from data
2625           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2626             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
2627                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2628             SMESH::SMESH_Hypothesis_var myHyp;
2629
2630             try { // protect persistence mechanism against exceptions
2631               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2632             }
2633             catch (...) {
2634               INFOS( "Exception during hypothesis creation" );
2635             }
2636
2637             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2638             if ( myImpl ) {
2639               // myImpl->LoadFrom( hypdata.c_str() );
2640               hypDataList.push_back( make_pair( myImpl, hypdata ));
2641               string iorString = GetORB()->object_to_string( myHyp );
2642               int newId = myStudyContext->findId( iorString );
2643               myStudyContext->mapOldToNew( id, newId );
2644             }
2645             else
2646               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2647           }
2648         }
2649       }
2650       // close hypotheses root HDF group
2651       aTopGroup->CloseOnDisk();
2652     }
2653
2654     // --> then we should read&create algorithms
2655     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
2656       // open algorithms root HDF group
2657       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
2658       aTopGroup->OpenOnDisk();
2659
2660       // get number of algorithms
2661       int aNbObjects = aTopGroup->nInternalObjects(); 
2662       for ( int j = 0; j < aNbObjects; j++ ) {
2663         // try to identify algorithm
2664         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2665         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2666
2667         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
2668           // open algorithm group
2669           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2670           aGroup->OpenOnDisk();
2671
2672           // --> get algorithm id
2673           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
2674           string hypname;
2675           string libname;
2676           string hypdata;
2677
2678           // get number of datasets
2679           int aNbSubObjects = aGroup->nInternalObjects();
2680           for ( int k = 0; k < aNbSubObjects; k++ ) {
2681             // identify dataset
2682             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2683             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2684             // --> get algorithm name
2685             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2686               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2687               aDataset->OpenOnDisk();
2688               size = aDataset->GetSize();
2689               char* hypname_str = new char[ size ];
2690               aDataset->ReadFromDisk( hypname_str );
2691               hypname = string( hypname_str );
2692               delete [] hypname_str;
2693               aDataset->CloseOnDisk();
2694             }
2695             // --> get algorithm plugin library name
2696             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2697               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2698               aDataset->OpenOnDisk();
2699               size = aDataset->GetSize();
2700               char* libname_str = new char[ size ];
2701               aDataset->ReadFromDisk( libname_str );
2702               if(MYDEBUG) SCRUTE( libname_str );
2703               libname = string( libname_str );
2704               delete [] libname_str;
2705               aDataset->CloseOnDisk();
2706             }
2707             // --> get algorithm data
2708             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2709               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2710               aDataset->OpenOnDisk();
2711               size = aDataset->GetSize();
2712               char* hypdata_str = new char[ size ];
2713               aDataset->ReadFromDisk( hypdata_str );
2714               if(MYDEBUG) SCRUTE( hypdata_str );
2715               hypdata = string( hypdata_str );
2716               delete [] hypdata_str;
2717               aDataset->CloseOnDisk();
2718             }
2719           }
2720           // close algorithm HDF group
2721           aGroup->CloseOnDisk();
2722
2723           // --> restore algorithm from data
2724           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2725             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
2726                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2727             SMESH::SMESH_Hypothesis_var myHyp;
2728
2729             try { // protect persistence mechanism against exceptions
2730               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2731             }
2732             catch (...) {
2733               INFOS( "Exception during hypothesis creation" );
2734             }
2735
2736             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2737             if ( myImpl ) {
2738               //myImpl->LoadFrom( hypdata.c_str() );
2739               hypDataList.push_back( make_pair( myImpl, hypdata ));
2740               string iorString = GetORB()->object_to_string( myHyp );
2741               int newId = myStudyContext->findId( iorString );
2742               myStudyContext->mapOldToNew( id, newId );
2743             }
2744             else
2745               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2746           }
2747         }
2748       }
2749       // close algorithms root HDF group
2750       aTopGroup->CloseOnDisk();
2751     }
2752
2753     // --> the rest groups should be meshes
2754     for ( int i = 0; i < aNbGroups; i++ ) {
2755       // identify next group
2756       char meshName[ HDF_NAME_MAX_LEN+1 ];
2757       aFile->InternalObjectIndentify( i, meshName );
2758
2759       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
2760         // --> get mesh id
2761         int id = atoi( string( meshName ).substr( 4 ).c_str() );
2762         if ( id <= 0 )
2763           continue;
2764
2765         // open mesh HDF group
2766         aTopGroup = new HDFgroup( meshName, aFile ); 
2767         aTopGroup->OpenOnDisk();
2768
2769         // get number of child HDF objects
2770         int aNbObjects = aTopGroup->nInternalObjects(); 
2771         if ( aNbObjects > 0 ) {
2772           // create mesh
2773           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
2774           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
2775           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
2776           if ( !myNewMeshImpl )
2777             continue;
2778           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
2779
2780           string iorString = GetORB()->object_to_string( myNewMesh );
2781           int newId = myStudyContext->findId( iorString );
2782           myStudyContext->mapOldToNew( id, newId );
2783
2784           // try to read and set reference to shape
2785           GEOM::GEOM_Object_var aShapeObject;
2786           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
2787             // load mesh "Ref on shape" - it's an entry to SObject
2788             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
2789             aDataset->OpenOnDisk();
2790             size = aDataset->GetSize();
2791             char* refFromFile = new char[ size ];
2792             aDataset->ReadFromDisk( refFromFile );
2793             aDataset->CloseOnDisk();
2794             if ( strlen( refFromFile ) > 0 ) {
2795               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
2796
2797               // Make sure GEOM data are loaded first
2798               //loadGeomData( shapeSO->GetFatherComponent() );
2799
2800               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
2801               if ( !CORBA::is_nil( shapeObject ) ) {
2802                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
2803                 if ( !aShapeObject->_is_nil() )
2804                   myNewMeshImpl->SetShape( aShapeObject );
2805               }
2806             }
2807           }
2808
2809         }
2810       }
2811     }
2812
2813     // As all object that can be referred by hypothesis are created,
2814     // we can restore hypothesis data
2815
2816     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
2817     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
2818     {
2819       SMESH_Hypothesis_i* hyp  = hyp_data->first;
2820       string &            data = hyp_data->second;
2821       hyp->LoadFrom( data.c_str() );
2822     }
2823
2824     // Restore the rest mesh data
2825
2826     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
2827     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
2828     {
2829       aTopGroup                   = meshi_group->second;
2830       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
2831       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
2832       SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2833
2834       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
2835       bool hasData = false;
2836
2837       // get mesh old id
2838       string iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
2839       int newId = myStudyContext->findId( iorString );
2840       int id = myStudyContext->getOldId( newId );
2841
2842       // try to find mesh data dataset
2843       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
2844         // load mesh "has data" flag
2845         aDataset = new HDFdataset( "Has data", aTopGroup );
2846         aDataset->OpenOnDisk();
2847         size = aDataset->GetSize();
2848         char* strHasData = new char[ size ];
2849         aDataset->ReadFromDisk( strHasData );
2850         aDataset->CloseOnDisk();
2851         if ( strcmp( strHasData, "1") == 0 ) {
2852           // read mesh data from MED file
2853           myReader.SetMesh( mySMESHDSMesh );
2854           myReader.SetMeshId( id );
2855           myReader.Perform();
2856           hasData = true;
2857         }
2858       }
2859
2860       // try to get applied algorithms
2861       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
2862         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
2863         aGroup->OpenOnDisk();
2864         // get number of applied algorithms
2865         int aNbSubObjects = aGroup->nInternalObjects(); 
2866         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
2867         for ( int j = 0; j < aNbSubObjects; j++ ) {
2868           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2869           aGroup->InternalObjectIndentify( j, name_dataset );
2870           // check if it is an algorithm
2871           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
2872             aDataset = new HDFdataset( name_dataset, aGroup );
2873             aDataset->OpenOnDisk();
2874             size = aDataset->GetSize();
2875             char* refFromFile = new char[ size ];
2876             aDataset->ReadFromDisk( refFromFile );
2877             aDataset->CloseOnDisk();
2878
2879             // san - it is impossible to recover applied algorithms using their entries within Load() method
2880
2881             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2882             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2883             int id = atoi( refFromFile );
2884             string anIOR = myStudyContext->getIORbyOldId( id );
2885             if ( !anIOR.empty() ) {
2886               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2887               if ( !CORBA::is_nil( hypObject ) ) {
2888                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2889                 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2890                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2891               }
2892             }
2893           }
2894         }
2895         aGroup->CloseOnDisk();
2896       }
2897
2898       // try to get applied hypotheses
2899       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2900         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2901         aGroup->OpenOnDisk();
2902         // get number of applied hypotheses
2903         int aNbSubObjects = aGroup->nInternalObjects(); 
2904         for ( int j = 0; j < aNbSubObjects; j++ ) {
2905           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2906           aGroup->InternalObjectIndentify( j, name_dataset );
2907           // check if it is a hypothesis
2908           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2909             aDataset = new HDFdataset( name_dataset, aGroup );
2910             aDataset->OpenOnDisk();
2911             size = aDataset->GetSize();
2912             char* refFromFile = new char[ size ];
2913             aDataset->ReadFromDisk( refFromFile );
2914             aDataset->CloseOnDisk();
2915
2916             // san - it is impossible to recover applied hypotheses using their entries within Load() method
2917
2918             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2919             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2920             int id = atoi( refFromFile );
2921             string anIOR = myStudyContext->getIORbyOldId( id );
2922             if ( !anIOR.empty() ) {
2923               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2924               if ( !CORBA::is_nil( hypObject ) ) {
2925                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2926                 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2927                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2928               }
2929             }
2930           }
2931         }
2932         aGroup->CloseOnDisk();
2933       }
2934
2935       // --> try to find submeshes containers for each type of submesh
2936       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
2937         char name_meshgroup[ 30 ];
2938         if ( j == GetSubMeshOnVertexTag() )
2939           strcpy( name_meshgroup, "SubMeshes On Vertex" );
2940         else if ( j == GetSubMeshOnEdgeTag() )
2941           strcpy( name_meshgroup, "SubMeshes On Edge" );
2942         else if ( j == GetSubMeshOnWireTag() )
2943           strcpy( name_meshgroup, "SubMeshes On Wire" );
2944         else if ( j == GetSubMeshOnFaceTag() )
2945           strcpy( name_meshgroup, "SubMeshes On Face" );
2946         else if ( j == GetSubMeshOnShellTag() )
2947           strcpy( name_meshgroup, "SubMeshes On Shell" );
2948         else if ( j == GetSubMeshOnSolidTag() )
2949           strcpy( name_meshgroup, "SubMeshes On Solid" );
2950         else if ( j == GetSubMeshOnCompoundTag() )
2951           strcpy( name_meshgroup, "SubMeshes On Compound" );
2952
2953         // try to get submeshes container HDF group
2954         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
2955           // open submeshes containers HDF group
2956           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2957           aGroup->OpenOnDisk();
2958
2959           // get number of submeshes
2960           int aNbSubMeshes = aGroup->nInternalObjects(); 
2961           for ( int k = 0; k < aNbSubMeshes; k++ ) {
2962             // identify submesh
2963             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
2964             aGroup->InternalObjectIndentify( k, name_submeshgroup );
2965             if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
2966               // --> get submesh id
2967               int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
2968               if ( subid <= 0 )
2969                 continue;
2970               // open submesh HDF group
2971               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
2972               aSubGroup->OpenOnDisk();
2973
2974               // try to read and set reference to subshape
2975               GEOM::GEOM_Object_var aSubShapeObject;
2976               SMESH::SMESH_subMesh_var aSubMesh;
2977
2978               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
2979                 // load submesh "Ref on shape" - it's an entry to SObject
2980                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
2981                 aDataset->OpenOnDisk();
2982                 size = aDataset->GetSize();
2983                 char* refFromFile = new char[ size ];
2984                 aDataset->ReadFromDisk( refFromFile );
2985                 aDataset->CloseOnDisk();
2986                 if ( strlen( refFromFile ) > 0 ) {
2987                   SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
2988                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
2989                   if ( !CORBA::is_nil( subShapeObject ) ) {
2990                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
2991                     if ( !aSubShapeObject->_is_nil() )
2992                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
2993                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
2994                     if ( aSubMesh->_is_nil() )
2995                       continue;
2996                     string iorSubString = GetORB()->object_to_string( aSubMesh );
2997                     int newSubId = myStudyContext->findId( iorSubString );
2998                     myStudyContext->mapOldToNew( subid, newSubId );
2999                   }
3000                 }
3001               }
3002
3003               if ( aSubMesh->_is_nil() )
3004                 continue;
3005
3006               // VSR: Get submesh data from MED convertor
3007               //                  int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
3008               //                  if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
3009               //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
3010               //                            subid << " for subshape # " << anInternalSubmeshId);
3011               //                    SMESHDS_SubMesh* aSubMeshDS =
3012               //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
3013               //                    if ( !aSubMeshDS ) {
3014               //                      if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
3015               //                              anInternalSubmeshId << " in current mesh!");
3016               //                    }
3017               //                    else
3018               //                      myReader.GetSubMesh( aSubMeshDS, subid );
3019               //                  }
3020
3021               // try to get applied algorithms
3022               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
3023                 // open "applied algorithms" HDF group
3024                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3025                 aSubSubGroup->OpenOnDisk();
3026                 // get number of applied algorithms
3027                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
3028                 for ( int l = 0; l < aNbSubObjects; l++ ) {
3029                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3030                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
3031                   // check if it is an algorithm
3032                   if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
3033                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
3034                     aDataset->OpenOnDisk();
3035                     size = aDataset->GetSize();
3036                     char* refFromFile = new char[ size ];
3037                     aDataset->ReadFromDisk( refFromFile );
3038                     aDataset->CloseOnDisk();
3039
3040                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3041                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3042                     int id = atoi( refFromFile );
3043                     string anIOR = myStudyContext->getIORbyOldId( id );
3044                     if ( !anIOR.empty() ) {
3045                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3046                       if ( !CORBA::is_nil( hypObject ) ) {
3047                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3048                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
3049                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
3050                       }
3051                     }
3052                   }
3053                 }
3054                 // close "applied algorithms" HDF group
3055                 aSubSubGroup->CloseOnDisk();
3056               }
3057
3058               // try to get applied hypotheses
3059               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
3060                 // open "applied hypotheses" HDF group
3061                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3062                 aSubSubGroup->OpenOnDisk();
3063                 // get number of applied hypotheses
3064                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
3065                 for ( int l = 0; l < aNbSubObjects; l++ ) {
3066                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3067                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
3068                   // check if it is a hypothesis
3069                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
3070                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
3071                     aDataset->OpenOnDisk();
3072                     size = aDataset->GetSize();
3073                     char* refFromFile = new char[ size ];
3074                     aDataset->ReadFromDisk( refFromFile );
3075                     aDataset->CloseOnDisk();
3076
3077                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3078                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3079                     int id = atoi( refFromFile );
3080                     string anIOR = myStudyContext->getIORbyOldId( id );
3081                     if ( !anIOR.empty() ) {
3082                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3083                       if ( !CORBA::is_nil( hypObject ) ) {
3084                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3085                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
3086                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
3087                       }
3088                     }
3089                   }
3090                 }
3091                 // close "applied hypotheses" HDF group
3092                 aSubSubGroup->CloseOnDisk();
3093               }
3094
3095               // close submesh HDF group
3096               aSubGroup->CloseOnDisk();
3097             }
3098           }
3099           // close submeshes containers HDF group
3100           aGroup->CloseOnDisk();
3101         }
3102       }
3103
3104       if(hasData) {
3105
3106         // Read sub-meshes from MED
3107         // -------------------------
3108         if(MYDEBUG) MESSAGE("Create all sub-meshes");
3109         bool submeshesInFamilies = ( ! aTopGroup->ExistInternalObject( "Submeshes" ));
3110         if ( submeshesInFamilies )
3111         {
3112           // old way working before fix of PAL 12992
3113           myReader.CreateAllSubMeshes();
3114         }
3115         else
3116         {
3117           // open a group
3118           aGroup = new HDFgroup( "Submeshes", aTopGroup ); 
3119           aGroup->OpenOnDisk();
3120
3121           int maxID = mySMESHDSMesh->MaxShapeIndex();
3122           vector< SMESHDS_SubMesh * > subMeshes( maxID + 1, (SMESHDS_SubMesh*) 0 );
3123           vector< TopAbs_ShapeEnum  > smType   ( maxID + 1, TopAbs_SHAPE ); 
3124
3125           PositionCreator aPositionCreator;
3126
3127           SMDS_NodeIteratorPtr nIt = mySMESHDSMesh->nodesIterator();
3128           SMDS_ElemIteratorPtr eIt = mySMESHDSMesh->elementsIterator();
3129           for ( int isNode = 0; isNode < 2; ++isNode )
3130           {
3131             string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3132             if ( aGroup->ExistInternalObject( (char*) aDSName.c_str() ))
3133             {
3134               aDataset = new HDFdataset( (char*) aDSName.c_str(), aGroup );
3135               aDataset->OpenOnDisk();
3136               // read submesh IDs for all elements sorted by ID
3137               int nbElems = aDataset->GetSize();
3138               int* smIDs = new int [ nbElems ];
3139               aDataset->ReadFromDisk( smIDs );
3140               aDataset->CloseOnDisk();
3141
3142               // get elements sorted by ID
3143               TIDSortedElemSet elemSet;
3144               if ( isNode )
3145                 while ( nIt->more() ) elemSet.insert( nIt->next() );
3146               else
3147                 while ( eIt->more() ) elemSet.insert( eIt->next() );
3148               ASSERT( elemSet.size() == nbElems );
3149
3150               // add elements to submeshes
3151               TIDSortedElemSet::iterator iE = elemSet.begin();
3152               for ( int i = 0; i < nbElems; ++i, ++iE )
3153               {
3154                 int smID = smIDs[ i ];
3155                 if ( smID == 0 ) continue;
3156                 ASSERT( smID <= maxID );
3157                 const SMDS_MeshElement* elem = *iE;
3158                 // get or create submesh
3159                 SMESHDS_SubMesh* & sm = subMeshes[ smID ];
3160                 if ( ! sm ) {
3161                   sm = mySMESHDSMesh->NewSubMesh( smID );
3162                   smType[ smID ] = mySMESHDSMesh->IndexToShape( smID ).ShapeType();
3163                 }
3164                 // add
3165                 if ( isNode ) {
3166                   SMDS_PositionPtr pos = aPositionCreator.MakePosition( smType[ smID ]);
3167                   pos->SetShapeId( smID );
3168                   SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>( static_cast<const SMDS_MeshNode*>( elem ));
3169                   node->SetPosition( pos );
3170                   sm->AddNode( node );
3171                 } else {
3172                   sm->AddElement( elem );
3173                 }
3174               }
3175               delete [] smIDs;
3176             }
3177           }
3178         } // end reading submeshes
3179
3180         // Read node positions on sub-shapes (SMDS_Position)
3181
3182         if ( aTopGroup->ExistInternalObject( "Node Positions" ))
3183         {
3184           // There are 5 datasets to read:
3185           // "Nodes on Edges" - ID of node on edge
3186           // "Edge positions" - U parameter on node on edge
3187           // "Nodes on Faces" - ID of node on face
3188           // "Face U positions" - U parameter of node on face
3189           // "Face V positions" - V parameter of node on face
3190           char* aEid_DSName = "Nodes on Edges";
3191           char* aEu_DSName  = "Edge positions";
3192           char* aFu_DSName  = "Face U positions";
3193           //char* aFid_DSName = "Nodes on Faces";
3194           //char* aFv_DSName  = "Face V positions";
3195
3196           // data to retrieve
3197           int nbEids = 0, nbFids = 0;
3198           int *aEids = 0, *aFids  = 0;
3199           double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
3200
3201           // open a group
3202           aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
3203           aGroup->OpenOnDisk();
3204
3205           // loop on 5 data sets
3206           int aNbObjects = aGroup->nInternalObjects();
3207           for ( int i = 0; i < aNbObjects; i++ )
3208           {
3209             // identify dataset
3210             char aDSName[ HDF_NAME_MAX_LEN+1 ];
3211             aGroup->InternalObjectIndentify( i, aDSName );
3212             // read data
3213             aDataset = new HDFdataset( aDSName, aGroup );
3214             aDataset->OpenOnDisk();
3215             if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
3216             {
3217               double* pos = new double [ aDataset->GetSize() ];
3218               aDataset->ReadFromDisk( pos );
3219               // which one?
3220               if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
3221                 aEpos = pos;
3222               else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
3223                 aFupos = pos;
3224               else
3225                 aFvpos = pos;
3226             }
3227             else // NODE IDS
3228             {
3229               int aSize = aDataset->GetSize();
3230
3231               // for reading files, created from 18.07.2005 till 10.10.2005
3232               if (aDataset->GetType() == HDF_STRING)
3233                 aSize /= sizeof(int);
3234
3235               int* ids = new int [aSize];
3236               aDataset->ReadFromDisk( ids );
3237               // on face or nodes?
3238               if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
3239                 aEids = ids;
3240                 nbEids = aSize;
3241               }
3242               else {
3243                 aFids = ids;
3244                 nbFids = aSize;
3245               }
3246             }
3247             aDataset->CloseOnDisk();
3248           } // loop on 5 datasets
3249
3250           // Set node positions on edges or faces
3251           for ( int onFace = 0; onFace < 2; onFace++ )
3252           {
3253             int nbNodes = ( onFace ? nbFids : nbEids );
3254             if ( nbNodes == 0 ) continue;
3255             int* aNodeIDs = ( onFace ? aFids : aEids );
3256             double* aUPos = ( onFace ? aFupos : aEpos );
3257             double* aVPos = ( onFace ? aFvpos : 0 );
3258             // loop on node IDs
3259             for ( int iNode = 0; iNode < nbNodes; iNode++ )
3260             {
3261               const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
3262               ASSERT( node );
3263               SMDS_PositionPtr aPos = node->GetPosition();
3264               ASSERT( aPos )
3265                 if ( onFace ) {
3266                   ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );
3267                   SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
3268                     ( static_cast<const SMDS_FacePosition*>( aPos.get() ));
3269                   fPos->SetUParameter( aUPos[ iNode ]);
3270                   fPos->SetVParameter( aVPos[ iNode ]);
3271                 }
3272                 else {
3273                   ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );
3274                   SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
3275                     ( static_cast<const SMDS_EdgePosition*>( aPos.get() ));
3276                   fPos->SetUParameter( aUPos[ iNode ]);
3277                 }
3278             }
3279           }
3280           if ( aEids ) delete [] aEids;
3281           if ( aFids ) delete [] aFids;
3282           if ( aEpos ) delete [] aEpos;
3283           if ( aFupos ) delete [] aFupos;
3284           if ( aFvpos ) delete [] aFvpos;
3285
3286           aGroup->CloseOnDisk();
3287
3288         } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
3289       } // if ( hasData )
3290
3291       // Recompute State (as computed sub-meshes are restored from MED)
3292       if ( !aShapeObject->_is_nil() ) {
3293         MESSAGE("Compute State Engine ...");
3294         TopoDS_Shape myLocShape = GeomObjectToShape( aShapeObject );
3295         myNewMeshImpl->GetImpl().GetSubMesh(myLocShape)->ComputeStateEngine
3296           (SMESH_subMesh::SUBMESH_RESTORED);
3297         MESSAGE("Compute State Engine finished");
3298       }
3299
3300       // try to get groups
3301       for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
3302         char name_group[ 30 ];
3303         if ( ii == GetNodeGroupsTag() )
3304           strcpy( name_group, "Groups of Nodes" );
3305         else if ( ii == GetEdgeGroupsTag() )
3306           strcpy( name_group, "Groups of Edges" );
3307         else if ( ii == GetFaceGroupsTag() )
3308           strcpy( name_group, "Groups of Faces" );
3309         else if ( ii == GetVolumeGroupsTag() )
3310           strcpy( name_group, "Groups of Volumes" );
3311
3312         if ( aTopGroup->ExistInternalObject( name_group ) ) {
3313           aGroup = new HDFgroup( name_group, aTopGroup );
3314           aGroup->OpenOnDisk();
3315           // get number of groups
3316           int aNbSubObjects = aGroup->nInternalObjects(); 
3317           for ( int j = 0; j < aNbSubObjects; j++ ) {
3318             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3319             aGroup->InternalObjectIndentify( j, name_dataset );
3320             // check if it is an group
3321             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
3322               // --> get group id
3323               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
3324               if ( subid <= 0 )
3325                 continue;
3326               aDataset = new HDFdataset( name_dataset, aGroup );
3327               aDataset->OpenOnDisk();
3328
3329               // Retrieve actual group name
3330               size = aDataset->GetSize();
3331               char* nameFromFile = new char[ size ];
3332               aDataset->ReadFromDisk( nameFromFile );
3333               aDataset->CloseOnDisk();
3334
3335               // Try to find a shape reference
3336               TopoDS_Shape aShape;
3337               char aRefName[ 30 ];
3338               sprintf( aRefName, "Ref on shape %d", subid);
3339               if ( aGroup->ExistInternalObject( aRefName ) ) {
3340                 // load mesh "Ref on shape" - it's an entry to SObject
3341                 aDataset = new HDFdataset( aRefName, aGroup );
3342                 aDataset->OpenOnDisk();
3343                 size = aDataset->GetSize();
3344                 char* refFromFile = new char[ size ];
3345                 aDataset->ReadFromDisk( refFromFile );
3346                 aDataset->CloseOnDisk();
3347                 if ( strlen( refFromFile ) > 0 ) {
3348                   SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
3349                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
3350                   if ( !CORBA::is_nil( shapeObject ) ) {
3351                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
3352                     if ( !aShapeObject->_is_nil() )
3353                       aShape = GeomObjectToShape( aShapeObject );
3354                   }
3355                 }
3356               }
3357               // Create group servant
3358               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
3359               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
3360                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
3361               // Obtain a SMESHDS_Group object 
3362               if ( aNewGroup->_is_nil() )
3363                 continue;
3364
3365               string iorSubString = GetORB()->object_to_string( aNewGroup );
3366               int newSubId = myStudyContext->findId( iorSubString );
3367               myStudyContext->mapOldToNew( subid, newSubId );
3368
3369               SMESH_GroupBase_i* aGroupImpl =
3370                 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
3371               if ( !aGroupImpl )
3372                 continue;
3373
3374               SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
3375               if ( !aLocalGroup )
3376                 continue;
3377
3378               SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
3379               aGroupBaseDS->SetStoreName( name_dataset );
3380
3381               // Fill group with contents from MED file
3382               SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
3383               if ( aGrp )
3384                 myReader.GetGroup( aGrp );
3385             }
3386           }
3387           aGroup->CloseOnDisk();
3388         }
3389       }
3390     }
3391     // close mesh group
3392     aTopGroup->CloseOnDisk();   
3393   }
3394   // close HDF file
3395   aFile->CloseOnDisk();
3396   delete aFile;
3397
3398   // Remove temporary files created from the stream
3399   if ( !isMultiFile ) 
3400     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3401
3402   INFOS( "SMESH_Gen_i::Load completed" );
3403   return true;
3404 }
3405
3406 //=============================================================================
3407 /*!
3408  *  SMESH_Gen_i::LoadASCII
3409  *
3410  *  Load SMESH module's data in ASCII format
3411  */
3412 //=============================================================================
3413
3414 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
3415                              const SALOMEDS::TMPFile& theStream,
3416                              const char*              theURL,
3417                              bool                     isMultiFile ) {
3418   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
3419   return Load( theComponent, theStream, theURL, isMultiFile );
3420
3421   //before call main ::Load method it's need for decipher text format to
3422   //binary ( "|xx" => x' )
3423   int size = theStream.length();
3424   if ( int((size / 3 )*3) != size ) //error size of buffer
3425     return false;
3426
3427   int real_size = int(size / 3);
3428
3429   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
3430   char tmp[3];
3431   tmp[2]='\0';
3432   int c = -1;
3433   for ( int i = 0; i < real_size; i++ )
3434   {
3435     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
3436     sscanf( tmp, "%x", &c );
3437     sprintf( (char*)&(buffer[i]), "%c", (char)c );
3438   }
3439
3440   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
3441   
3442   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
3443 }
3444
3445 //=============================================================================
3446 /*!
3447  *  SMESH_Gen_i::Close
3448  *
3449  *  Clears study-connected data when it is closed
3450  */
3451 //=============================================================================
3452
3453 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
3454 {
3455   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
3456
3457   // Clear study contexts data
3458   int studyId = GetCurrentStudyID();
3459   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
3460     delete myStudyContextMap[ studyId ];
3461     myStudyContextMap.erase( studyId );
3462   }
3463   return;
3464 }
3465
3466 //=============================================================================
3467 /*!
3468  *  SMESH_Gen_i::ComponentDataType
3469  * 
3470  *  Get component data type
3471  */
3472 //=============================================================================
3473
3474 char* SMESH_Gen_i::ComponentDataType()
3475 {
3476   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
3477   return CORBA::string_dup( "SMESH" );
3478 }
3479
3480     
3481 //=============================================================================
3482 /*!
3483  *  SMESH_Gen_i::IORToLocalPersistentID
3484  *  
3485  *  Transform data from transient form to persistent
3486  */
3487 //=============================================================================
3488
3489 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
3490                                            const char*           IORString,
3491                                            CORBA::Boolean        /*isMultiFile*/,
3492                                            CORBA::Boolean        /*isASCII*/ )
3493 {
3494   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
3495   StudyContext* myStudyContext = GetCurrentStudyContext();
3496   
3497   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
3498     int anId = myStudyContext->findId( IORString );
3499     if ( anId ) {
3500       if(MYDEBUG) MESSAGE( "VSR " << anId )
3501       char strId[ 20 ];
3502       sprintf( strId, "%d", anId );
3503       return  CORBA::string_dup( strId );
3504     }
3505   }
3506   return CORBA::string_dup( "" );
3507 }
3508
3509 //=============================================================================
3510 /*!
3511  *  SMESH_Gen_i::LocalPersistentIDToIOR
3512  *
3513  *  Transform data from persistent form to transient
3514  */
3515 //=============================================================================
3516
3517 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
3518                                            const char*           aLocalPersistentID,
3519                                            CORBA::Boolean        /*isMultiFile*/,
3520                                            CORBA::Boolean        /*isASCII*/ )
3521 {
3522   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
3523   StudyContext* myStudyContext = GetCurrentStudyContext();
3524
3525   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
3526     int anId = atoi( aLocalPersistentID );
3527     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
3528   }
3529   return CORBA::string_dup( "" );
3530 }
3531
3532 //=======================================================================
3533 //function : RegisterObject
3534 //purpose  : 
3535 //=======================================================================
3536
3537 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
3538 {
3539   StudyContext* myStudyContext = GetCurrentStudyContext();
3540   if ( myStudyContext && !CORBA::is_nil( theObject )) {
3541     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
3542     return myStudyContext->addObject( string( iorString.in() ) );
3543   }
3544   return 0;
3545 }
3546
3547 //================================================================================
3548 /*!
3549  * \brief Return id of registered object
3550   * \param theObject - the Object
3551   * \retval int - Object id
3552  */
3553 //================================================================================
3554
3555 int SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
3556 {
3557   StudyContext* myStudyContext = GetCurrentStudyContext();
3558   if ( myStudyContext && !CORBA::is_nil( theObject )) {
3559     string iorString = GetORB()->object_to_string( theObject );
3560     return myStudyContext->findId( iorString );
3561   }
3562   return 0;
3563 }
3564
3565 //=============================================================================
3566 /*! 
3567  *  SMESHEngine_factory
3568  *
3569  *  C factory, accessible with dlsym, after dlopen  
3570  */
3571 //=============================================================================
3572
3573 extern "C"
3574 { SMESH_I_EXPORT
3575   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
3576                                                  PortableServer::POA_ptr   poa, 
3577                                                  PortableServer::ObjectId* contId,
3578                                                  const char*               instanceName, 
3579                                                  const char*               interfaceName )
3580   {
3581     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
3582     if(MYDEBUG) SCRUTE(interfaceName);
3583     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
3584     return aSMESHGen->getId() ;
3585   }
3586 }