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