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