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