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