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