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