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