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