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