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