Salome HOME
Merge from V6_2_BR 23/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             // copy orphan nodes
2031             SMDS_NodeIteratorPtr  itNodes = anInitMeshDS->nodesIterator();
2032             while ( itNodes->more() )
2033             {
2034               const SMDS_MeshNode* aNode = itNodes->next();
2035               if ( aNode->NbInverseElements() == 0 )
2036               {
2037                 const SMDS_MeshNode* aNewNode =
2038                   aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2039                 nodesMap.insert( make_pair(aNode->GetID(), aNewNode->GetID()) );
2040                 if( theCommonGroups )
2041                   anIDsNodes[anNbNodes++] = aNewNode->GetID();
2042               }
2043             }
2044
2045
2046             aListOfGroups = anInitImpl->GetGroups();
2047             SMESH::SMESH_GroupBase_ptr aGroup;
2048
2049             // loop on groups of mesh
2050             SMESH::long_array_var anInitIDs = new SMESH::long_array();
2051             SMESH::long_array_var anNewIDs = new SMESH::long_array();
2052             SMESH::SMESH_Group_var aNewGroup;
2053
2054             SMESH::ElementType aGroupType;
2055             CORBA::String_var aGroupName;
2056             if ( theCommonGroups ) {
2057               for(aGroupType=SMESH::NODE;aGroupType<=SMESH::VOLUME;aGroupType=(SMESH::ElementType)(aGroupType+1)) {
2058                 string str = "Gr";
2059                 SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, anInitMesh );
2060                 if(aMeshSObj)
2061                   str += aMeshSObj->GetName();
2062                 str += "_";
2063
2064                 int anLen = 0;
2065
2066                 switch(aGroupType) {
2067                 case SMESH::NODE:
2068                   str += "Nodes";
2069                   anIDsNodes->length(anNbNodes);
2070                   anLen = anNbNodes;
2071                   break;
2072                 case SMESH::EDGE:
2073                   str += "Edges";
2074                   anIDsEdges->length(anNbEdges);
2075                   anLen = anNbEdges;
2076                   break;
2077                 case SMESH::FACE:
2078                   str += "Faces";
2079                   anIDsFaces->length(anNbFaces);
2080                   anLen = anNbFaces;
2081                   break;
2082                 case SMESH::VOLUME:
2083                   str += "Volumes";
2084                   anIDsVolumes->length(anNbVolumes);
2085                   anLen = anNbVolumes;
2086                   break;
2087                 default:
2088                   break;
2089                 }
2090
2091                 if(anLen) {
2092                   aGroupName = str.c_str();
2093
2094                   // add a new group in the mesh
2095                   aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2096
2097                   switch(aGroupType) {
2098                   case SMESH::NODE:
2099                     aNewGroup->Add( anIDsNodes );
2100                     break;
2101                   case SMESH::EDGE:
2102                     aNewGroup->Add( anIDsEdges );
2103                     break;
2104                   case SMESH::FACE:
2105                     aNewGroup->Add( anIDsFaces );
2106                     break;
2107                   case SMESH::VOLUME:
2108                     aNewGroup->Add( anIDsVolumes );
2109                     break;
2110                   default:
2111                     break;
2112                   }
2113                 
2114                   aListOfNewGroups.clear();
2115                   aListOfNewGroups.push_back(aNewGroup);
2116                   aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2117                 }
2118               }
2119             }
2120
2121             // check that current group name and type don't have identical ones in union mesh
2122             for (int i = 0; i < aListOfGroups->length(); i++) {
2123               aGroup = aListOfGroups[i];
2124               aListOfNewGroups.clear();
2125               aGroupType = aGroup->GetType();
2126               aGroupName = aGroup->GetName();
2127
2128               TGroupsMap::iterator anIter = aGroupsMap.find(make_pair(aGroupName, aGroupType));
2129
2130               // convert a list of IDs
2131               anInitIDs = aGroup->GetListOfID();
2132               anNewIDs->length(anInitIDs->length());
2133               if ( aGroupType == SMESH::NODE )
2134                 for (int j = 0; j < anInitIDs->length(); j++) {
2135                   anNewIDs[j] = nodesMap.find(anInitIDs[j])->second;
2136                 }
2137               else
2138                 for (int j = 0; j < anInitIDs->length(); j++) {
2139                   anNewIDs[j] = elemsMap.find(anInitIDs[j])->second;
2140                 }
2141               
2142               // check that current group name and type don't have identical ones in union mesh
2143               if ( anIter == aGroupsMap.end() ) {
2144                 // add a new group in the mesh
2145                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2146                 // add elements into new group
2147                 aNewGroup->Add( anNewIDs );
2148                 
2149                 aListOfNewGroups.push_back(aNewGroup);
2150                 aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2151               }
2152
2153               else if ( theUniteIdenticalGroups ) {
2154                 // unite identical groups
2155                 TListOfNewGroups& aNewGroups = anIter->second;
2156                 aNewGroups.front()->Add( anNewIDs );
2157               }
2158
2159               else {
2160                 // rename identical groups
2161                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2162                 aNewGroup->Add( anNewIDs );
2163                 
2164                 TListOfNewGroups& aNewGroups = anIter->second;
2165                 string aNewGroupName;
2166                 if (aNewGroups.size() == 1) {
2167                   aNewGroupName = string(aGroupName) + "_1";
2168                   aNewGroups.front()->SetName(aNewGroupName.c_str());
2169                 }
2170                 char aGroupNum[128];
2171                 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
2172                 aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
2173                 aNewGroup->SetName(aNewGroupName.c_str());
2174                 aNewGroups.push_back(aNewGroup);
2175               }
2176             }//groups loop
2177           }
2178         }
2179       }//meshes loop
2180
2181       if (theMergeNodesAndElements) {
2182         // merge nodes
2183         TIDSortedNodeSet aMeshNodes; // no input nodes
2184         SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2185         aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes );
2186         aNewEditor.MergeNodes( aGroupsOfNodes );
2187         // merge elements
2188         aNewEditor.MergeEqualElements();
2189       }
2190     }
2191   }
2192   
2193   // Update Python script
2194   aPythonDump << aNewMesh << " = " << this;
2195   if( !theCommonGroups )
2196     aPythonDump << ".Concatenate(";
2197   else
2198     aPythonDump << ".ConcatenateWithGroups(";
2199   aPythonDump << "[";
2200   for ( int i = 0; i < theMeshesArray.length(); i++) {
2201     if (i > 0) aPythonDump << ", ";
2202     aPythonDump << theMeshesArray[i];
2203   }
2204   aPythonDump << "], ";
2205   aPythonDump << theUniteIdenticalGroups << ", "
2206               << theMergeNodesAndElements << ", "
2207               << theMergeTolerance << ")";
2208
2209   delete pPythonDump; // enable python dump from GetGroups()
2210
2211   // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2212   if ( !aNewMesh->_is_nil() )
2213   {
2214     SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2215   }
2216
2217   // IPAL21468 Change icon of compound because it need not be computed.
2218   SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
2219   if( !aMeshSObj->_is_nil() ) {
2220     SALOMEDS::GenericAttribute_var anAttr;
2221     SALOMEDS::StudyBuilder_var aBuilder = myCurrentStudy->NewBuilder();
2222     anAttr = aBuilder->FindOrCreateAttribute( aMeshSObj,"AttributePixMap" );
2223     SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
2224     aPixmap->SetPixMap("ICON_SMESH_TREE_MESH");
2225   }
2226   if (aNewMeshDS)
2227     aNewMeshDS->Modified();
2228   return aNewMesh._retn();
2229 }
2230
2231 //================================================================================
2232 /*!
2233  * \brief Create a mesh by copying a part of another mesh
2234  *  \param meshPart - a part of mesh to copy
2235  *  \param toCopyGroups - to create in the new mesh groups
2236  *                        the copied elements belongs to
2237  *  \param toKeepIDs - to preserve IDs of the copied elements or not
2238  *  \retval SMESH::SMESH_Mesh_ptr - the new mesh
2239  */
2240 //================================================================================
2241
2242 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2243                                             const char*               meshName,
2244                                             CORBA::Boolean            toCopyGroups,
2245                                             CORBA::Boolean            toKeepIDs)
2246 {
2247   Unexpect aCatch(SALOME_SalomeException);
2248
2249   TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2250
2251   // 1. Get source mesh
2252
2253   if ( CORBA::is_nil( meshPart ))
2254     THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2255
2256   SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2257   SMESH_Mesh_i*       srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2258   if ( !srcMesh_i )
2259     THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2260   
2261   SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2262
2263   // 2. Make a new mesh
2264
2265   SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2266   SMESH_Mesh_i*       newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2267   if ( !newMesh_i )
2268     THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2269   SALOMEDS::SObject_var meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2270   if ( !meshSO->_is_nil() )
2271   {
2272     SetName( meshSO, meshName, "Mesh" );
2273     SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2274   }
2275   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2276   ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2277
2278   // 3. Get elements to copy
2279
2280   SMDS_ElemIteratorPtr srcElemIt;
2281   TIDSortedElemSet srcElems;
2282   SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2283   if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2284   {
2285     srcElemIt = srcMeshDS->elementsIterator();
2286   }
2287   else
2288   {
2289     SMESH::long_array_var ids = meshPart->GetIDs();
2290     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2291     {
2292       for (int i=0; i < ids->length(); i++)
2293         if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2294           srcElems.insert( elem );
2295     }
2296     else
2297     {
2298       for (int i=0; i < ids->length(); i++)
2299         if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2300           srcElems.insert( elem );
2301     }
2302     if ( srcElems.empty() )
2303       return newMesh._retn();
2304
2305     typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2306     srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2307   }
2308
2309   // 4. Copy elements
2310
2311   typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2312   TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2313   TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2314   int iN;
2315   const SMDS_MeshNode *nSrc, *nTgt;
2316   vector< const SMDS_MeshNode* > nodes;
2317   while ( srcElemIt->more() )
2318   {
2319     const SMDS_MeshElement * elem = srcElemIt->next();
2320     nodes.resize( elem->NbNodes());
2321     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2322     if ( toKeepIDs ) {
2323       for ( iN = 0; nIt->more(); ++iN )
2324       {
2325         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2326         nTgt = newMeshDS->FindNode( nSrc->GetID());
2327         if ( !nTgt )
2328           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2329         nodes[ iN ] = nTgt;
2330       }
2331     }
2332     else {
2333       for ( iN = 0; nIt->more(); ++iN )
2334       {
2335         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2336         TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2337         if ( !n2n->second )
2338           n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2339         nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2340       }
2341     }
2342     if ( elem->GetType() != SMDSAbs_Node )
2343     {
2344       int ID = toKeepIDs ? elem->GetID() : 0;
2345       const SMDS_MeshElement * newElem = editor.AddElement( nodes,
2346                                                             elem->GetType(),
2347                                                             elem->IsPoly(),
2348                                                             ID);
2349       if ( toCopyGroups && !toKeepIDs )
2350         e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2351     }
2352   }
2353
2354   // 5. Copy groups
2355
2356   int nbNewGroups = 0;
2357   if ( toCopyGroups )
2358   {
2359     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2360     while ( gIt->more() )
2361     {
2362       SMESH_Group* group = gIt->next();
2363       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2364
2365       // Check group type. We copy nodal groups containing nodes of copied element
2366       SMDSAbs_ElementType groupType = groupDS->GetType();
2367       if ( groupType != SMDSAbs_Node &&
2368            newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2369         continue; // group type differs from types of meshPart
2370
2371       // Find copied elements in the group
2372       vector< const SMDS_MeshElement* > groupElems;
2373       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2374       if ( toKeepIDs )
2375       {
2376         const SMDS_MeshElement* foundElem;
2377         if ( groupType == SMDSAbs_Node )
2378         {
2379           while ( eIt->more() )
2380             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2381               groupElems.push_back( foundElem );
2382         }
2383         else
2384         {
2385           while ( eIt->more() )
2386             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2387               groupElems.push_back( foundElem );
2388         }
2389       }
2390       else
2391       {
2392         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2393         if ( e2eMap.empty() ) continue;
2394         int minID = e2eMap.begin()->first->GetID();
2395         int maxID = e2eMap.rbegin()->first->GetID();
2396         TE2EMap::iterator e2e;
2397         while ( eIt->more() && groupElems.size() < e2eMap.size())
2398         {
2399           const SMDS_MeshElement* e = eIt->next();
2400           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2401           if ((e2e = e2eMap.find( e )) != e2eMap.end())
2402             groupElems.push_back( e2e->second );
2403         }
2404       }
2405       // Make a new group
2406       if ( !groupElems.empty() )
2407       {
2408         SMESH::SMESH_Group_var newGroupObj =
2409           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2410         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2411         {
2412           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2413           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2414           for ( unsigned i = 0; i < groupElems.size(); ++i )
2415             smdsGroup.Add( groupElems[i] );
2416
2417           nbNewGroups++;
2418         }
2419       }
2420     }
2421   }
2422
2423   *pyDump << newMesh << " = " << this
2424           << ".CopyMesh( " << meshPart << ", "
2425           << "'" << meshName << "', "
2426           << toCopyGroups << ", "
2427           << toKeepIDs << ")";
2428
2429   delete pyDump; pyDump = 0; // allow dump in GetGroups()
2430
2431   if ( nbNewGroups > 0 ) // dump created groups
2432     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2433
2434   return newMesh._retn();
2435 }
2436
2437 //================================================================================
2438 /*!
2439  *  SMESH_Gen_i::GetMEDVersion
2440  *
2441  *  Get MED version of the file by its name
2442  */
2443 //================================================================================
2444 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2445                                           SMESH::MED_VERSION& theVersion)
2446 {
2447   theVersion = SMESH::MED_V2_1;
2448   MED::EVersion aVersion = MED::GetVersionId( theFileName );
2449   switch( aVersion ) {
2450     case MED::eV2_1     : theVersion = SMESH::MED_V2_1; return true;
2451     case MED::eV2_2     : theVersion = SMESH::MED_V2_2; return true;
2452     case MED::eVUnknown : return false;
2453   }
2454   return false;
2455 }
2456
2457 //================================================================================
2458 /*!
2459  *  SMESH_Gen_i::GetMeshNames
2460  *
2461  *  Get names of meshes defined in file with the specified name
2462  */
2463 //================================================================================
2464 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2465 {
2466   SMESH::string_array_var aResult = new SMESH::string_array();
2467   MED::PWrapper aMed = MED::CrWrapper( theFileName );
2468   MED::TErr anErr;
2469   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2470   if( anErr >= 0 ) {
2471     aResult->length( aNbMeshes );
2472     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2473       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2474       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2475     }
2476   }
2477   return aResult._retn();
2478 }
2479
2480 //=============================================================================
2481 /*!
2482  *  SMESH_Gen_i::Save
2483  *
2484  *  Save SMESH module's data
2485  */
2486 //=============================================================================
2487 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2488                                       const char*              theURL,
2489                                       bool                     isMultiFile )
2490 {
2491   INFOS( "SMESH_Gen_i::Save" );
2492
2493   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2494   // san -- in case <myCurrentStudy> differs from theComponent's study,
2495   // use that of the component
2496   if ( myCurrentStudy->_is_nil() || 
2497     theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2498     SetCurrentStudy( theComponent->GetStudy() );
2499
2500   // Store study contents as a set of python commands
2501   SavePython(myCurrentStudy);
2502
2503   StudyContext* myStudyContext = GetCurrentStudyContext();
2504
2505   // Declare a byte stream
2506   SALOMEDS::TMPFile_var aStreamFile;
2507
2508   // Obtain a temporary dir
2509   TCollection_AsciiString tmpDir =
2510     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2511
2512   // Create a sequence of files processed
2513   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2514   aFileSeq->length( NUM_TMP_FILES );
2515
2516   TCollection_AsciiString aStudyName( "" );
2517   if ( isMultiFile ) 
2518     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2519
2520   // Set names of temporary files
2521   TCollection_AsciiString filename =
2522     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
2523   TCollection_AsciiString meshfile =
2524     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
2525   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
2526   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
2527   filename = tmpDir + filename;
2528   meshfile = tmpDir + meshfile;
2529
2530   HDFfile*    aFile;
2531   HDFdataset* aDataset;
2532   HDFgroup*   aTopGroup;
2533   HDFgroup*   aGroup;
2534   HDFgroup*   aSubGroup;
2535   HDFgroup*   aSubSubGroup;
2536   hdf_size    aSize[ 1 ];
2537
2538
2539   //Remove the files if they exist: BugID: 11225
2540 #ifndef WNT /* unix functionality */
2541   TCollection_AsciiString cmd("rm -f \"");
2542 #else /* windows */
2543   TCollection_AsciiString cmd("del /F \"");
2544 #endif
2545
2546   cmd+=filename;
2547   cmd+="\" \"";
2548   cmd+=meshfile;
2549   cmd+="\"";
2550   system(cmd.ToCString());
2551
2552   // MED writer to be used by storage process
2553   DriverMED_W_SMESHDS_Mesh myWriter;
2554   myWriter.SetFile( meshfile.ToCString() );
2555
2556   // IMP issue 20918
2557   // SetStoreName() to groups before storing hypotheses to let them refer to
2558   // groups using "store name", which is "Group <group_persistent_id>"
2559   {
2560     SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2561     for ( ; itBig->More(); itBig->Next() ) {
2562       SALOMEDS::SObject_var gotBranch = itBig->Value();
2563       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2564         CORBA::Object_var anObject = SObjectToObject( gotBranch );
2565         if ( !CORBA::is_nil( anObject ) ) {
2566           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2567           if ( !myMesh->_is_nil() ) {
2568             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
2569             for ( int i = 0; i < groups->length(); ++i )
2570             {
2571               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
2572               if ( grImpl )
2573               {
2574                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
2575                 int anId = myStudyContext->findId( string( objStr.in() ) );
2576                 char grpName[ 30 ];
2577                 sprintf( grpName, "Group %d", anId );
2578                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
2579                 aGrpBaseDS->SetStoreName( grpName );
2580               }
2581             }
2582           }
2583         }
2584       }
2585     }
2586   }
2587
2588   // Write data
2589   // ---> create HDF file
2590   aFile = new HDFfile( (char*) filename.ToCString() );
2591   aFile->CreateOnDisk();
2592
2593   // --> iterator for top-level objects
2594   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2595   for ( ; itBig->More(); itBig->Next() ) {
2596     SALOMEDS::SObject_var gotBranch = itBig->Value();
2597
2598     // --> hypotheses root branch (only one for the study)
2599     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
2600       // create hypotheses root HDF group
2601       aTopGroup = new HDFgroup( "Hypotheses", aFile );
2602       aTopGroup->CreateOnDisk();
2603
2604       // iterator for all hypotheses
2605       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2606       for ( ; it->More(); it->Next() ) {
2607         SALOMEDS::SObject_var mySObject = it->Value();
2608         CORBA::Object_var anObject = SObjectToObject( mySObject );
2609         if ( !CORBA::is_nil( anObject ) ) {
2610           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2611           if ( !myHyp->_is_nil() ) {
2612             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2613             if ( myImpl ) {
2614               string hypname = string( myHyp->GetName() );
2615               string libname = string( myHyp->GetLibName() );
2616               // BUG SWP13062
2617               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2618               // WNT and ".so" for X-system) must be deleted
2619               int libname_len = libname.length();
2620 #ifdef WNT
2621               if( libname_len > 4 )
2622                 libname.resize( libname_len - 4 );
2623 #else
2624               // PAL17753 (Regresion: missing hypothesis in restored study)
2625               // "lib" also should be removed from the beginning
2626               //if( libname_len > 3 )
2627                 //libname.resize( libname_len - 3 );
2628               if( libname_len > 6 )
2629                 libname = libname.substr( 3, libname_len - 3 - 3 );
2630 #endif
2631               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2632               int    id      = myStudyContext->findId( string( objStr.in() ) );
2633               string hypdata = string( myImpl->SaveTo() );
2634
2635               // for each hypothesis create HDF group basing on its id
2636               char hypGrpName[30];
2637               sprintf( hypGrpName, "Hypothesis %d", id );
2638               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2639               aGroup->CreateOnDisk();
2640               // --> type name of hypothesis
2641               aSize[ 0 ] = hypname.length() + 1;
2642               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2643               aDataset->CreateOnDisk();
2644               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2645               aDataset->CloseOnDisk();
2646               // --> server plugin library name of hypothesis
2647               aSize[ 0 ] = libname.length() + 1;
2648               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2649               aDataset->CreateOnDisk();
2650               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2651               aDataset->CloseOnDisk();
2652               // --> persistent data of hypothesis
2653               aSize[ 0 ] = hypdata.length() + 1;
2654               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2655               aDataset->CreateOnDisk();
2656               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2657               aDataset->CloseOnDisk();
2658               // close hypothesis HDF group
2659               aGroup->CloseOnDisk();
2660             }
2661           }
2662         }
2663       }
2664       // close hypotheses root HDF group
2665       aTopGroup->CloseOnDisk();
2666     }
2667     // --> algorithms root branch (only one for the study)
2668     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
2669       // create algorithms root HDF group
2670       aTopGroup = new HDFgroup( "Algorithms", aFile );
2671       aTopGroup->CreateOnDisk();
2672
2673       // iterator for all algorithms
2674       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2675       for ( ; it->More(); it->Next() ) {
2676         SALOMEDS::SObject_var mySObject = it->Value();
2677         CORBA::Object_var anObject = SObjectToObject( mySObject );
2678         if ( !CORBA::is_nil( anObject ) ) {
2679           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2680           if ( !myHyp->_is_nil() ) {
2681             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2682             if ( myImpl ) {
2683               string hypname = string( myHyp->GetName() );
2684               string libname = string( myHyp->GetLibName() );
2685               // BUG SWP13062
2686               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2687               // WNT and ".so" for X-system) must be deleted
2688               int libname_len = libname.length();
2689 #ifdef WNT
2690               if( libname_len > 4 )
2691                 libname.resize( libname_len - 4 );
2692 #else
2693               // PAL17753 (Regresion: missing hypothesis in restored study)
2694               // "lib" also should be removed from the beginning
2695               //if( libname_len > 3 )
2696                 //libname.resize( libname_len - 3 );
2697               if( libname_len > 6 )
2698                 libname = libname.substr( 3, libname_len - 3 - 3 );
2699 #endif
2700               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2701               int    id      = myStudyContext->findId( string( objStr.in() ) );
2702               string hypdata = string( myImpl->SaveTo() );
2703
2704               // for each algorithm create HDF group basing on its id
2705               char hypGrpName[30];
2706               sprintf( hypGrpName, "Algorithm %d", id );
2707               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2708               aGroup->CreateOnDisk();
2709               // --> type name of algorithm
2710               aSize[0] = hypname.length() + 1;
2711               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2712               aDataset->CreateOnDisk();
2713               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2714               aDataset->CloseOnDisk();
2715               // --> server plugin library name of hypothesis
2716               aSize[0] = libname.length() + 1;
2717               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2718               aDataset->CreateOnDisk();
2719               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2720               aDataset->CloseOnDisk();
2721               // --> persistent data of algorithm
2722               aSize[0] = hypdata.length() + 1;
2723               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2724               aDataset->CreateOnDisk();
2725               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2726               aDataset->CloseOnDisk();
2727               // close algorithm HDF group
2728               aGroup->CloseOnDisk();
2729             }
2730           }
2731         }
2732       }
2733       // close algorithms root HDF group
2734       aTopGroup->CloseOnDisk();
2735     }
2736     // --> mesh objects roots branches
2737     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2738       CORBA::Object_var anObject = SObjectToObject( gotBranch );
2739       if ( !CORBA::is_nil( anObject ) ) {
2740         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2741         if ( !myMesh->_is_nil() ) {
2742           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
2743           if ( myImpl ) {
2744             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2745             int id = myStudyContext->findId( string( objStr.in() ) );
2746             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
2747             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2748             bool hasShape = myLocMesh.HasShapeToMesh();
2749
2750             // for each mesh open the HDF group basing on its id
2751             char meshGrpName[ 30 ];
2752             sprintf( meshGrpName, "Mesh %d", id );
2753             aTopGroup = new HDFgroup( meshGrpName, aFile );
2754             aTopGroup->CreateOnDisk();
2755
2756             // --> put dataset to hdf file which is a flag that mesh has data
2757             string strHasData = "0";
2758             // check if the mesh is not empty
2759             if ( mySMESHDSMesh->NbNodes() > 0 ) {
2760               // write mesh data to med file
2761               myWriter.SetMesh( mySMESHDSMesh );
2762               myWriter.SetMeshId( id );
2763               strHasData = "1";
2764             }
2765             aSize[ 0 ] = strHasData.length() + 1;
2766             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
2767             aDataset->CreateOnDisk();
2768             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
2769             aDataset->CloseOnDisk();
2770
2771             // ouv : NPAL12872
2772             // for each mesh open the HDF group basing on its auto color parameter
2773             char meshAutoColorName[ 30 ];
2774             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
2775             int anAutoColor[1];
2776             anAutoColor[0] = myImpl->GetAutoColor();
2777             aSize[ 0 ] = 1;
2778             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
2779             aDataset->CreateOnDisk();
2780             aDataset->WriteOnDisk( anAutoColor );
2781             aDataset->CloseOnDisk();
2782
2783             // issue 0020693. Store _isModified flag
2784             int isModified = myLocMesh.GetIsModified();
2785             aSize[ 0 ] = 1;
2786             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
2787             aDataset->CreateOnDisk();
2788             aDataset->WriteOnDisk( &isModified );
2789             aDataset->CloseOnDisk();
2790
2791             // issue 20918. Store Persistent Id of SMESHDS_Mesh
2792             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
2793             aSize[ 0 ] = 1;
2794             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
2795             aDataset->CreateOnDisk();
2796             aDataset->WriteOnDisk( &meshPersistentId );
2797             aDataset->CloseOnDisk();
2798
2799             // write reference on a shape if exists
2800             SALOMEDS::SObject_var myRef;
2801             bool shapeRefFound = false;
2802             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
2803             if ( found ) {
2804               SALOMEDS::SObject_var myShape;
2805               bool ok = myRef->ReferencedObject( myShape );
2806               if ( ok ) {
2807                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
2808                 string myRefOnObject = myShape->GetID();
2809                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
2810                   aSize[ 0 ] = myRefOnObject.length() + 1;
2811                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
2812                   aDataset->CreateOnDisk();
2813                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2814                   aDataset->CloseOnDisk();
2815                 }
2816               }
2817             }
2818
2819             // write applied hypotheses if exist
2820             SALOMEDS::SObject_var myHypBranch;
2821             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
2822             if ( found && !shapeRefFound && hasShape) { // remove applied hyps
2823               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
2824             }
2825             if ( found && (shapeRefFound || !hasShape) ) {
2826               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2827               aGroup->CreateOnDisk();
2828
2829               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
2830               int hypNb = 0;
2831               for ( ; it->More(); it->Next() ) {
2832                 SALOMEDS::SObject_var mySObject = it->Value();
2833                 SALOMEDS::SObject_var myRefOnHyp;
2834                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
2835                 if ( ok ) {
2836                   // san - it is impossible to recover applied hypotheses
2837                   //       using their entries within Load() method,
2838                   // for there are no AttributeIORs in the study when Load() is working. 
2839                   // Hence, it is better to store persistent IDs of hypotheses as references to them
2840
2841                   //string myRefOnObject = myRefOnHyp->GetID();
2842                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
2843                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2844                   int id = myStudyContext->findId( string( objStr.in() ) );
2845                   //if ( myRefOnObject.length() > 0 ) {
2846                   //aSize[ 0 ] = myRefOnObject.length() + 1;
2847                   char hypName[ 30 ], hypId[ 30 ];
2848                   sprintf( hypName, "Hyp %d", ++hypNb );
2849                   sprintf( hypId, "%d", id );
2850                   aSize[ 0 ] = strlen( hypId ) + 1;
2851                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
2852                   aDataset->CreateOnDisk();
2853                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2854                   aDataset->WriteOnDisk( hypId );
2855                   aDataset->CloseOnDisk();
2856                   //}
2857                 }
2858               }
2859               aGroup->CloseOnDisk();
2860             }
2861
2862             // write applied algorithms if exist
2863             SALOMEDS::SObject_var myAlgoBranch;
2864             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
2865             if ( found && !shapeRefFound && hasShape) { // remove applied algos
2866               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
2867             }
2868             if ( found && (shapeRefFound || !hasShape)) {
2869               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
2870               aGroup->CreateOnDisk();
2871
2872               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
2873               int algoNb = 0;
2874               for ( ; it->More(); it->Next() ) {
2875                 SALOMEDS::SObject_var mySObject = it->Value();
2876                 SALOMEDS::SObject_var myRefOnAlgo;
2877                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
2878                 if ( ok ) {
2879                   // san - it is impossible to recover applied algorithms
2880                   //       using their entries within Load() method,
2881                   // for there are no AttributeIORs in the study when Load() is working. 
2882                   // Hence, it is better to store persistent IDs of algorithms as references to them
2883
2884                   //string myRefOnObject = myRefOnAlgo->GetID();
2885                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
2886                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2887                   int id = myStudyContext->findId( string( objStr.in() ) );
2888                   //if ( myRefOnObject.length() > 0 ) {
2889                   //aSize[ 0 ] = myRefOnObject.length() + 1;
2890                   char algoName[ 30 ], algoId[ 30 ];
2891                   sprintf( algoName, "Algo %d", ++algoNb );
2892                   sprintf( algoId, "%d", id );
2893                   aSize[ 0 ] = strlen( algoId ) + 1;
2894                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
2895                   aDataset->CreateOnDisk();
2896                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2897                   aDataset->WriteOnDisk( algoId );
2898                   aDataset->CloseOnDisk();
2899                   //}
2900                 }
2901               }
2902               aGroup->CloseOnDisk();
2903             }
2904
2905             // --> submesh objects sub-branches
2906
2907             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
2908               SALOMEDS::SObject_var mySubmeshBranch;
2909               found = gotBranch->FindSubObject( i, mySubmeshBranch );
2910
2911               if ( found ) // check if there is shape reference in submeshes
2912               {
2913                 bool hasShapeRef = false;
2914                 SALOMEDS::ChildIterator_var itSM =
2915                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
2916                 for ( ; itSM->More(); itSM->Next() ) {
2917                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
2918                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
2919                     mySubRef->ReferencedObject( myShape );
2920                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
2921                     hasShapeRef = true;
2922                   else
2923                   { // remove one submesh
2924                     if ( shapeRefFound )
2925                     { // unassign hypothesis
2926                       SMESH::SMESH_subMesh_var mySubMesh =
2927                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
2928                       if ( !mySubMesh->_is_nil() ) {
2929                         int shapeID = mySubMesh->GetId();
2930                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
2931                         const list<const SMESHDS_Hypothesis*>& hypList =
2932                           mySMESHDSMesh->GetHypothesis( S );
2933                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
2934                         while ( hyp != hypList.end() ) {
2935                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
2936                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
2937                         }
2938                       }
2939                     }
2940                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
2941                   }
2942                 } // loop on submeshes of a type
2943                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
2944                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
2945                   found = false;
2946                 }
2947               }  // end check if there is shape reference in submeshes
2948               if ( found ) {
2949                 char name_meshgroup[ 30 ];
2950                 if ( i == GetSubMeshOnVertexTag() )
2951                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
2952                 else if ( i == GetSubMeshOnEdgeTag() )
2953                   strcpy( name_meshgroup, "SubMeshes On Edge" );
2954                 else if ( i == GetSubMeshOnWireTag() )
2955                   strcpy( name_meshgroup, "SubMeshes On Wire" );
2956                 else if ( i == GetSubMeshOnFaceTag() )
2957                   strcpy( name_meshgroup, "SubMeshes On Face" );
2958                 else if ( i == GetSubMeshOnShellTag() )
2959                   strcpy( name_meshgroup, "SubMeshes On Shell" );
2960                 else if ( i == GetSubMeshOnSolidTag() )
2961                   strcpy( name_meshgroup, "SubMeshes On Solid" );
2962                 else if ( i == GetSubMeshOnCompoundTag() )
2963                   strcpy( name_meshgroup, "SubMeshes On Compound" );
2964
2965                 // for each type of submeshes create container HDF group
2966                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2967                 aGroup->CreateOnDisk();
2968
2969                 // iterator for all submeshes of given type
2970                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
2971                 for ( ; itSM->More(); itSM->Next() ) {
2972                   SALOMEDS::SObject_var mySObject = itSM->Value();
2973                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
2974                   if ( !CORBA::is_nil( anSubObject ))
2975                   {
2976                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
2977                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
2978                     int subid = myStudyContext->findId( string( objStr.in() ) );
2979
2980                     // for each mesh open the HDF group basing on its id
2981                     char submeshGrpName[ 30 ];
2982                     sprintf( submeshGrpName, "SubMesh %d", subid );
2983                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
2984                     aSubGroup->CreateOnDisk();
2985
2986                     // write reference on a shape, already checked if it exists
2987                     SALOMEDS::SObject_var mySubRef, myShape;
2988                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
2989                       mySubRef->ReferencedObject( myShape );
2990                     string myRefOnObject = myShape->GetID();
2991                     if ( myRefOnObject.length() > 0 ) {
2992                       aSize[ 0 ] = myRefOnObject.length() + 1;
2993                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
2994                       aDataset->CreateOnDisk();
2995                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2996                       aDataset->CloseOnDisk();
2997                     }
2998
2999                     // write applied hypotheses if exist
3000                     SALOMEDS::SObject_var mySubHypBranch;
3001                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
3002                     if ( found ) {
3003                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3004                       aSubSubGroup->CreateOnDisk();
3005
3006                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
3007                       int hypNb = 0;
3008                       for ( ; it->More(); it->Next() ) {
3009                         SALOMEDS::SObject_var mySubSObject = it->Value();
3010                         SALOMEDS::SObject_var myRefOnHyp;
3011                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
3012                         if ( ok ) {
3013                           //string myRefOnObject = myRefOnHyp->GetID();
3014                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3015                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3016                           int id = myStudyContext->findId( string( objStr.in() ) );
3017                           //if ( myRefOnObject.length() > 0 ) {
3018                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3019                           char hypName[ 30 ], hypId[ 30 ];
3020                           sprintf( hypName, "Hyp %d", ++hypNb );
3021                           sprintf( hypId, "%d", id );
3022                           aSize[ 0 ] = strlen( hypId ) + 1;
3023                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3024                           aDataset->CreateOnDisk();
3025                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3026                           aDataset->WriteOnDisk( hypId );
3027                           aDataset->CloseOnDisk();
3028                           //}
3029                         }
3030                       }
3031                       aSubSubGroup->CloseOnDisk();
3032                     }
3033
3034                     // write applied algorithms if exist
3035                     SALOMEDS::SObject_var mySubAlgoBranch;
3036                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
3037                     if ( found ) {
3038                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3039                       aSubSubGroup->CreateOnDisk();
3040
3041                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3042                       int algoNb = 0;
3043                       for ( ; it->More(); it->Next() ) {
3044                         SALOMEDS::SObject_var mySubSObject = it->Value();
3045                         SALOMEDS::SObject_var myRefOnAlgo;
3046                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
3047                         if ( ok ) {
3048                           //string myRefOnObject = myRefOnAlgo->GetID();
3049                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3050                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3051                           int id = myStudyContext->findId( string( objStr.in() ) );
3052                           //if ( myRefOnObject.length() > 0 ) {
3053                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3054                           char algoName[ 30 ], algoId[ 30 ];
3055                           sprintf( algoName, "Algo %d", ++algoNb );
3056                           sprintf( algoId, "%d", id );
3057                           aSize[ 0 ] = strlen( algoId ) + 1;
3058                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3059                           aDataset->CreateOnDisk();
3060                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3061                           aDataset->WriteOnDisk( algoId );
3062                           aDataset->CloseOnDisk();
3063                           //}
3064                         }
3065                       }
3066                       aSubSubGroup->CloseOnDisk();
3067                     }
3068                     // close submesh HDF group
3069                     aSubGroup->CloseOnDisk();
3070                   }
3071                 }
3072                 // close container of submeshes by type HDF group
3073                 aGroup->CloseOnDisk();
3074               }
3075             }
3076             // All sub-meshes will be stored in MED file
3077             // .. will NOT (PAL 12992)
3078             //if ( shapeRefFound )
3079             //myWriter.AddAllSubMeshes();
3080
3081             // store submesh order if any
3082             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3083             if ( theOrderIds.size() ) {
3084               char order_list[ 30 ];
3085               strcpy( order_list, "Mesh Order" );
3086               // count number of submesh ids
3087               int nbIDs = 0;
3088               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3089               for ( ; idIt != theOrderIds.end(); idIt++ )
3090                 nbIDs += (*idIt).size();
3091               // number of values = number of IDs +
3092               //                    number of lists (for separators) - 1
3093               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3094               idIt = theOrderIds.begin();
3095               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3096                 const TListOfInt& idList = *idIt;
3097                 if (idIt != theOrderIds.begin()) // not first list
3098                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3099                 // dump submesh ids from current list
3100                 TListOfInt::const_iterator id_smId = idList.begin();
3101                 for( ; id_smId != idList.end(); id_smId++ )
3102                   smIDs[ i++ ] = *id_smId;
3103               }
3104               // write HDF group
3105               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3106
3107               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3108               aDataset->CreateOnDisk();
3109               aDataset->WriteOnDisk( smIDs );
3110               aDataset->CloseOnDisk();
3111               //
3112               delete[] smIDs;
3113             }
3114
3115             // groups root sub-branch
3116             SALOMEDS::SObject_var myGroupsBranch;
3117             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
3118               found = gotBranch->FindSubObject( i, myGroupsBranch );
3119               if ( found ) {
3120                 char name_group[ 30 ];
3121                 if ( i == GetNodeGroupsTag() )
3122                   strcpy( name_group, "Groups of Nodes" );
3123                 else if ( i == GetEdgeGroupsTag() )
3124                   strcpy( name_group, "Groups of Edges" );
3125                 else if ( i == GetFaceGroupsTag() )
3126                   strcpy( name_group, "Groups of Faces" );
3127                 else if ( i == GetVolumeGroupsTag() )
3128                   strcpy( name_group, "Groups of Volumes" );
3129
3130                 aGroup = new HDFgroup( name_group, aTopGroup );
3131                 aGroup->CreateOnDisk();
3132
3133                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3134                 for ( ; it->More(); it->Next() ) {
3135                   SALOMEDS::SObject_var mySObject = it->Value();
3136                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3137                   if ( !CORBA::is_nil( aSubObject ) ) {
3138                     SMESH_GroupBase_i* myGroupImpl =
3139                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3140                     if ( !myGroupImpl )
3141                       continue;
3142                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3143                     if ( !aGrpBaseDS )
3144                       continue;
3145                     
3146                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3147                     int anId = myStudyContext->findId( string( objStr.in() ) );
3148
3149                     // For each group, create a dataset named "Group <group_persistent_id>"
3150                     // and store the group's user name into it
3151                     const char* grpName = aGrpBaseDS->GetStoreName();
3152                     char* aUserName = myGroupImpl->GetName();
3153                     aSize[ 0 ] = strlen( aUserName ) + 1;
3154
3155                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3156                     aDataset->CreateOnDisk();
3157                     aDataset->WriteOnDisk( aUserName );
3158                     aDataset->CloseOnDisk();
3159
3160                     // ouv : NPAL12872
3161                     // For each group, create a dataset named "Group <group_persistent_id> Color"
3162                     // and store the group's color into it
3163                     char grpColorName[ 30 ];
3164                     sprintf( grpColorName, "ColorGroup %d", anId );
3165                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
3166                     double anRGB[3];
3167                     anRGB[ 0 ] = aColor.R;
3168                     anRGB[ 1 ] = aColor.G;
3169                     anRGB[ 2 ] = aColor.B;
3170                     aSize[ 0 ] = 3;
3171                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3172                     aDataset->CreateOnDisk();
3173                     aDataset->WriteOnDisk( anRGB );
3174                     aDataset->CloseOnDisk();
3175
3176                     // Pass SMESHDS_Group to MED writer 
3177                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3178                     if ( aGrpDS )
3179                       myWriter.AddGroup( aGrpDS );
3180
3181                     // write reference on a shape if exists
3182                     SMESHDS_GroupOnGeom* aGeomGrp =
3183                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3184                     if ( aGeomGrp ) {
3185                       SALOMEDS::SObject_var mySubRef, myShape;
3186                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
3187                           mySubRef->ReferencedObject( myShape ) &&
3188                           !CORBA::is_nil( myShape->GetObject() ))
3189                       {
3190                         string myRefOnObject = myShape->GetID();
3191                         if ( myRefOnObject.length() > 0 ) {
3192                           char aRefName[ 30 ];
3193                           sprintf( aRefName, "Ref on shape %d", anId);
3194                           aSize[ 0 ] = myRefOnObject.length() + 1;
3195                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3196                           aDataset->CreateOnDisk();
3197                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3198                           aDataset->CloseOnDisk();
3199                         }
3200                       }
3201                       else // shape ref is invalid:
3202                       {
3203                         // save a group on geometry as ordinary group
3204                         myWriter.AddGroup( aGeomGrp );
3205                       }
3206                     }
3207                   }
3208                 }
3209                 aGroup->CloseOnDisk();
3210               }
3211             } // loop on groups 
3212             
3213             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3214             {
3215               // Flush current mesh information into MED file
3216               myWriter.Perform();
3217               
3218               // maybe a shape was deleted in the study
3219               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3220                 TopoDS_Shape nullShape;
3221                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3222               }
3223               
3224               if ( !mySMESHDSMesh->SubMeshes().empty() )
3225               {
3226                 // Store submeshes
3227                 // ----------------
3228                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3229                 aGroup->CreateOnDisk();
3230                 
3231                 // each element belongs to one or none submesh,
3232                 // so for each node/element, we store a submesh ID
3233                 
3234                 // Make maps of submesh IDs of elements sorted by element IDs
3235                 typedef int TElemID;
3236                 typedef int TSubMID;
3237                 map< TElemID, TSubMID > eId2smId, nId2smId;
3238                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
3239                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
3240                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
3241                 SMDS_NodeIteratorPtr itNode;
3242                 SMDS_ElemIteratorPtr itElem;
3243                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3244                 {
3245                   TSubMID          aSubMeID = itSubM->first;
3246                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
3247                   if ( aSubMesh->IsComplexSubmesh() )
3248                     continue; // submesh containing other submeshs
3249                   // nodes
3250                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
3251                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
3252                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
3253                   // elements
3254                   hint = eId2smId.begin();
3255                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
3256                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
3257                 }
3258                 
3259                 // Care of elements that are not on submeshes
3260                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
3261                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
3262                     /*  --- stl_map.h says : */
3263                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
3264                     /*  first element (the key) is not already present in the %map.           */
3265                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
3266                 }
3267                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
3268                 if ( nbElems != eId2smId.size() ) {
3269                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
3270                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
3271                 }
3272                 
3273                 // Store submesh IDs
3274                 for ( int isNode = 0; isNode < 2; ++isNode )
3275                 {
3276                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
3277                   if ( id2smId.empty() ) continue;
3278                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
3279                   // make and fill array of submesh IDs
3280                   int* smIDs = new int [ id2smId.size() ];
3281                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
3282                     smIDs[ i ] = id_smId->second;
3283                   // write HDF group
3284                   aSize[ 0 ] = id2smId.size();
3285                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3286                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3287                   aDataset->CreateOnDisk();
3288                   aDataset->WriteOnDisk( smIDs );
3289                   aDataset->CloseOnDisk();
3290                   //
3291                   delete[] smIDs;
3292                 }
3293                 
3294                 // Store node positions on sub-shapes (SMDS_Position):
3295                 // ----------------------------------------------------
3296                 
3297                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3298                 aGroup->CreateOnDisk();
3299                 
3300                 // in aGroup, create 5 datasets to contain:
3301                 // "Nodes on Edges" - ID of node on edge
3302                 // "Edge positions" - U parameter on node on edge
3303                 // "Nodes on Faces" - ID of node on face
3304                 // "Face U positions" - U parameter of node on face
3305                 // "Face V positions" - V parameter of node on face
3306                 
3307                 // Find out nb of nodes on edges and faces
3308                 // Collect corresponing sub-meshes
3309                 int nbEdgeNodes = 0, nbFaceNodes = 0;
3310                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3311                 // loop on SMESHDS_SubMesh'es
3312                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3313                 {
3314                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
3315                   if ( aSubMesh->IsComplexSubmesh() )
3316                     continue; // submesh containing other submeshs
3317                   int nbNodes = aSubMesh->NbNodes();
3318                   if ( nbNodes == 0 ) continue;
3319                   
3320                   int aShapeID = (*itSubM).first;
3321                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3322                     continue;
3323                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3324                   // write only SMDS_FacePosition and SMDS_EdgePosition
3325                   switch ( aShapeType ) {
3326                   case TopAbs_FACE:
3327                     nbFaceNodes += nbNodes;
3328                     aFaceSM.push_back( aSubMesh );
3329                     break;
3330                   case TopAbs_EDGE:
3331                     nbEdgeNodes += nbNodes;
3332                     aEdgeSM.push_back( aSubMesh );
3333                     break;
3334                   default:
3335                     continue;
3336                   }
3337                 }
3338                 // Treat positions on edges or faces
3339                 for ( int onFace = 0; onFace < 2; onFace++ )
3340                 {
3341                   // Create arrays to store in datasets
3342                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3343                   if (!nbNodes) continue;
3344                   int* aNodeIDs = new int [ nbNodes ];
3345                   double* aUPos = new double [ nbNodes ];
3346                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3347                   
3348                   // Fill arrays
3349                   // loop on sub-meshes
3350                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3351                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3352                   for ( ; itSM != pListSM->end(); itSM++ )
3353                   {
3354                     SMESHDS_SubMesh* aSubMesh = (*itSM);
3355                     
3356                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3357                     // loop on nodes in aSubMesh
3358                     while ( itNode->more() )
3359                     {
3360                       //node ID
3361                       const SMDS_MeshNode* node = itNode->next();
3362                       aNodeIDs [ iNode ] = node->GetID();
3363                       
3364                       // Position
3365                       const SMDS_PositionPtr pos = node->GetPosition();
3366                       if ( onFace ) { // on FACE
3367                         const SMDS_FacePosition* fPos =
3368                           dynamic_cast<const SMDS_FacePosition*>( pos );
3369                         if ( fPos ) {
3370                           aUPos[ iNode ] = fPos->GetUParameter();
3371                           aVPos[ iNode ] = fPos->GetVParameter();
3372                           iNode++;
3373                         }
3374                         else
3375                           nbNodes--;
3376                       }
3377                       else { // on EDGE
3378                         const SMDS_EdgePosition* ePos =
3379                           dynamic_cast<const SMDS_EdgePosition*>( pos );
3380                         if ( ePos ) {
3381                           aUPos[ iNode ] = ePos->GetUParameter();
3382                           iNode++;
3383                         }
3384                         else
3385                           nbNodes--;
3386                       }
3387                     } // loop on nodes in aSubMesh
3388                   } // loop on sub-meshes
3389                   
3390                   // Write datasets
3391                   if ( nbNodes )
3392                   {
3393                     aSize[ 0 ] = nbNodes;
3394                     // IDS
3395                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3396                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3397                     aDataset->CreateOnDisk();
3398                     aDataset->WriteOnDisk( aNodeIDs );
3399                     aDataset->CloseOnDisk();
3400                 
3401                     // U Positions
3402                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
3403                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3404                     aDataset->CreateOnDisk();
3405                     aDataset->WriteOnDisk( aUPos );
3406                     aDataset->CloseOnDisk();
3407                     // V Positions
3408                     if ( onFace ) {
3409                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3410                       aDataset->CreateOnDisk();
3411                       aDataset->WriteOnDisk( aVPos );
3412                       aDataset->CloseOnDisk();
3413                     }
3414                   }
3415                   delete [] aNodeIDs;
3416                   delete [] aUPos;
3417                   if ( aVPos ) delete [] aVPos;
3418                   
3419                 } // treat positions on edges or faces
3420                 
3421                 // close "Node Positions" group
3422                 aGroup->CloseOnDisk(); 
3423                 
3424               } // if ( there are submeshes in SMESHDS_Mesh )
3425             } // if ( hasData )
3426             
3427             // close mesh HDF group
3428             aTopGroup->CloseOnDisk();
3429           }
3430         }
3431       }
3432     }
3433   }
3434   
3435   // close HDF file
3436   aFile->CloseOnDisk();
3437   delete aFile;
3438
3439   // Convert temporary files to stream
3440   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3441
3442   // Remove temporary files and directory
3443   if ( !isMultiFile ) 
3444     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3445
3446   INFOS( "SMESH_Gen_i::Save() completed" );
3447   return aStreamFile._retn();
3448 }
3449
3450 //=============================================================================
3451 /*!
3452  *  SMESH_Gen_i::SaveASCII
3453  *
3454  *  Save SMESH module's data in ASCII format
3455  */
3456 //=============================================================================
3457
3458 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3459                                            const char*              theURL,
3460                                            bool                     isMultiFile ) {
3461   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3462   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3463   return aStreamFile._retn();
3464
3465   //after usual saving needs to encipher binary to text string
3466   //Any binary symbol will be represent as "|xx" () hexadecimal format number
3467   int size = aStreamFile.in().length();
3468   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3469   for ( int i = 0; i < size; i++ )
3470     sprintf( (char*)&(buffer[i*3]), "|%02x", (char*)(aStreamFile[i]) );
3471
3472   buffer[size * 3] = '\0';
3473
3474   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3475   
3476   return anAsciiStreamFile._retn();
3477 }
3478
3479 //=============================================================================
3480 /*!
3481  *  SMESH_Gen_i::loadGeomData
3482  *
3483  *  Load GEOM module data
3484  */
3485 //=============================================================================
3486
3487 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3488 {
3489   if ( theCompRoot->_is_nil() )
3490     return;
3491
3492   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3493   if ( aStudy->_is_nil() )
3494     return;
3495
3496   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
3497   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3498 }
3499 //=============================================================================
3500 /*!
3501  * \brief Creates SMDS_Position according to shape type
3502  */
3503 //=============================================================================
3504
3505 class PositionCreator {
3506 public:
3507   SMDS_PositionPtr MakePosition(const TopAbs_ShapeEnum type) {
3508     return (this->*myFuncTable[ type ])();
3509   }
3510   PositionCreator() {
3511     myFuncTable.resize( (size_t) TopAbs_SHAPE, & PositionCreator::defaultPosition );
3512     myFuncTable[ TopAbs_SOLID  ] = & PositionCreator::volumePosition;
3513     myFuncTable[ TopAbs_FACE   ] = & PositionCreator::facePosition;
3514     myFuncTable[ TopAbs_EDGE   ] = & PositionCreator::edgePosition;
3515     myFuncTable[ TopAbs_VERTEX ] = & PositionCreator::vertexPosition;
3516   }
3517 private:
3518   SMDS_PositionPtr edgePosition()    const { return SMDS_PositionPtr( new SMDS_EdgePosition  ); }
3519   SMDS_PositionPtr facePosition()    const { return SMDS_PositionPtr( new SMDS_FacePosition  ); }
3520   SMDS_PositionPtr volumePosition()  const { return SMDS_PositionPtr( new SMDS_SpacePosition ); }
3521   SMDS_PositionPtr vertexPosition()  const { return SMDS_PositionPtr( new SMDS_VertexPosition); }
3522   SMDS_PositionPtr defaultPosition() const { return SMDS_SpacePosition::originSpacePosition();  }
3523   typedef SMDS_PositionPtr (PositionCreator:: * FmakePos)() const;
3524   vector<FmakePos> myFuncTable;
3525 };
3526
3527 //=============================================================================
3528 /*!
3529  *  SMESH_Gen_i::Load
3530  *
3531  *  Load SMESH module's data
3532  */
3533 //=============================================================================
3534
3535 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3536                         const SALOMEDS::TMPFile& theStream,
3537                         const char*              theURL,
3538                         bool                     isMultiFile )
3539 {
3540   INFOS( "SMESH_Gen_i::Load" );
3541
3542   if ( myCurrentStudy->_is_nil() || 
3543        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
3544     SetCurrentStudy( theComponent->GetStudy() );
3545
3546   /*  if( !theComponent->_is_nil() )
3547       {
3548       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
3549       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
3550       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
3551       }*/
3552
3553   StudyContext* myStudyContext = GetCurrentStudyContext();
3554
3555   // Get temporary files location
3556   TCollection_AsciiString tmpDir =
3557     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3558     
3559     INFOS( "THE URL++++++++++++++" )
3560     INFOS( theURL );
3561     INFOS( "THE TMP PATH+++++++++" );
3562     INFOS( tmpDir );
3563
3564   // Convert the stream into sequence of files to process
3565   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
3566                                                                             tmpDir.ToCString(),
3567                                                                             isMultiFile );
3568   TCollection_AsciiString aStudyName( "" );
3569   if ( isMultiFile ) 
3570     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3571
3572   // Set names of temporary files
3573   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
3574   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
3575
3576   int size;
3577   HDFfile*    aFile;
3578   HDFdataset* aDataset;
3579   HDFgroup*   aTopGroup;
3580   HDFgroup*   aGroup;
3581   HDFgroup*   aSubGroup;
3582   HDFgroup*   aSubSubGroup;
3583
3584   // Read data
3585   // ---> open HDF file
3586   aFile = new HDFfile( (char*) filename.ToCString() );
3587   try {
3588     aFile->OpenOnDisk( HDF_RDONLY );
3589   }
3590   catch ( HDFexception ) {
3591     INFOS( "Load(): " << filename << " not found!" );
3592     return false;
3593   }
3594
3595   DriverMED_R_SMESHDS_Mesh myReader;
3596   myReader.SetFile( meshfile.ToCString() );
3597
3598   // For PAL13473 ("Repetitive mesh") implementation.
3599   // New dependencies between SMESH objects are established:
3600   // now hypotheses can refer to meshes, shapes and other hypotheses.
3601   // To keep data consistent, the following order of data restoration
3602   // imposed:
3603   // 1. Create hypotheses
3604   // 2. Create all meshes
3605   // 3. Load hypotheses' data
3606   // 4. All the rest
3607
3608   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
3609   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
3610
3611   // get total number of top-level groups
3612   int aNbGroups = aFile->nInternalObjects(); 
3613   if ( aNbGroups > 0 ) {
3614     // --> in first turn we should read&create hypotheses
3615     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
3616       // open hypotheses root HDF group
3617       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
3618       aTopGroup->OpenOnDisk();
3619
3620       // get number of hypotheses
3621       int aNbObjects = aTopGroup->nInternalObjects(); 
3622       for ( int j = 0; j < aNbObjects; j++ ) {
3623         // try to identify hypothesis
3624         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3625         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3626
3627         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
3628           // open hypothesis group
3629           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
3630           aGroup->OpenOnDisk();
3631
3632           // --> get hypothesis id
3633           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
3634           string hypname;
3635           string libname;
3636           string hypdata;
3637
3638           // get number of datasets
3639           int aNbSubObjects = aGroup->nInternalObjects();
3640           for ( int k = 0; k < aNbSubObjects; k++ ) {
3641             // identify dataset
3642             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3643             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3644             // --> get hypothesis name
3645             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3646               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3647               aDataset->OpenOnDisk();
3648               size = aDataset->GetSize();
3649               char* hypname_str = new char[ size ];
3650               aDataset->ReadFromDisk( hypname_str );
3651               hypname = string( hypname_str );
3652               delete [] hypname_str;
3653               aDataset->CloseOnDisk();
3654             }
3655             // --> get hypothesis plugin library name
3656             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3657               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3658               aDataset->OpenOnDisk();
3659               size = aDataset->GetSize();
3660               char* libname_str = new char[ size ];
3661               aDataset->ReadFromDisk( libname_str );
3662               if(MYDEBUG) SCRUTE( libname_str );
3663               libname = string( libname_str );
3664               delete [] libname_str;
3665               aDataset->CloseOnDisk();
3666             }
3667             // --> get hypothesis data
3668             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3669               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3670               aDataset->OpenOnDisk();
3671               size = aDataset->GetSize();
3672               char* hypdata_str = new char[ size ];
3673               aDataset->ReadFromDisk( hypdata_str );
3674               hypdata = string( hypdata_str );
3675               delete [] hypdata_str;
3676               aDataset->CloseOnDisk();
3677             }
3678           }
3679           // close hypothesis HDF group
3680           aGroup->CloseOnDisk();
3681
3682           // --> restore hypothesis from data
3683           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3684             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
3685                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3686             SMESH::SMESH_Hypothesis_var myHyp;
3687
3688             try { // protect persistence mechanism against exceptions
3689               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3690             }
3691             catch (...) {
3692               INFOS( "Exception during hypothesis creation" );
3693             }
3694
3695             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3696             if ( myImpl ) {
3697               // myImpl->LoadFrom( hypdata.c_str() );
3698               hypDataList.push_back( make_pair( myImpl, hypdata ));
3699               string iorString = GetORB()->object_to_string( myHyp );
3700               int newId = myStudyContext->findId( iorString );
3701               myStudyContext->mapOldToNew( id, newId );
3702             }
3703             else
3704               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
3705           }
3706         }
3707       }
3708       // close hypotheses root HDF group
3709       aTopGroup->CloseOnDisk();
3710       aTopGroup = 0;
3711     }
3712
3713     // --> then we should read&create algorithms
3714     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
3715       // open algorithms root HDF group
3716       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
3717       aTopGroup->OpenOnDisk();
3718
3719       // get number of algorithms
3720       int aNbObjects = aTopGroup->nInternalObjects(); 
3721       for ( int j = 0; j < aNbObjects; j++ ) {
3722         // try to identify algorithm
3723         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3724         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3725
3726         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
3727           // open algorithm group
3728           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
3729           aGroup->OpenOnDisk();
3730
3731           // --> get algorithm id
3732           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
3733           string hypname;
3734           string libname;
3735           string hypdata;
3736
3737           // get number of datasets
3738           int aNbSubObjects = aGroup->nInternalObjects();
3739           for ( int k = 0; k < aNbSubObjects; k++ ) {
3740             // identify dataset
3741             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3742             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3743             // --> get algorithm name
3744             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3745               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3746               aDataset->OpenOnDisk();
3747               size = aDataset->GetSize();
3748               char* hypname_str = new char[ size ];
3749               aDataset->ReadFromDisk( hypname_str );
3750               hypname = string( hypname_str );
3751               delete [] hypname_str;
3752               aDataset->CloseOnDisk();
3753             }
3754             // --> get algorithm plugin library name
3755             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3756               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3757               aDataset->OpenOnDisk();
3758               size = aDataset->GetSize();
3759               char* libname_str = new char[ size ];
3760               aDataset->ReadFromDisk( libname_str );
3761               if(MYDEBUG) SCRUTE( libname_str );
3762               libname = string( libname_str );
3763               delete [] libname_str;
3764               aDataset->CloseOnDisk();
3765             }
3766             // --> get algorithm data
3767             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3768               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3769               aDataset->OpenOnDisk();
3770               size = aDataset->GetSize();
3771               char* hypdata_str = new char[ size ];
3772               aDataset->ReadFromDisk( hypdata_str );
3773               if(MYDEBUG) SCRUTE( hypdata_str );
3774               hypdata = string( hypdata_str );
3775               delete [] hypdata_str;
3776               aDataset->CloseOnDisk();
3777             }
3778           }
3779           // close algorithm HDF group
3780           aGroup->CloseOnDisk();
3781
3782           // --> restore algorithm from data
3783           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3784             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
3785                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3786             SMESH::SMESH_Hypothesis_var myHyp;
3787
3788             try { // protect persistence mechanism against exceptions
3789               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3790             }
3791             catch (...) {
3792               INFOS( "Exception during hypothesis creation" );
3793             }
3794
3795             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3796             if ( myImpl ) {
3797               //myImpl->LoadFrom( hypdata.c_str() );
3798               hypDataList.push_back( make_pair( myImpl, hypdata ));
3799               string iorString = GetORB()->object_to_string( myHyp );
3800               int newId = myStudyContext->findId( iorString );
3801               myStudyContext->mapOldToNew( id, newId );
3802             }
3803             else
3804               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
3805           }
3806         }
3807       }
3808       // close algorithms root HDF group
3809       aTopGroup->CloseOnDisk();
3810       aTopGroup = 0;
3811     }
3812
3813     // --> the rest groups should be meshes
3814     for ( int i = 0; i < aNbGroups; i++ ) {
3815       // identify next group
3816       char meshName[ HDF_NAME_MAX_LEN+1 ];
3817       aFile->InternalObjectIndentify( i, meshName );
3818
3819       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
3820         // --> get mesh id
3821         int id = atoi( string( meshName ).substr( 4 ).c_str() );
3822         if ( id <= 0 )
3823           continue;
3824
3825         // open mesh HDF group
3826         aTopGroup = new HDFgroup( meshName, aFile ); 
3827         aTopGroup->OpenOnDisk();
3828
3829         // get number of child HDF objects
3830         int aNbObjects = aTopGroup->nInternalObjects(); 
3831         if ( aNbObjects > 0 ) {
3832           // create mesh
3833           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
3834           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
3835           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
3836           if ( !myNewMeshImpl )
3837             continue;
3838           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
3839
3840           string iorString = GetORB()->object_to_string( myNewMesh );
3841           int newId = myStudyContext->findId( iorString );
3842           myStudyContext->mapOldToNew( id, newId );
3843
3844           // ouv : NPAL12872
3845           // try to read and set auto color flag
3846           char aMeshAutoColorName[ 30 ];
3847           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
3848           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
3849           {
3850             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
3851             aDataset->OpenOnDisk();
3852             size = aDataset->GetSize();
3853             int* anAutoColor = new int[ size ];
3854             aDataset->ReadFromDisk( anAutoColor );
3855             aDataset->CloseOnDisk();
3856             myNewMeshImpl->SetAutoColor( (bool)anAutoColor[0] );
3857           }
3858
3859           // try to read and set reference to shape
3860           GEOM::GEOM_Object_var aShapeObject;
3861           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
3862             // load mesh "Ref on shape" - it's an entry to SObject
3863             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
3864             aDataset->OpenOnDisk();
3865             size = aDataset->GetSize();
3866             char* refFromFile = new char[ size ];
3867             aDataset->ReadFromDisk( refFromFile );
3868             aDataset->CloseOnDisk();
3869             if ( strlen( refFromFile ) > 0 ) {
3870               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
3871
3872               // Make sure GEOM data are loaded first
3873               //loadGeomData( shapeSO->GetFatherComponent() );
3874
3875               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
3876               if ( !CORBA::is_nil( shapeObject ) ) {
3877                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
3878                 if ( !aShapeObject->_is_nil() )
3879                   myNewMeshImpl->SetShape( aShapeObject );
3880               }
3881             }
3882           }
3883
3884           // issue 0020693. Restore _isModified flag
3885           if( aTopGroup->ExistInternalObject( "_isModified" ) )
3886           {
3887             aDataset = new HDFdataset( "_isModified", aTopGroup );
3888             aDataset->OpenOnDisk();
3889             size = aDataset->GetSize();
3890             int* isModified = new int[ size ];
3891             aDataset->ReadFromDisk( isModified );
3892             aDataset->CloseOnDisk();
3893             myNewMeshImpl->GetImpl().SetIsModified( bool(*isModified));
3894           }
3895
3896           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
3897           if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
3898           {
3899             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
3900             aDataset->OpenOnDisk();
3901             size = aDataset->GetSize();
3902             int* meshPersistentId = new int[ size ];
3903             aDataset->ReadFromDisk( meshPersistentId );
3904             aDataset->CloseOnDisk();
3905             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
3906           }
3907         }
3908       }
3909     }
3910
3911     // As all object that can be referred by hypothesis are created,
3912     // we can restore hypothesis data
3913
3914     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
3915     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
3916     {
3917       SMESH_Hypothesis_i* hyp  = hyp_data->first;
3918       string &            data = hyp_data->second;
3919       hyp->LoadFrom( data.c_str() );
3920     }
3921
3922     // Restore the rest mesh data
3923
3924     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
3925     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
3926     {
3927       aTopGroup                   = meshi_group->second;
3928       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
3929       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
3930       SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3931
3932       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
3933       bool hasData = false;
3934
3935       // get mesh old id
3936       string iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
3937       int newId = myStudyContext->findId( iorString );
3938       int id = myStudyContext->getOldId( newId );
3939
3940       // try to find mesh data dataset
3941       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
3942         // load mesh "has data" flag
3943         aDataset = new HDFdataset( "Has data", aTopGroup );
3944         aDataset->OpenOnDisk();
3945         size = aDataset->GetSize();
3946         char* strHasData = new char[ size ];
3947         aDataset->ReadFromDisk( strHasData );
3948         aDataset->CloseOnDisk();
3949         if ( strcmp( strHasData, "1") == 0 ) {
3950           // read mesh data from MED file
3951           myReader.SetMesh( mySMESHDSMesh );
3952           myReader.SetMeshId( id );
3953           myReader.Perform();
3954           hasData = true;
3955         }
3956       }
3957
3958       // try to get applied algorithms
3959       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
3960         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3961         aGroup->OpenOnDisk();
3962         // get number of applied algorithms
3963         int aNbSubObjects = aGroup->nInternalObjects(); 
3964         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
3965         for ( int j = 0; j < aNbSubObjects; j++ ) {
3966           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3967           aGroup->InternalObjectIndentify( j, name_dataset );
3968           // check if it is an algorithm
3969           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
3970             aDataset = new HDFdataset( name_dataset, aGroup );
3971             aDataset->OpenOnDisk();
3972             size = aDataset->GetSize();
3973             char* refFromFile = new char[ size ];
3974             aDataset->ReadFromDisk( refFromFile );
3975             aDataset->CloseOnDisk();
3976
3977             // san - it is impossible to recover applied algorithms using their entries within Load() method
3978
3979             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3980             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3981             int id = atoi( refFromFile );
3982             string anIOR = myStudyContext->getIORbyOldId( id );
3983             if ( !anIOR.empty() ) {
3984               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3985               if ( !CORBA::is_nil( hypObject ) ) {
3986                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3987                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
3988                                            || !myNewMeshImpl->HasShapeToMesh()) )
3989                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
3990               }
3991             }
3992           }
3993         }
3994         aGroup->CloseOnDisk();
3995       }
3996
3997       // try to get applied hypotheses
3998       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
3999         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4000         aGroup->OpenOnDisk();
4001         // get number of applied hypotheses
4002         int aNbSubObjects = aGroup->nInternalObjects(); 
4003         for ( int j = 0; j < aNbSubObjects; j++ ) {
4004           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4005           aGroup->InternalObjectIndentify( j, name_dataset );
4006           // check if it is a hypothesis
4007           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4008             aDataset = new HDFdataset( name_dataset, aGroup );
4009             aDataset->OpenOnDisk();
4010             size = aDataset->GetSize();
4011             char* refFromFile = new char[ size ];
4012             aDataset->ReadFromDisk( refFromFile );
4013             aDataset->CloseOnDisk();
4014
4015             // san - it is impossible to recover applied hypotheses using their entries within Load() method
4016
4017             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4018             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4019             int id = atoi( refFromFile );
4020             string anIOR = myStudyContext->getIORbyOldId( id );
4021             if ( !anIOR.empty() ) {
4022               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4023               if ( !CORBA::is_nil( hypObject ) ) {
4024                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4025                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4026                                            || !myNewMeshImpl->HasShapeToMesh()) )
4027                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4028               }
4029             }
4030           }
4031         }
4032         aGroup->CloseOnDisk();
4033       }
4034
4035       // --> try to find submeshes containers for each type of submesh
4036       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4037         char name_meshgroup[ 30 ];
4038         if ( j == GetSubMeshOnVertexTag() )
4039           strcpy( name_meshgroup, "SubMeshes On Vertex" );
4040         else if ( j == GetSubMeshOnEdgeTag() )
4041           strcpy( name_meshgroup, "SubMeshes On Edge" );
4042         else if ( j == GetSubMeshOnWireTag() )
4043           strcpy( name_meshgroup, "SubMeshes On Wire" );
4044         else if ( j == GetSubMeshOnFaceTag() )
4045           strcpy( name_meshgroup, "SubMeshes On Face" );
4046         else if ( j == GetSubMeshOnShellTag() )
4047           strcpy( name_meshgroup, "SubMeshes On Shell" );
4048         else if ( j == GetSubMeshOnSolidTag() )
4049           strcpy( name_meshgroup, "SubMeshes On Solid" );
4050         else if ( j == GetSubMeshOnCompoundTag() )
4051           strcpy( name_meshgroup, "SubMeshes On Compound" );
4052
4053         // try to get submeshes container HDF group
4054         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4055           // open submeshes containers HDF group
4056           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4057           aGroup->OpenOnDisk();
4058
4059           // get number of submeshes
4060           int aNbSubMeshes = aGroup->nInternalObjects(); 
4061           for ( int k = 0; k < aNbSubMeshes; k++ ) {
4062             // identify submesh
4063             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4064             aGroup->InternalObjectIndentify( k, name_submeshgroup );
4065             if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
4066               // --> get submesh id
4067               int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
4068               if ( subid <= 0 )
4069                 continue;
4070               // open submesh HDF group
4071               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4072               aSubGroup->OpenOnDisk();
4073
4074               // try to read and set reference to subshape
4075               GEOM::GEOM_Object_var aSubShapeObject;
4076               SMESH::SMESH_subMesh_var aSubMesh;
4077
4078               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4079                 // load submesh "Ref on shape" - it's an entry to SObject
4080                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4081                 aDataset->OpenOnDisk();
4082                 size = aDataset->GetSize();
4083                 char* refFromFile = new char[ size ];
4084                 aDataset->ReadFromDisk( refFromFile );
4085                 aDataset->CloseOnDisk();
4086                 if ( strlen( refFromFile ) > 0 ) {
4087                   SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4088                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4089                   if ( !CORBA::is_nil( subShapeObject ) ) {
4090                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4091                     if ( !aSubShapeObject->_is_nil() )
4092                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
4093                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4094                     if ( aSubMesh->_is_nil() )
4095                       continue;
4096                     string iorSubString = GetORB()->object_to_string( aSubMesh );
4097                     int newSubId = myStudyContext->findId( iorSubString );
4098                     myStudyContext->mapOldToNew( subid, newSubId );
4099                   }
4100                 }
4101               }
4102
4103               if ( aSubMesh->_is_nil() )
4104                 continue;
4105
4106               // VSR: Get submesh data from MED convertor
4107               //                  int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
4108               //                  if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
4109               //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
4110               //                            subid << " for subshape # " << anInternalSubmeshId);
4111               //                    SMESHDS_SubMesh* aSubMeshDS =
4112               //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
4113               //                    if ( !aSubMeshDS ) {
4114               //                      if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
4115               //                              anInternalSubmeshId << " in current mesh!");
4116               //                    }
4117               //                    else
4118               //                      myReader.GetSubMesh( aSubMeshDS, subid );
4119               //                  }
4120
4121               // try to get applied algorithms
4122               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4123                 // open "applied algorithms" HDF group
4124                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4125                 aSubSubGroup->OpenOnDisk();
4126                 // get number of applied algorithms
4127                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
4128                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4129                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4130                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4131                   // check if it is an algorithm
4132                   if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4133                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4134                     aDataset->OpenOnDisk();
4135                     size = aDataset->GetSize();
4136                     char* refFromFile = new char[ size ];
4137                     aDataset->ReadFromDisk( refFromFile );
4138                     aDataset->CloseOnDisk();
4139
4140                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4141                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4142                     int id = atoi( refFromFile );
4143                     string anIOR = myStudyContext->getIORbyOldId( id );
4144                     if ( !anIOR.empty() ) {
4145                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4146                       if ( !CORBA::is_nil( hypObject ) ) {
4147                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4148                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4149                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4150                       }
4151                     }
4152                   }
4153                 }
4154                 // close "applied algorithms" HDF group
4155                 aSubSubGroup->CloseOnDisk();
4156               }
4157
4158               // try to get applied hypotheses
4159               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4160                 // open "applied hypotheses" HDF group
4161                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4162                 aSubSubGroup->OpenOnDisk();
4163                 // get number of applied hypotheses
4164                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
4165                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4166                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4167                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4168                   // check if it is a hypothesis
4169                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4170                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4171                     aDataset->OpenOnDisk();
4172                     size = aDataset->GetSize();
4173                     char* refFromFile = new char[ size ];
4174                     aDataset->ReadFromDisk( refFromFile );
4175                     aDataset->CloseOnDisk();
4176
4177                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4178                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4179                     int id = atoi( refFromFile );
4180                     string anIOR = myStudyContext->getIORbyOldId( id );
4181                     if ( !anIOR.empty() ) {
4182                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4183                       if ( !CORBA::is_nil( hypObject ) ) {
4184                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4185                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4186                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4187                       }
4188                     }
4189                   }
4190                 }
4191                 // close "applied hypotheses" HDF group
4192                 aSubSubGroup->CloseOnDisk();
4193               }
4194
4195               // close submesh HDF group
4196               aSubGroup->CloseOnDisk();
4197             }
4198           }
4199           // close submeshes containers HDF group
4200           aGroup->CloseOnDisk();
4201         }
4202       }
4203
4204       if(hasData) {
4205
4206         // Read sub-meshes from MED
4207         // -------------------------
4208         if(MYDEBUG) MESSAGE("Create all sub-meshes");
4209         bool submeshesInFamilies = ( ! aTopGroup->ExistInternalObject( "Submeshes" ));
4210         if ( submeshesInFamilies )
4211         {
4212           // old way working before fix of PAL 12992
4213           myReader.CreateAllSubMeshes();
4214         }
4215         else
4216         {
4217           // open a group
4218           aGroup = new HDFgroup( "Submeshes", aTopGroup ); 
4219           aGroup->OpenOnDisk();
4220
4221           int maxID = Max( mySMESHDSMesh->MaxSubMeshIndex(), mySMESHDSMesh->MaxShapeIndex() );
4222           vector< SMESHDS_SubMesh * > subMeshes( maxID + 1, (SMESHDS_SubMesh*) 0 );
4223           vector< TopAbs_ShapeEnum  > smType   ( maxID + 1, TopAbs_SHAPE ); 
4224
4225           PositionCreator aPositionCreator;
4226
4227           SMDS_NodeIteratorPtr nIt = mySMESHDSMesh->nodesIterator();
4228           SMDS_ElemIteratorPtr eIt = mySMESHDSMesh->elementsIterator();
4229           for ( int isNode = 0; isNode < 2; ++isNode )
4230           {
4231             string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4232             if ( aGroup->ExistInternalObject( (char*) aDSName.c_str() ))
4233             {
4234               aDataset = new HDFdataset( (char*) aDSName.c_str(), aGroup );
4235               aDataset->OpenOnDisk();
4236               // read submesh IDs for all elements sorted by ID
4237               int nbElems = aDataset->GetSize();
4238               int* smIDs = new int [ nbElems ];
4239               aDataset->ReadFromDisk( smIDs );
4240               aDataset->CloseOnDisk();
4241
4242               // get elements sorted by ID
4243               TIDSortedElemSet elemSet;
4244               if ( isNode )
4245                 while ( nIt->more() ) elemSet.insert( nIt->next() );
4246               else
4247                 while ( eIt->more() ) elemSet.insert( eIt->next() );
4248               //ASSERT( elemSet.size() == nbElems ); -- issue 20182
4249               // -- Most probably a bad study was saved when there were
4250               // not fixed bugs in SMDS_MeshInfo
4251               if ( elemSet.size() < nbElems ) {
4252 #ifdef _DEBUG_
4253                 cout << "SMESH_Gen_i::Load(), warning: Node position data is invalid" << endl;
4254 #endif
4255                 nbElems = elemSet.size();
4256               }
4257               // add elements to submeshes
4258               TIDSortedElemSet::iterator iE = elemSet.begin();
4259               for ( int i = 0; i < nbElems; ++i, ++iE )
4260               {
4261                 int smID = smIDs[ i ];
4262                 if ( smID == 0 ) continue;
4263                 const SMDS_MeshElement* elem = *iE;
4264                 if( smID > maxID ) {
4265                   // corresponding subshape no longer exists: maybe geom group has been edited
4266                   if ( myNewMeshImpl->HasShapeToMesh() )
4267                     mySMESHDSMesh->RemoveElement( elem );
4268                   continue;
4269                 }
4270                 // get or create submesh
4271                 SMESHDS_SubMesh* & sm = subMeshes[ smID ];
4272                 if ( ! sm ) {
4273                   sm = mySMESHDSMesh->NewSubMesh( smID );
4274                   smType[ smID ] = mySMESHDSMesh->IndexToShape( smID ).ShapeType();
4275                 }
4276                 // add
4277                 if ( isNode ) {
4278                   SMDS_PositionPtr pos = aPositionCreator.MakePosition( smType[ smID ]);
4279                   SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>( static_cast<const SMDS_MeshNode*>( elem ));
4280                   node->SetPosition( pos );
4281                   sm->AddNode( node );
4282                 } else {
4283                   sm->AddElement( elem );
4284                 }
4285               }
4286               delete [] smIDs;
4287             }
4288           }
4289         } // end reading submeshes
4290
4291         // Read node positions on sub-shapes (SMDS_Position)
4292
4293         if ( aTopGroup->ExistInternalObject( "Node Positions" ))
4294         {
4295           // There are 5 datasets to read:
4296           // "Nodes on Edges" - ID of node on edge
4297           // "Edge positions" - U parameter on node on edge
4298           // "Nodes on Faces" - ID of node on face
4299           // "Face U positions" - U parameter of node on face
4300           // "Face V positions" - V parameter of node on face
4301           const char* aEid_DSName = "Nodes on Edges";
4302           const char* aEu_DSName  = "Edge positions";
4303           const char* aFu_DSName  = "Face U positions";
4304           //char* aFid_DSName = "Nodes on Faces";
4305           //char* aFv_DSName  = "Face V positions";
4306
4307           // data to retrieve
4308           int nbEids = 0, nbFids = 0;
4309           int *aEids = 0, *aFids  = 0;
4310           double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
4311
4312           // open a group
4313           aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
4314           aGroup->OpenOnDisk();
4315
4316           // loop on 5 data sets
4317           int aNbObjects = aGroup->nInternalObjects();
4318           for ( int i = 0; i < aNbObjects; i++ )
4319           {
4320             // identify dataset
4321             char aDSName[ HDF_NAME_MAX_LEN+1 ];
4322             aGroup->InternalObjectIndentify( i, aDSName );
4323             // read data
4324             aDataset = new HDFdataset( aDSName, aGroup );
4325             aDataset->OpenOnDisk();
4326             if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
4327             {
4328               double* pos = new double [ aDataset->GetSize() ];
4329               aDataset->ReadFromDisk( pos );
4330               // which one?
4331               if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
4332                 aEpos = pos;
4333               else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
4334                 aFupos = pos;
4335               else
4336                 aFvpos = pos;
4337             }
4338             else // NODE IDS
4339             {
4340               int aSize = aDataset->GetSize();
4341
4342               // for reading files, created from 18.07.2005 till 10.10.2005
4343               if (aDataset->GetType() == HDF_STRING)
4344                 aSize /= sizeof(int);
4345
4346               int* ids = new int [aSize];
4347               aDataset->ReadFromDisk( ids );
4348               // on face or nodes?
4349               if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
4350                 aEids = ids;
4351                 nbEids = aSize;
4352               }
4353               else {
4354                 aFids = ids;
4355                 nbFids = aSize;
4356               }
4357             }
4358             aDataset->CloseOnDisk();
4359           } // loop on 5 datasets
4360
4361           // Set node positions on edges or faces
4362           for ( int onFace = 0; onFace < 2; onFace++ )
4363           {
4364             int nbNodes = ( onFace ? nbFids : nbEids );
4365             if ( nbNodes == 0 ) continue;
4366             int* aNodeIDs = ( onFace ? aFids : aEids );
4367             double* aUPos = ( onFace ? aFupos : aEpos );
4368             double* aVPos = ( onFace ? aFvpos : 0 );
4369             // loop on node IDs
4370             for ( int iNode = 0; iNode < nbNodes; iNode++ )
4371             {
4372               const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
4373               if ( !node ) continue; // maybe removed while Loading() if geometry changed
4374               SMDS_PositionPtr aPos = node->GetPosition();
4375               ASSERT( aPos );
4376               if ( onFace ) {
4377                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );-- issue 20182
4378                 // -- Most probably a bad study was saved when there were
4379                 // not fixed bugs in SMDS_MeshInfo
4380                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
4381                   SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
4382                     ( static_cast<const SMDS_FacePosition*>( aPos ));
4383                   fPos->SetUParameter( aUPos[ iNode ]);
4384                   fPos->SetVParameter( aVPos[ iNode ]);
4385                 }
4386               }
4387               else {
4388                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );-- issue 20182
4389                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE ) {
4390                   SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
4391                     ( static_cast<const SMDS_EdgePosition*>( aPos ));
4392                   fPos->SetUParameter( aUPos[ iNode ]);
4393                 }
4394               }
4395             }
4396           }
4397           if ( aEids ) delete [] aEids;
4398           if ( aFids ) delete [] aFids;
4399           if ( aEpos ) delete [] aEpos;
4400           if ( aFupos ) delete [] aFupos;
4401           if ( aFvpos ) delete [] aFvpos;
4402
4403           aGroup->CloseOnDisk();
4404
4405         } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
4406       } // if ( hasData )
4407
4408       // try to get groups
4409       for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
4410         char name_group[ 30 ];
4411         if ( ii == GetNodeGroupsTag() )
4412           strcpy( name_group, "Groups of Nodes" );
4413         else if ( ii == GetEdgeGroupsTag() )
4414           strcpy( name_group, "Groups of Edges" );
4415         else if ( ii == GetFaceGroupsTag() )
4416           strcpy( name_group, "Groups of Faces" );
4417         else if ( ii == GetVolumeGroupsTag() )
4418           strcpy( name_group, "Groups of Volumes" );
4419
4420         if ( aTopGroup->ExistInternalObject( name_group ) ) {
4421           aGroup = new HDFgroup( name_group, aTopGroup );
4422           aGroup->OpenOnDisk();
4423           // get number of groups
4424           int aNbSubObjects = aGroup->nInternalObjects(); 
4425           for ( int j = 0; j < aNbSubObjects; j++ ) {
4426             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4427             aGroup->InternalObjectIndentify( j, name_dataset );
4428             // check if it is an group
4429             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4430               // --> get group id
4431               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4432               if ( subid <= 0 )
4433                 continue;
4434               aDataset = new HDFdataset( name_dataset, aGroup );
4435               aDataset->OpenOnDisk();
4436
4437               // Retrieve actual group name
4438               size = aDataset->GetSize();
4439               char* nameFromFile = new char[ size ];
4440               aDataset->ReadFromDisk( nameFromFile );
4441               aDataset->CloseOnDisk();
4442
4443               // Try to find a shape reference
4444               TopoDS_Shape aShape;
4445               char aRefName[ 30 ];
4446               sprintf( aRefName, "Ref on shape %d", subid);
4447               if ( aGroup->ExistInternalObject( aRefName ) ) {
4448                 // load mesh "Ref on shape" - it's an entry to SObject
4449                 aDataset = new HDFdataset( aRefName, aGroup );
4450                 aDataset->OpenOnDisk();
4451                 size = aDataset->GetSize();
4452                 char* refFromFile = new char[ size ];
4453                 aDataset->ReadFromDisk( refFromFile );
4454                 aDataset->CloseOnDisk();
4455                 if ( strlen( refFromFile ) > 0 ) {
4456                   SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4457                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4458                   if ( !CORBA::is_nil( shapeObject ) ) {
4459                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4460                     if ( !aShapeObject->_is_nil() )
4461                       aShape = GeomObjectToShape( aShapeObject );
4462                   }
4463                 }
4464               }
4465               // Create group servant
4466               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4467               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4468                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
4469               // Obtain a SMESHDS_Group object 
4470               if ( aNewGroup->_is_nil() )
4471                 continue;
4472
4473               string iorSubString = GetORB()->object_to_string( aNewGroup );
4474               int newSubId = myStudyContext->findId( iorSubString );
4475               myStudyContext->mapOldToNew( subid, newSubId );
4476
4477               SMESH_GroupBase_i* aGroupImpl =
4478                 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
4479               if ( !aGroupImpl )
4480                 continue;
4481
4482               SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
4483               if ( !aLocalGroup )
4484                 continue;
4485
4486               SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
4487               aGroupBaseDS->SetStoreName( name_dataset );
4488
4489               // ouv : NPAL12872
4490               // Read color of the group
4491               char aGroupColorName[ 30 ];
4492               sprintf( aGroupColorName, "ColorGroup %d", subid);
4493               if ( aGroup->ExistInternalObject( aGroupColorName ) )
4494               {
4495                 aDataset = new HDFdataset( aGroupColorName, aGroup );
4496                 aDataset->OpenOnDisk();
4497                 size = aDataset->GetSize();
4498                 double* anRGB = new double[ size ];
4499                 aDataset->ReadFromDisk( anRGB );
4500                 aDataset->CloseOnDisk();
4501                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4502                 aGroupBaseDS->SetColor( aColor );
4503               }
4504
4505               // Fill group with contents from MED file
4506               SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
4507               if ( aGrp )
4508                 myReader.GetGroup( aGrp );
4509             }
4510           }
4511           aGroup->CloseOnDisk();
4512         }
4513       }
4514
4515       // read submeh order if any
4516       if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4517         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4518         aDataset->OpenOnDisk();
4519         size = aDataset->GetSize();
4520         int* smIDs = new int[ size ];
4521         aDataset->ReadFromDisk( smIDs );
4522         aDataset->CloseOnDisk();
4523         TListOfListOfInt anOrderIds;
4524         anOrderIds.push_back( TListOfInt() );
4525         for ( int i = 0; i < size; i++ )
4526           if ( smIDs[ i ] < 0 ) // is separator
4527             anOrderIds.push_back( TListOfInt() );
4528           else
4529             anOrderIds.back().push_back(smIDs[ i ]);
4530         
4531         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4532       }
4533     } // loop on meshes
4534
4535     // notify algos on completed restoration
4536     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4537     {
4538       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4539       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
4540
4541       TopoDS_Shape myLocShape;
4542       if(myLocMesh.HasShapeToMesh())
4543         myLocShape = myLocMesh.GetShapeToMesh();
4544       else
4545         myLocShape = SMESH_Mesh::PseudoShape();
4546         
4547       myLocMesh.GetSubMesh(myLocShape)->
4548         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4549     }
4550
4551     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4552     {
4553       SMESH_Hypothesis_i* hyp  = hyp_data->first;
4554       hyp->UpdateAsMeshesRestored(); // for hyps needing full mesh data restored (issue 20918)
4555     }
4556
4557     // close mesh group
4558     if(aTopGroup)
4559       aTopGroup->CloseOnDisk();   
4560   }
4561   // close HDF file
4562   aFile->CloseOnDisk();
4563   delete aFile;
4564
4565   // Remove temporary files created from the stream
4566   if ( !isMultiFile ) 
4567     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4568
4569   INFOS( "SMESH_Gen_i::Load completed" );
4570   return true;
4571 }
4572
4573 //=============================================================================
4574 /*!
4575  *  SMESH_Gen_i::LoadASCII
4576  *
4577  *  Load SMESH module's data in ASCII format
4578  */
4579 //=============================================================================
4580
4581 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4582                              const SALOMEDS::TMPFile& theStream,
4583                              const char*              theURL,
4584                              bool                     isMultiFile ) {
4585   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4586   return Load( theComponent, theStream, theURL, isMultiFile );
4587
4588   //before call main ::Load method it's need for decipher text format to
4589   //binary ( "|xx" => x' )
4590   int size = theStream.length();
4591   if ( int((size / 3 )*3) != size ) //error size of buffer
4592     return false;
4593
4594   int real_size = int(size / 3);
4595
4596   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4597   char tmp[3];
4598   tmp[2]='\0';
4599   int c = -1;
4600   for ( int i = 0; i < real_size; i++ )
4601   {
4602     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4603     sscanf( tmp, "%x", &c );
4604     sprintf( (char*)&(buffer[i]), "%c", (char)c );
4605   }
4606
4607   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4608   
4609   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4610 }
4611
4612 //=============================================================================
4613 /*!
4614  *  SMESH_Gen_i::Close
4615  *
4616  *  Clears study-connected data when it is closed
4617  */
4618 //=============================================================================
4619
4620 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4621 {
4622   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4623
4624   // set correct current study
4625   if (theComponent->GetStudy()->StudyId() != GetCurrentStudyID())
4626     SetCurrentStudy(theComponent->GetStudy());
4627
4628   // Clear study contexts data
4629   int studyId = GetCurrentStudyID();
4630   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4631     delete myStudyContextMap[ studyId ];
4632     myStudyContextMap.erase( studyId );
4633   }
4634
4635   // delete SMESH_Mesh's
4636 //   See bug IPAL19437.
4637 //
4638 //   StudyContextStruct* context = myGen.GetStudyContext( studyId );
4639 //   map< int, SMESH_Mesh* >::iterator i_mesh = context->mapMesh.begin();
4640 //   for ( ; i_mesh != context->mapMesh.end(); ++i_mesh ) {
4641 //     printf( "--------------------------- SMESH_Gen_i::Close, delete aGroup = %p \n", i_mesh->second );
4642 //     delete i_mesh->second;
4643 //   }
4644   
4645
4646   // delete SMESHDS_Mesh's
4647   // it's too long on big meshes
4648 //   if ( context->myDocument ) {
4649 //     delete context->myDocument;
4650 //     context->myDocument = 0;
4651 //   }
4652   
4653   myCurrentStudy = SALOMEDS::Study::_nil();
4654   return;
4655 }
4656
4657 //=============================================================================
4658 /*!
4659  *  SMESH_Gen_i::ComponentDataType
4660  * 
4661  *  Get component data type
4662  */
4663 //=============================================================================
4664
4665 char* SMESH_Gen_i::ComponentDataType()
4666 {
4667   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4668   return CORBA::string_dup( "SMESH" );
4669 }
4670
4671     
4672 //=============================================================================
4673 /*!
4674  *  SMESH_Gen_i::IORToLocalPersistentID
4675  *  
4676  *  Transform data from transient form to persistent
4677  */
4678 //=============================================================================
4679
4680 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4681                                            const char*           IORString,
4682                                            CORBA::Boolean        /*isMultiFile*/,
4683                                            CORBA::Boolean        /*isASCII*/ )
4684 {
4685   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4686   StudyContext* myStudyContext = GetCurrentStudyContext();
4687   
4688   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4689     int anId = myStudyContext->findId( IORString );
4690     if ( anId ) {
4691       if(MYDEBUG) MESSAGE( "VSR " << anId )
4692       char strId[ 20 ];
4693       sprintf( strId, "%d", anId );
4694       return  CORBA::string_dup( strId );
4695     }
4696   }
4697   return CORBA::string_dup( "" );
4698 }
4699
4700 //=============================================================================
4701 /*!
4702  *  SMESH_Gen_i::LocalPersistentIDToIOR
4703  *
4704  *  Transform data from persistent form to transient
4705  */
4706 //=============================================================================
4707
4708 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4709                                            const char*           aLocalPersistentID,
4710                                            CORBA::Boolean        /*isMultiFile*/,
4711                                            CORBA::Boolean        /*isASCII*/ )
4712 {
4713   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4714   StudyContext* myStudyContext = GetCurrentStudyContext();
4715
4716   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4717     int anId = atoi( aLocalPersistentID );
4718     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4719   }
4720   return CORBA::string_dup( "" );
4721 }
4722
4723 //=======================================================================
4724 //function : RegisterObject
4725 //purpose  : 
4726 //=======================================================================
4727
4728 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4729 {
4730   StudyContext* myStudyContext = GetCurrentStudyContext();
4731   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4732     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4733     return myStudyContext->addObject( string( iorString.in() ) );
4734   }
4735   return 0;
4736 }
4737
4738 //================================================================================
4739 /*!
4740  * \brief Return id of registered object
4741   * \param theObject - the Object
4742   * \retval int - Object id
4743  */
4744 //================================================================================
4745
4746 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
4747 {
4748   StudyContext* myStudyContext = GetCurrentStudyContext();
4749   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4750     string iorString = GetORB()->object_to_string( theObject );
4751     return myStudyContext->findId( iorString );
4752   }
4753   return 0;
4754 }
4755
4756 //=============================================================================
4757 /*!
4758  *  SMESH_Gen_i::SetName
4759  *
4760  *  Set a new object name
4761  */
4762 //=============================================================================
4763 void SMESH_Gen_i::SetName(const char* theIOR,
4764                           const char* theName)
4765 {
4766   if ( theIOR && strcmp( theIOR, "" ) ) {
4767     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
4768     SALOMEDS::SObject_var aSO = ObjectToSObject( myCurrentStudy, anObject );
4769     if ( !aSO->_is_nil() ) {
4770       SetName( aSO, theName );
4771     }
4772   }
4773 }
4774
4775 int SMESH_Gen_i::GetCurrentStudyID()
4776 {
4777   return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
4778 }
4779     
4780 //=============================================================================
4781 /*! 
4782  *  SMESHEngine_factory
4783  *
4784  *  C factory, accessible with dlsym, after dlopen  
4785  */
4786 //=============================================================================
4787
4788 extern "C"
4789 { SMESH_I_EXPORT
4790   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
4791                                                  PortableServer::POA_ptr   poa, 
4792                                                  PortableServer::ObjectId* contId,
4793                                                  const char*               instanceName, 
4794                                                  const char*               interfaceName )
4795   {
4796     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
4797     if(MYDEBUG) SCRUTE(interfaceName);
4798     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
4799     return aSMESHGen->getId() ;
4800   }
4801 }