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