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