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