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