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