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