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