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