Salome HOME
PR: merged from V5_1_4rc1
[modules/smesh.git] / src / SMESH_I / SMESH_Gen_i.cxx
1 //  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
24 //  File   : SMESH_Gen_i.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //
28 #include <TopExp.hxx>
29 #include <TopExp_Explorer.hxx>
30 #include <TopoDS.hxx>
31 #include <TopoDS_Iterator.hxx>
32 #include <TopoDS_Compound.hxx>
33 #include <TopoDS_CompSolid.hxx>
34 #include <TopoDS_Solid.hxx>
35 #include <TopoDS_Shell.hxx>
36 #include <TopoDS_Face.hxx>
37 #include <TopoDS_Wire.hxx>
38 #include <TopoDS_Edge.hxx>
39 #include <TopoDS_Vertex.hxx>
40 #include <TopoDS_Shape.hxx>
41 #include <TopTools_MapOfShape.hxx>
42 #include <TopTools_IndexedMapOfShape.hxx>
43 #include <TopTools_ListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <gp_Pnt.hxx>
46 #include <BRep_Tool.hxx>
47 #include <TCollection_AsciiString.hxx>
48 #include <OSD.hxx>
49
50 #include "Utils_CorbaException.hxx"
51
52 #include "utilities.h"
53 #include <fstream>
54 #include <stdio.h>
55
56 #ifdef WNT
57  #include <windows.h>
58  #include <process.h>
59 #else
60  #include <dlfcn.h>
61 #endif
62
63 #ifdef WNT
64  #define LibHandle HMODULE
65  #define LoadLib( name ) LoadLibrary( name )
66  #define GetProc GetProcAddress
67  #define UnLoadLib( handle ) FreeLibrary( handle );
68 #else
69  #define LibHandle void*
70  #define LoadLib( name ) dlopen( name, RTLD_LAZY )
71  #define GetProc dlsym
72  #define UnLoadLib( handle ) dlclose( handle );
73 #endif
74
75 #include <HDFOI.hxx>
76
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_Mesh_i.hxx"
79 #include "SMESH_Hypothesis_i.hxx"
80 #include "SMESH_Algo_i.hxx"
81 #include "SMESH_Group_i.hxx"
82 #include "SMESH_PythonDump.hxx"
83
84 #include "SMESHDS_Document.hxx"
85 #include "SMESHDS_Group.hxx"
86 #include "SMESHDS_GroupOnGeom.hxx"
87 #include "SMESH_Mesh.hxx"
88 #include "SMESH_Hypothesis.hxx"
89 #include "SMESH_Group.hxx"
90 #include "SMESH_MeshEditor.hxx"
91
92 #include "SMDS_EdgePosition.hxx"
93 #include "SMDS_FacePosition.hxx"
94 #include "SMDS_VertexPosition.hxx"
95 #include "SMDS_SpacePosition.hxx"
96 #include "SMDS_PolyhedralVolumeOfNodes.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::Component_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('" << 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   aServant->GetGroups();
905
906   return aMesh._retn();
907 }
908
909 //=============================================================================
910 /*!
911  *  SMESH_Gen_i::CreateMeshFromMED
912  *
913  *  Create mesh and import data from MED file
914  */
915 //=============================================================================
916
917 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
918                                                      SMESH::DriverMED_ReadStatus& theStatus)
919      throw ( SALOME::SALOME_Exception )
920 {
921   Unexpect aCatch(SALOME_SalomeException);
922   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshFromMED" );
923
924   // Retrieve mesh names from the file
925   DriverMED_R_SMESHDS_Mesh myReader;
926   myReader.SetFile( theFileName );
927   myReader.SetMeshId( -1 );
928   Driver_Mesh::Status aStatus;
929   list<string> aNames = myReader.GetMeshNames(aStatus);
930   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
931   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
932
933   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
934
935   // Python Dump
936   TPythonDump aPythonDump;
937   aPythonDump << "([";
938   //TCollection_AsciiString aStr ("([");
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) aStr += ", ";
950       if (i > 0) aPythonDump << ", ";
951
952       // create mesh
953       SMESH::SMESH_Mesh_var mesh = createMesh();
954       
955       // publish mesh in the study
956       SALOMEDS::SObject_var aSO;
957       if ( CanPublishInStudy( mesh ) )
958         aSO = PublishMesh( myCurrentStudy, mesh.in(), (*it).c_str() );
959       if ( !aSO->_is_nil() ) {
960         // Python Dump
961         aPythonDump << aSO;
962         //aStr += aSO->GetID();
963       } else {
964         // Python Dump
965         aPythonDump << "mesh_" << i;
966 //         aStr += "mesh_";
967 //         aStr += TCollection_AsciiString(i);
968       }
969
970       // Read mesh data (groups are published automatically by ImportMEDFile())
971       SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
972       ASSERT( meshServant );
973       SMESH::DriverMED_ReadStatus status1 =
974         meshServant->ImportMEDFile( theFileName, (*it).c_str() );
975       if (status1 > theStatus)
976         theStatus = status1;
977
978       aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
979     }
980     aStudyBuilder->CommitCommand();
981   }
982
983   // Update Python script
984   aPythonDump << "], status) = " << this << ".CreateMeshesFromMED('" << theFileName << "')";
985   }
986   // Dump creation of groups
987   for ( int i = 0; i < aResult->length(); ++i )
988     aResult[ i ]->GetGroups();
989
990   return aResult._retn();
991 }
992
993 //=============================================================================
994 /*!
995  *  SMESH_Gen_i::CreateMeshFromSTL
996  *
997  *  Create mesh and import data from STL file
998  */
999 //=============================================================================
1000
1001 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1002   throw ( SALOME::SALOME_Exception )
1003 {
1004   Unexpect aCatch(SALOME_SalomeException);
1005   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromSTL" );
1006
1007   SMESH::SMESH_Mesh_var aMesh = createMesh();
1008   string aFileName;
1009   // publish mesh in the study
1010   if ( CanPublishInStudy( aMesh ) ) {
1011     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1012     aStudyBuilder->NewCommand();  // There is a transaction
1013     SALOMEDS::SObject_var aSO = PublishInStudy
1014       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1015     aStudyBuilder->CommitCommand();
1016     if ( !aSO->_is_nil() ) {
1017       // Update Python script
1018       TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL('" << theFileName << "')";
1019     }
1020   }
1021
1022   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1023   ASSERT( aServant );
1024   aServant->ImportSTLFile( theFileName );
1025   return aMesh._retn();
1026 }
1027
1028 //=============================================================================
1029 /*!
1030  *  SMESH_Gen_i::IsReadyToCompute
1031  *
1032  *  Returns true if mesh contains enough data to be computed
1033  */
1034 //=============================================================================
1035
1036 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1037                                               GEOM::GEOM_Object_ptr theShapeObject )
1038   throw ( SALOME::SALOME_Exception )
1039 {
1040   Unexpect aCatch(SALOME_SalomeException);
1041   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1042
1043   if ( CORBA::is_nil( theShapeObject ) )
1044     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
1045                                   SALOME::BAD_PARAM );
1046
1047   if ( CORBA::is_nil( theMesh ) )
1048     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1049                                   SALOME::BAD_PARAM );
1050
1051   try {
1052     // get mesh servant
1053     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1054     ASSERT( meshServant );
1055     if ( meshServant ) {
1056       // get local TopoDS_Shape
1057       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1058       // call implementation
1059       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1060       return myGen.CheckAlgoState( myLocMesh, myLocShape );
1061     }
1062   }
1063   catch ( SALOME_Exception& S_ex ) {
1064     INFOS( "catch exception "<< S_ex.what() );
1065   }
1066   return false;
1067 }
1068
1069 //================================================================================
1070 /*!
1071  * \brief  Find SObject for an algo
1072  */
1073 //================================================================================
1074
1075 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1076 {
1077   if ( algo ) {
1078     if ( !myCurrentStudy->_is_nil() ) {
1079       // find algo in the study
1080       SALOMEDS::SComponent_var father = SALOMEDS::SComponent::_narrow
1081         ( myCurrentStudy->FindComponent( ComponentDataType() ) );
1082       if ( !father->_is_nil() ) {
1083         SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( father );
1084         for ( ; itBig->More(); itBig->Next() ) {
1085           SALOMEDS::SObject_var gotBranch = itBig->Value();
1086           if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1087             SALOMEDS::ChildIterator_var algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1088             for ( ; algoIt->More(); algoIt->Next() ) {
1089               SALOMEDS::SObject_var algoSO = algoIt->Value();
1090               CORBA::Object_var     algoIOR = SObjectToObject( algoSO );
1091               if ( !CORBA::is_nil( algoIOR )) {
1092                 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1093                 if ( impl && impl->GetImpl() == algo )
1094                   return algoSO._retn();
1095               }
1096             } // loop on algo SO's
1097             break;
1098           } // if algo tag
1099         } // SMESH component iterator
1100       }
1101     }
1102   }
1103   return SALOMEDS::SObject::_nil();
1104 }
1105
1106 //================================================================================
1107 /*!
1108  * \brief Return errors of mesh computation
1109  */
1110 //================================================================================
1111
1112 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh, 
1113                                                            GEOM::GEOM_Object_ptr theSubObject )
1114   throw ( SALOME::SALOME_Exception )
1115 {
1116   Unexpect aCatch(SALOME_SalomeException);
1117   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1118
1119   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1120     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1121
1122   if ( CORBA::is_nil( theMesh ) )
1123     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1124
1125   SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1126   try {
1127     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1128     {
1129       TopoDS_Shape shape;
1130       if(theMesh->HasShapeToMesh())
1131         shape = GeomObjectToShape( theSubObject );
1132       else
1133         shape = SMESH_Mesh::PseudoShape();
1134       
1135       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1136
1137       error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1138       int nbErr = 0;
1139
1140       SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1141       const bool includeSelf = true, complexShapeFirst = true;
1142       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1143                                                                complexShapeFirst);
1144       while ( smIt->more() )
1145       {
1146         sm = smIt->next();
1147         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1148           break;
1149         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1150         if ( error && !error->IsOK() && error->myAlgo )
1151         {
1152           SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1153           errStruct.code       = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1154           errStruct.comment    = error->myComment.c_str();
1155           errStruct.subShapeID = sm->GetId();
1156           SALOMEDS::SObject_var algoSO = GetAlgoSO( error->myAlgo );
1157           if ( !algoSO->_is_nil() )
1158             errStruct.algoName = algoSO->GetName();
1159           else
1160             errStruct.algoName = error->myAlgo->GetName();
1161           errStruct.hasBadMesh = !error->myBadElements.empty();
1162         }
1163       }
1164       error_array->length( nbErr );
1165     }
1166   }
1167   catch ( SALOME_Exception& S_ex ) {
1168     INFOS( "catch exception "<< S_ex.what() );
1169   }
1170
1171   return error_array._retn();
1172 }
1173
1174 // 
1175 //================================================================================
1176 /*!
1177  * \brief Return mesh elements preventing computation of a subshape
1178  */
1179 //================================================================================
1180
1181 SMESH::MeshPreviewStruct*
1182 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1183                                   CORBA::Short          theSubShapeID )
1184   throw ( SALOME::SALOME_Exception )
1185 {
1186   Unexpect aCatch(SALOME_SalomeException);
1187   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1188
1189   if ( CORBA::is_nil( theMesh ) )
1190     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1191
1192   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1193   try {
1194     // mesh servant
1195     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1196     {
1197       // mesh implementation
1198       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1199       // submesh by subshape id
1200       if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1201       {
1202         // compute error
1203         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1204         if ( error && !error->myBadElements.empty())
1205         {
1206           typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1207           typedef TNode2LocalIDMap::iterator         TNodeLocalID;
1208
1209           // get nodes of elements and count elements
1210           TNode2LocalIDMap mapNode2LocalID;
1211           list< TNodeLocalID > connectivity;
1212           int i, nbElements = 0, nbConnNodes = 0;
1213
1214           list<const SMDS_MeshElement*>::iterator elemIt  = error->myBadElements.begin();
1215           list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1216           for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1217           {
1218             SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1219             while ( nIt->more() )
1220               connectivity.push_back
1221                 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1222           }
1223           // fill node coords and assign local ids to the nodes
1224           int nbNodes = mapNode2LocalID.size();
1225           result->nodesXYZ.length( nbNodes );
1226           TNodeLocalID node2ID = mapNode2LocalID.begin();
1227           for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1228             node2ID->second = i;
1229             const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1230             result->nodesXYZ[i].x = node->X();
1231             result->nodesXYZ[i].y = node->Y();
1232             result->nodesXYZ[i].z = node->Z();
1233           }
1234           // fill connectivity
1235           result->elementConnectivities.length( nbConnNodes );
1236           list< TNodeLocalID >::iterator connIt = connectivity.begin();
1237           for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1238             result->elementConnectivities[i] = (*connIt)->second;
1239           }
1240           // fill element types
1241           result->elementTypes.length( nbElements );
1242           for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1243           {
1244             const SMDS_MeshElement* elem = *elemIt;
1245             result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1246             result->elementTypes[i].isPoly           = elem->IsPoly();
1247             result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1248           }
1249         }
1250       }
1251     }
1252   }
1253   catch ( SALOME_Exception& S_ex ) {
1254     INFOS( "catch exception "<< S_ex.what() );
1255   }
1256
1257   return result._retn();
1258 }
1259
1260 //================================================================================
1261 /*!
1262  * \brief Returns errors of hypotheses definintion
1263  * \param theMesh - the mesh
1264  * \param theSubObject - the main or sub- shape
1265  * \retval SMESH::algo_error_array* - sequence of errors
1266  */
1267 //================================================================================
1268
1269 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh, 
1270                                                     GEOM::GEOM_Object_ptr theSubObject )
1271       throw ( SALOME::SALOME_Exception )
1272 {
1273   Unexpect aCatch(SALOME_SalomeException);
1274   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1275
1276   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1277     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1278
1279   if ( CORBA::is_nil( theMesh ) )
1280     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1281
1282   SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1283   try {
1284     SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1285     ASSERT( meshServant );
1286     if ( meshServant ) {
1287       TopoDS_Shape myLocShape;
1288       if(theMesh->HasShapeToMesh())
1289         myLocShape = GeomObjectToShape( theSubObject );
1290       else
1291         myLocShape = SMESH_Mesh::PseudoShape();
1292       
1293       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1294       list< ::SMESH_Gen::TAlgoStateError > error_list;
1295       list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1296       // call ::SMESH_Gen::GetAlgoState()
1297       myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1298       error_array->length( error_list.size() );
1299       int i = 0;
1300       for ( error = error_list.begin(); error != error_list.end(); ++error )
1301       {
1302         // fill AlgoStateError structure
1303         SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1304         errStruct.state        = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1305         errStruct.algoDim      = error->_algoDim;
1306         errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1307         errStruct.algoName     = "";
1308         SALOMEDS::SObject_var algoSO = GetAlgoSO( error->_algo );
1309         if ( !algoSO->_is_nil() )
1310           errStruct.algoName   = algoSO->GetName();
1311       }
1312     }
1313   }
1314   catch ( SALOME_Exception& S_ex ) {
1315     INFOS( "catch exception "<< S_ex.what() );
1316   }
1317   return error_array._retn();
1318 }
1319
1320 //=============================================================================
1321 /*!
1322  *  SMESH_Gen_i::GetSubShapesId
1323  *
1324  *  Get sub-shapes unique ID's list
1325  */
1326 //=============================================================================
1327
1328 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1329                                             const SMESH::object_array& theListOfSubShapeObject )
1330      throw ( SALOME::SALOME_Exception )
1331 {
1332   Unexpect aCatch(SALOME_SalomeException);
1333   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1334
1335   SMESH::long_array_var shapesId = new SMESH::long_array;
1336   set<int> setId;
1337
1338   if ( CORBA::is_nil( theMainShapeObject ) )
1339     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1340                                   SALOME::BAD_PARAM );
1341
1342   try
1343     {
1344       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1345       TopTools_IndexedMapOfShape myIndexToShape;      
1346       TopExp::MapShapes(myMainShape,myIndexToShape);
1347
1348       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1349         {
1350           GEOM::GEOM_Object_var aShapeObject
1351             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1352           if ( CORBA::is_nil( aShapeObject ) )
1353             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1354                                         SALOME::BAD_PARAM );
1355
1356           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
1357           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1358             {
1359               const TopoDS_Face& F = TopoDS::Face(exp.Current());
1360               setId.insert(myIndexToShape.FindIndex(F));
1361               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1362             }
1363           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1364             {
1365               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1366               setId.insert(myIndexToShape.FindIndex(E));
1367               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1368             }
1369           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1370             {
1371               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1372               setId.insert(myIndexToShape.FindIndex(V));
1373               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1374             }
1375         }
1376       shapesId->length(setId.size());
1377       set<int>::iterator iind;
1378       int i=0;
1379       for (iind = setId.begin(); iind != setId.end(); iind++)
1380         {
1381           if(MYDEBUG) SCRUTE((*iind));
1382           shapesId[i] = (*iind);
1383           if(MYDEBUG) SCRUTE(shapesId[i]);
1384           i++;
1385         }
1386     }
1387   catch (SALOME_Exception& S_ex)
1388     {
1389       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1390     }
1391
1392   return shapesId._retn();
1393 }
1394
1395 //=============================================================================
1396 /*!
1397  *  SMESH_Gen_i::Compute
1398  *
1399  *  Compute mesh on a shape
1400  */
1401 //=============================================================================
1402
1403 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1404                                      GEOM::GEOM_Object_ptr theShapeObject )
1405      throw ( SALOME::SALOME_Exception )
1406 {
1407   MEMOSTAT;
1408   Unexpect aCatch(SALOME_SalomeException);
1409   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1410
1411   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1412     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
1413                                   SALOME::BAD_PARAM );
1414
1415   if ( CORBA::is_nil( theMesh ) )
1416     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1417                                   SALOME::BAD_PARAM );
1418
1419   // Update Python script
1420   TPythonDump() << "isDone = " << this << ".Compute( "
1421                 << theMesh << ", " << theShapeObject << ")";
1422
1423   try {
1424     // get mesh servant
1425     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1426     ASSERT( meshServant );
1427     if ( meshServant ) {
1428       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1429       meshServant->CheckGeomGroupModif();
1430       // get local TopoDS_Shape
1431       TopoDS_Shape myLocShape;
1432       if(theMesh->HasShapeToMesh())
1433         myLocShape = GeomObjectToShape( theShapeObject );
1434       else
1435         myLocShape = SMESH_Mesh::PseudoShape();
1436       // call implementation compute
1437       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1438       return myGen.Compute( myLocMesh, myLocShape);
1439     }
1440   }
1441   catch ( std::bad_alloc ) {
1442     INFOS( "Compute(): lack of memory" );
1443   }
1444   catch ( SALOME_Exception& S_ex ) {
1445     INFOS( "Compute(): catch exception "<< S_ex.what() );
1446   }
1447   catch ( ... ) {
1448     INFOS( "Compute(): unknown exception " );
1449   }
1450   return false;
1451 }
1452
1453 //=============================================================================
1454 /*!
1455  *  SMESH_Gen_i::Precompute
1456  *
1457  *  Compute mesh as preview till indicated dimension on shape
1458  */
1459 //=============================================================================
1460
1461 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1462                                                    GEOM::GEOM_Object_ptr theShapeObject,
1463                                                    SMESH::Dimension      theDimension,
1464                                                    SMESH::long_array&    theShapesId)
1465      throw ( SALOME::SALOME_Exception )
1466 {
1467   Unexpect aCatch(SALOME_SalomeException);
1468   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1469
1470   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1471     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
1472                                   SALOME::BAD_PARAM );
1473
1474   if ( CORBA::is_nil( theMesh ) )
1475     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1476                                   SALOME::BAD_PARAM );
1477
1478   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1479   try {
1480     // get mesh servant
1481     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1482     ASSERT( meshServant );
1483     if ( meshServant ) {
1484       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1485       meshServant->CheckGeomGroupModif();
1486       // get local TopoDS_Shape
1487       TopoDS_Shape myLocShape;
1488       if(theMesh->HasShapeToMesh())
1489         myLocShape = GeomObjectToShape( theShapeObject );
1490       else
1491         return result._retn();;
1492
1493       // call implementation compute
1494       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1495       TSetOfInt shapeIds;
1496       ::MeshDimension aDim = (MeshDimension)theDimension;
1497       if ( myGen.Compute( myLocMesh, myLocShape, false, aDim, &shapeIds ) )
1498       {
1499         int nbShapeId = shapeIds.size();
1500         theShapesId.length( nbShapeId );
1501         // iterates on shapes and collect mesh entities into mesh preview
1502         TSetOfInt::const_iterator idIt = shapeIds.begin();
1503         TSetOfInt::const_iterator idEnd = shapeIds.end();
1504         std::map< int, int > mapOfShIdNb;
1505         std::set< SMESH_TLink > setOfEdge;
1506         std::list< SMDSAbs_ElementType > listOfElemType;
1507         typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1508         typedef TNode2LocalIDMap::iterator         TNodeLocalID;
1509         TNode2LocalIDMap mapNode2LocalID;
1510         list< TNodeLocalID > connectivity;
1511         int i, nbConnNodes = 0;
1512         std::set< const SMESH_subMesh* > setOfVSubMesh;
1513         // iterates on shapes
1514         for ( ; idIt != idEnd; idIt++ )
1515         {
1516           if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
1517             continue;
1518           SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
1519           if ( !sm || !sm->IsMeshComputed() )
1520             continue;
1521           
1522           const TopoDS_Shape& aSh = sm->GetSubShape();
1523           const int shDim = myGen.GetShapeDim( aSh );
1524           if ( shDim < 1 || shDim > theDimension )
1525             continue;
1526
1527           mapOfShIdNb[ *idIt ] = 0;
1528           theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
1529
1530           SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1531           if ( !smDS ) continue;
1532
1533           if ( theDimension == SMESH::DIM_2D )
1534           {
1535             SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1536             while ( faceIt->more() )
1537             {
1538               const SMDS_MeshElement* face = faceIt->next();
1539               int aNbNode = face->NbNodes();
1540               if ( aNbNode > 4 )
1541                 aNbNode /= 2; // do not take into account additional middle nodes
1542
1543               SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
1544               for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
1545               {
1546                 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
1547                 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
1548                 {
1549                   listOfElemType.push_back( SMDSAbs_Edge );
1550                   connectivity.push_back
1551                     ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
1552                   connectivity.push_back
1553                     ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
1554                 }
1555                 node1 = node2;
1556               }
1557             }
1558           }
1559           else if ( theDimension == SMESH::DIM_1D )
1560           {
1561             SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1562             while ( nodeIt->more() )
1563             {
1564               listOfElemType.push_back( SMDSAbs_Node );
1565               connectivity.push_back
1566                 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
1567             }
1568             // add corner nodes by first vertex from edge
1569             SMESH_subMeshIteratorPtr edgeSmIt =
1570               sm->getDependsOnIterator(/*includeSelf*/false,
1571                                        /*complexShapeFirst*/false);
1572             while ( edgeSmIt->more() )
1573             {
1574               SMESH_subMesh* vertexSM = edgeSmIt->next();
1575               // check that vertex is not already treated
1576               if ( !setOfVSubMesh.insert( vertexSM ).second )
1577                 continue;
1578               if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
1579                 continue;
1580
1581               const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
1582               SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
1583               while ( nodeIt->more() )
1584               {
1585                 listOfElemType.push_back( SMDSAbs_Node );
1586                 connectivity.push_back
1587                   ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
1588               }
1589             }
1590           }
1591         }
1592
1593         // fill node coords and assign local ids to the nodes
1594         int nbNodes = mapNode2LocalID.size();
1595         result->nodesXYZ.length( nbNodes );
1596         TNodeLocalID node2ID = mapNode2LocalID.begin();
1597         for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1598           node2ID->second = i;
1599           const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1600           result->nodesXYZ[i].x = node->X();
1601           result->nodesXYZ[i].y = node->Y();
1602           result->nodesXYZ[i].z = node->Z();
1603         }
1604         // fill connectivity
1605         result->elementConnectivities.length( nbConnNodes );
1606         list< TNodeLocalID >::iterator connIt = connectivity.begin();
1607         for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1608           result->elementConnectivities[i] = (*connIt)->second;
1609         }
1610
1611         // fill element types
1612         result->elementTypes.length( listOfElemType.size() );
1613         std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
1614         std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
1615         for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
1616         {
1617           SMDSAbs_ElementType elemType = *typeIt;
1618           result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
1619           result->elementTypes[i].isPoly           = false;
1620           result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
1621         }
1622
1623         // correct number of shapes
1624         theShapesId.length( mapOfShIdNb.size() );
1625       }
1626     }
1627   }
1628   catch ( std::bad_alloc ) {
1629     INFOS( "Precompute(): lack of memory" );
1630   }
1631   catch ( SALOME_Exception& S_ex ) {
1632     INFOS( "Precompute(): catch exception "<< S_ex.what() );
1633   }
1634   catch ( ... ) {
1635     INFOS( "Precompute(): unknown exception " );
1636   }
1637   return result._retn();
1638 }
1639
1640
1641 //=============================================================================
1642 /*!
1643  *  SMESH_Gen_i::Evaluate
1644  *
1645  *  Evaluate mesh on a shape
1646  */
1647 //=============================================================================
1648
1649 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
1650                                          GEOM::GEOM_Object_ptr theShapeObject)
1651 //                                     SMESH::long_array& theNbElems)
1652      throw ( SALOME::SALOME_Exception )
1653 {
1654   Unexpect aCatch(SALOME_SalomeException);
1655   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
1656
1657   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1658     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
1659                                   SALOME::BAD_PARAM );
1660
1661   if ( CORBA::is_nil( theMesh ) )
1662     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1663                                   SALOME::BAD_PARAM );
1664
1665   SMESH::long_array_var nbels = new SMESH::long_array;
1666   nbels->length(SMESH::Entity_Last);
1667   int i = SMESH::Entity_Node;
1668   for (; i < SMESH::Entity_Last; i++)
1669     nbels[i] = 0;
1670
1671   // Update Python script
1672   TPythonDump() << "theNbElems = " << this << ".Evaluate( "
1673                 << theMesh << ", " << theShapeObject << ")";
1674
1675   try {
1676     // get mesh servant
1677     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1678     ASSERT( meshServant );
1679     if ( meshServant ) {
1680       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1681       meshServant->CheckGeomGroupModif();
1682       // get local TopoDS_Shape
1683       TopoDS_Shape myLocShape;
1684       if(theMesh->HasShapeToMesh())
1685         myLocShape = GeomObjectToShape( theShapeObject );
1686       else
1687         myLocShape = SMESH_Mesh::PseudoShape();
1688       // call implementation compute
1689       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1690       MapShapeNbElems aResMap;
1691       /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
1692       MapShapeNbElemsItr anIt = aResMap.begin();
1693       for(; anIt!=aResMap.end(); anIt++) {
1694         const vector<int>& aVec = (*anIt).second;
1695         for(i = SMESH::Entity_Node; i < aVec.size(); i++) {
1696           int nbElem = aVec[i];
1697           if ( nbElem < 0 ) // algo failed, check that it has reported a message
1698           {
1699             SMESH_subMesh* sm = anIt->first;
1700             SMESH_ComputeErrorPtr& error = sm->GetComputeError();
1701             const SMESH_Algo* algo = myGen.GetAlgo( myLocMesh, sm->GetSubShape());
1702             if ( algo && !error.get() || error->IsOK() )
1703               error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
1704           }
1705           else
1706           {
1707             nbels[i] += aVec[i];
1708           }
1709         }
1710       }
1711       return nbels._retn();
1712     }
1713   }
1714   catch ( std::bad_alloc ) {
1715     INFOS( "Evaluate(): lack of memory" );
1716   }
1717   catch ( SALOME_Exception& S_ex ) {
1718     INFOS( "Evaluate(): catch exception "<< S_ex.what() );
1719   }
1720   catch ( ... ) {
1721     INFOS( "Evaluate(): unknown exception " );
1722   }
1723
1724   return nbels._retn();
1725 }
1726
1727 //================================================================================
1728 /*!
1729  * \brief Return geometrical object the given element is built on
1730  *  \param theMesh - the mesh the element is in
1731  *  \param theElementID - the element ID
1732  *  \param theGeomName - the name of the result geom object if it is not yet published
1733  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object
1734  */
1735 //================================================================================
1736
1737 GEOM::GEOM_Object_ptr
1738 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
1739                                        CORBA::Long            theElementID,
1740                                        const char*            theGeomName)
1741   throw ( SALOME::SALOME_Exception )
1742 {
1743   Unexpect aCatch(SALOME_SalomeException);
1744  
1745   GEOM::GEOM_Object_var geom = FindGeometryByMeshElement(theMesh, theElementID);
1746   if ( !geom->_is_nil() ) {
1747     GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1748     GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
1749
1750     // try to find the corresponding SObject
1751     SALOMEDS::SObject_var SObj = ObjectToSObject( myCurrentStudy, geom.in() );
1752     if ( SObj->_is_nil() ) // submesh can be not found even if published
1753     {
1754       // try to find published submesh
1755       GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
1756       if ( !geom->IsMainShape() && list->length() == 1 ) {
1757         SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
1758         SALOMEDS::ChildIterator_var it;
1759         if ( !mainSO->_is_nil() )
1760           it = myCurrentStudy->NewChildIterator( mainSO );
1761         if ( !it->_is_nil() ) {
1762           for ( it->InitEx(true); SObj->_is_nil() && it->More(); it->Next() ) {
1763             GEOM::GEOM_Object_var subGeom =
1764               GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
1765             if ( !subGeom->_is_nil() ) {
1766               GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
1767               if ( subList->length() == 1 && list[0] == subList[0] ) {
1768                 SObj = it->Value();
1769                 geom = subGeom;
1770               }
1771             }
1772           }
1773         }
1774       }
1775     }
1776     if ( SObj->_is_nil() ) // publish a new subshape
1777       SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
1778
1779     // return only published geometry
1780     if ( !SObj->_is_nil() )
1781       return geom._retn();
1782   }
1783   return GEOM::GEOM_Object::_nil();
1784 }
1785
1786 //================================================================================
1787 /*!
1788  * \brief Return geometrical object the given element is built on.
1789  *  \param theMesh - the mesh the element is in
1790  *  \param theElementID - the element ID
1791  *  \retval GEOM::GEOM_Object_ptr - the found geom object
1792  */
1793 //================================================================================
1794
1795 GEOM::GEOM_Object_ptr
1796 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
1797                                         CORBA::Long            theElementID)
1798   throw ( SALOME::SALOME_Exception )
1799 {
1800   Unexpect aCatch(SALOME_SalomeException);
1801   if ( CORBA::is_nil( theMesh ) )
1802     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
1803
1804   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1805   GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
1806
1807   // get a core mesh DS
1808   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1809   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
1810   {
1811     ::SMESH_Mesh & mesh = meshServant->GetImpl();
1812     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
1813     // find the element in mesh
1814     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
1815       // find a shape id by the element
1816       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
1817         // get a geom object by the shape id
1818         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
1819         if ( geom->_is_nil() ) {
1820           // try to find a published sub-shape
1821           SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
1822           SALOMEDS::ChildIterator_var it;
1823           if ( !mainSO->_is_nil() )
1824             it = myCurrentStudy->NewChildIterator( mainSO );
1825           if ( !it->_is_nil() ) {
1826             for ( it->InitEx(true); it->More(); it->Next() ) {
1827               GEOM::GEOM_Object_var subGeom =
1828                 GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
1829               if ( !subGeom->_is_nil() ) {
1830                 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
1831                 if ( subList->length() == 1 && shapeID == subList[0] ) {
1832                   geom = subGeom;
1833                   break;
1834                 }
1835               }
1836             }
1837           }
1838         }
1839         if ( geom->_is_nil() ) {
1840           // explode
1841           GEOM::GEOM_IShapesOperations_var op =
1842             geomGen->GetIShapesOperations( GetCurrentStudyID() );
1843           if ( !op->_is_nil() )
1844             geom = op->GetSubShape( mainShape, shapeID );
1845         }
1846         if ( !geom->_is_nil() ) {
1847           GeomObjectToShape( geom ); // let geom client remember the found shape
1848           return geom._retn();
1849         }
1850       }
1851     }
1852   }
1853   return GEOM::GEOM_Object::_nil();
1854 }
1855
1856 //================================================================================
1857 /*!
1858  *  SMESH_Gen_i::Concatenate
1859  *
1860  *  Concatenate the given meshes into one mesh
1861  */
1862 //================================================================================
1863
1864 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::Concatenate(const SMESH::mesh_array& theMeshesArray,
1865                                                CORBA::Boolean           theUniteIdenticalGroups, 
1866                                                CORBA::Boolean           theMergeNodesAndElements, 
1867                                                CORBA::Double            theMergeTolerance)
1868   throw ( SALOME::SALOME_Exception )
1869 {
1870   return ConcatenateCommon(theMeshesArray,
1871                            theUniteIdenticalGroups,
1872                            theMergeNodesAndElements,
1873                            theMergeTolerance,
1874                            false);
1875 }
1876
1877 //================================================================================
1878 /*!
1879  *  SMESH_Gen_i::ConcatenateWithGroups
1880  *
1881  *  Concatenate the given meshes into one mesh
1882  *  Create the groups of all elements from initial meshes
1883  */
1884 //================================================================================
1885
1886 SMESH::SMESH_Mesh_ptr
1887 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::mesh_array& theMeshesArray,
1888                                    CORBA::Boolean           theUniteIdenticalGroups, 
1889                                    CORBA::Boolean           theMergeNodesAndElements, 
1890                                    CORBA::Double            theMergeTolerance)
1891   throw ( SALOME::SALOME_Exception )
1892 {
1893   return ConcatenateCommon(theMeshesArray,
1894                            theUniteIdenticalGroups,
1895                            theMergeNodesAndElements,
1896                            theMergeTolerance,
1897                            true);
1898 }
1899
1900 //================================================================================
1901 /*!
1902  *  SMESH_Gen_i::ConcatenateCommon
1903  *
1904  *  Concatenate the given meshes into one mesh
1905  */
1906 //================================================================================
1907
1908 SMESH::SMESH_Mesh_ptr
1909 SMESH_Gen_i::ConcatenateCommon(const SMESH::mesh_array& theMeshesArray,
1910                                CORBA::Boolean           theUniteIdenticalGroups, 
1911                                CORBA::Boolean           theMergeNodesAndElements, 
1912                                CORBA::Double            theMergeTolerance,
1913                                CORBA::Boolean           theCommonGroups)
1914   throw ( SALOME::SALOME_Exception )
1915 {
1916   typedef map<int, int> TIDsMap;
1917   typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
1918   typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
1919   typedef std::set<SMESHDS_GroupBase*> TGroups;
1920
1921   TPythonDump* pPythonDump = new TPythonDump;
1922   TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
1923
1924   // create mesh
1925   SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
1926   
1927   if ( !aNewMesh->_is_nil() ) {
1928     SMESH_Mesh_i* aNewImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( aNewMesh ).in() );
1929     if ( aNewImpl ) {
1930       ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
1931       SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
1932
1933       TGroupsMap aGroupsMap;
1934       TListOfNewGroups aListOfNewGroups;
1935       SMESH_MeshEditor aNewEditor = ::SMESH_MeshEditor(&aLocMesh);
1936       SMESH::ListOfGroups_var aListOfGroups = new SMESH::ListOfGroups();
1937
1938       // loop on meshes
1939       for ( int i = 0; i < theMeshesArray.length(); i++) {
1940         SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i];
1941         if ( !anInitMesh->_is_nil() ) {
1942           SMESH_Mesh_i* anInitImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( anInitMesh ).in() );
1943           if ( anInitImpl ) {
1944             ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
1945             SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
1946
1947             TIDsMap nodesMap;
1948             TIDsMap elemsMap;
1949
1950             // loop on elements of mesh
1951             SMDS_ElemIteratorPtr itElems = anInitMeshDS->elementsIterator();
1952             const SMDS_MeshElement* anElem = 0;
1953             const SMDS_MeshElement* aNewElem = 0;
1954             int anElemNbNodes = 0;
1955
1956             int anNbNodes   = 0;
1957             int anNbEdges   = 0;
1958             int anNbFaces   = 0;
1959             int anNbVolumes = 0;
1960
1961             SMESH::long_array_var anIDsNodes   = new SMESH::long_array();
1962             SMESH::long_array_var anIDsEdges   = new SMESH::long_array();
1963             SMESH::long_array_var anIDsFaces   = new SMESH::long_array();
1964             SMESH::long_array_var anIDsVolumes = new SMESH::long_array();
1965
1966             if( theCommonGroups ) {
1967               anIDsNodes->length(   anInitMeshDS->NbNodes()   );
1968               anIDsEdges->length(   anInitMeshDS->NbEdges()   );
1969               anIDsFaces->length(   anInitMeshDS->NbFaces()   );
1970               anIDsVolumes->length( anInitMeshDS->NbVolumes() );
1971             }
1972
1973             for ( int j = 0; itElems->more(); j++) {
1974               anElem = itElems->next();
1975               SMDSAbs_ElementType anElemType = anElem->GetType();
1976               anElemNbNodes = anElem->NbNodes();
1977               std::vector<const SMDS_MeshNode*> aNodesArray (anElemNbNodes);
1978
1979               // loop on nodes of element
1980               const SMDS_MeshNode* aNode = 0;
1981               const SMDS_MeshNode* aNewNode = 0;
1982               SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
1983
1984               for ( int k = 0; itNodes->more(); k++) {
1985                 aNode = static_cast<const SMDS_MeshNode*>(itNodes->next());
1986                 if ( nodesMap.find(aNode->GetID()) == nodesMap.end() ) {
1987                   aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
1988                   nodesMap.insert( make_pair(aNode->GetID(), aNewNode->GetID()) );
1989                   if( theCommonGroups )
1990                     anIDsNodes[anNbNodes++] = aNewNode->GetID();
1991                 }
1992                 else
1993                   aNewNode = aNewMeshDS->FindNode( nodesMap.find(aNode->GetID())->second );
1994                 aNodesArray[k] = aNewNode;
1995               }//nodes loop
1996
1997               // creates a corresponding element on existent nodes in new mesh
1998               if ( anElem->IsPoly() && anElemType == SMDSAbs_Volume )
1999                 {
2000                   const SMDS_PolyhedralVolumeOfNodes* aVolume =
2001                     dynamic_cast<const SMDS_PolyhedralVolumeOfNodes*> (anElem);
2002                   if ( aVolume ) {
2003                     aNewElem = aNewMeshDS->AddPolyhedralVolume(aNodesArray, 
2004                                                                aVolume->GetQuanities());
2005                     elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
2006                     if( theCommonGroups )
2007                       anIDsVolumes[anNbVolumes++] = aNewElem->GetID();
2008                   }
2009                 }
2010               else {
2011                 
2012                 aNewElem = aNewEditor.AddElement(aNodesArray,
2013                                                  anElemType,
2014                                                  anElem->IsPoly());
2015                 elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
2016                 if( theCommonGroups ) {
2017                   if( anElemType == SMDSAbs_Edge )
2018                     anIDsEdges[anNbEdges++] = aNewElem->GetID();
2019                   else if( anElemType == SMDSAbs_Face )
2020                     anIDsFaces[anNbFaces++] = aNewElem->GetID();
2021                   else if( anElemType == SMDSAbs_Volume )
2022                     anIDsVolumes[anNbVolumes++] = aNewElem->GetID();
2023                 }
2024               } 
2025             }//elems loop
2026             
2027             aListOfGroups = anInitImpl->GetGroups();
2028             SMESH::SMESH_GroupBase_ptr aGroup;
2029
2030             // loop on groups of mesh
2031             SMESH::long_array_var anInitIDs = new SMESH::long_array();
2032             SMESH::long_array_var anNewIDs = new SMESH::long_array();
2033             SMESH::SMESH_Group_var aNewGroup;
2034
2035             SMESH::ElementType aGroupType;
2036             CORBA::String_var aGroupName;
2037             if ( theCommonGroups ) {
2038               for(aGroupType=SMESH::NODE;aGroupType<=SMESH::VOLUME;aGroupType=(SMESH::ElementType)(aGroupType+1)) {
2039                 string str = "Gr";
2040                 SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, anInitMesh );
2041                 if(aMeshSObj)
2042                   str += aMeshSObj->GetName();
2043                 str += "_";
2044
2045                 int anLen = 0;
2046
2047                 switch(aGroupType) {
2048                 case SMESH::NODE:
2049                   str += "Nodes";
2050                   anIDsNodes->length(anNbNodes);
2051                   anLen = anNbNodes;
2052                   break;
2053                 case SMESH::EDGE:
2054                   str += "Edges";
2055                   anIDsEdges->length(anNbEdges);
2056                   anLen = anNbEdges;
2057                   break;
2058                 case SMESH::FACE:
2059                   str += "Faces";
2060                   anIDsFaces->length(anNbFaces);
2061                   anLen = anNbFaces;
2062                   break;
2063                 case SMESH::VOLUME:
2064                   str += "Volumes";
2065                   anIDsVolumes->length(anNbVolumes);
2066                   anLen = anNbVolumes;
2067                   break;
2068                 default:
2069                   break;
2070                 }
2071
2072                 if(anLen) {
2073                   aGroupName = str.c_str();
2074
2075                   // add a new group in the mesh
2076                   aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2077
2078                   switch(aGroupType) {
2079                   case SMESH::NODE:
2080                     aNewGroup->Add( anIDsNodes );
2081                     break;
2082                   case SMESH::EDGE:
2083                     aNewGroup->Add( anIDsEdges );
2084                     break;
2085                   case SMESH::FACE:
2086                     aNewGroup->Add( anIDsFaces );
2087                     break;
2088                   case SMESH::VOLUME:
2089                     aNewGroup->Add( anIDsVolumes );
2090                     break;
2091                   default:
2092                     break;
2093                   }
2094                 
2095                   aListOfNewGroups.clear();
2096                   aListOfNewGroups.push_back(aNewGroup);
2097                   aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2098                 }
2099               }
2100             }
2101
2102             // check that current group name and type don't have identical ones in union mesh
2103             for (int i = 0; i < aListOfGroups->length(); i++) {
2104               aGroup = aListOfGroups[i];
2105               aListOfNewGroups.clear();
2106               aGroupType = aGroup->GetType();
2107               aGroupName = aGroup->GetName();
2108
2109               TGroupsMap::iterator anIter = aGroupsMap.find(make_pair(aGroupName, aGroupType));
2110
2111               // convert a list of IDs
2112               anInitIDs = aGroup->GetListOfID();
2113               anNewIDs->length(anInitIDs->length());
2114               if ( aGroupType == SMESH::NODE )
2115                 for (int j = 0; j < anInitIDs->length(); j++) {
2116                   anNewIDs[j] = nodesMap.find(anInitIDs[j])->second;
2117                 }
2118               else
2119                 for (int j = 0; j < anInitIDs->length(); j++) {
2120                   anNewIDs[j] = elemsMap.find(anInitIDs[j])->second;
2121                 }
2122               
2123               // check that current group name and type don't have identical ones in union mesh
2124               if ( anIter == aGroupsMap.end() ) {
2125                 // add a new group in the mesh
2126                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2127                 // add elements into new group
2128                 aNewGroup->Add( anNewIDs );
2129                 
2130                 aListOfNewGroups.push_back(aNewGroup);
2131                 aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2132               }
2133
2134               else if ( theUniteIdenticalGroups ) {
2135                 // unite identical groups
2136                 TListOfNewGroups& aNewGroups = anIter->second;
2137                 aNewGroups.front()->Add( anNewIDs );
2138               }
2139
2140               else {
2141                 // rename identical groups
2142                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2143                 aNewGroup->Add( anNewIDs );
2144                 
2145                 TListOfNewGroups& aNewGroups = anIter->second;
2146                 string aNewGroupName;
2147                 if (aNewGroups.size() == 1) {
2148                   aNewGroupName = string(aGroupName) + "_1";
2149                   aNewGroups.front()->SetName(aNewGroupName.c_str());
2150                 }
2151                 char aGroupNum[128];
2152                 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
2153                 aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
2154                 aNewGroup->SetName(aNewGroupName.c_str());
2155                 aNewGroups.push_back(aNewGroup);
2156               }
2157             }//groups loop
2158           }
2159         }
2160       }//meshes loop
2161
2162       if (theMergeNodesAndElements) {
2163         // merge nodes
2164         set<const SMDS_MeshNode*> aMeshNodes; // no input nodes
2165         SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2166         aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes );
2167         aNewEditor.MergeNodes( aGroupsOfNodes );
2168         // merge elements
2169         aNewEditor.MergeEqualElements();
2170       }
2171     }
2172   }
2173   
2174   // Update Python script
2175   aPythonDump << aNewMesh << " = " << this;
2176   if( !theCommonGroups )
2177     aPythonDump << ".Concatenate(";
2178   else
2179     aPythonDump << ".ConcatenateWithGroups(";
2180   aPythonDump << "[";
2181   for ( int i = 0; i < theMeshesArray.length(); i++) {
2182     if (i > 0) aPythonDump << ", ";
2183     aPythonDump << theMeshesArray[i];
2184   }
2185   aPythonDump << "], ";
2186   aPythonDump << theUniteIdenticalGroups << ", "
2187               << theMergeNodesAndElements << ", "
2188               << theMergeTolerance << ")";
2189
2190   delete pPythonDump; // enable python dump from GetGroups()
2191
2192   // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2193   if ( !aNewMesh->_is_nil() )
2194   {
2195     SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2196   }
2197
2198   // IPAL21468 Change icon of compound because it need not be computed.
2199   SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
2200   if( !aMeshSObj->_is_nil() ) {
2201     SALOMEDS::GenericAttribute_var anAttr;
2202     SALOMEDS::StudyBuilder_var aBuilder = myCurrentStudy->NewBuilder();
2203     anAttr = aBuilder->FindOrCreateAttribute( aMeshSObj,"AttributePixMap" );
2204     SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
2205     aPixmap->SetPixMap("ICON_SMESH_TREE_MESH");
2206   }
2207
2208   return aNewMesh._retn();
2209 }
2210
2211 //================================================================================
2212 /*!
2213  *  SMESH_Gen_i::GetMEDVersion
2214  *
2215  *  Get MED version of the file by its name
2216  */
2217 //================================================================================
2218 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2219                                           SMESH::MED_VERSION& theVersion)
2220 {
2221   theVersion = SMESH::MED_V2_1;
2222   MED::EVersion aVersion = MED::GetVersionId( theFileName );
2223   switch( aVersion ) {
2224     case MED::eV2_1     : theVersion = SMESH::MED_V2_1; return true;
2225     case MED::eV2_2     : theVersion = SMESH::MED_V2_2; return true;
2226     case MED::eVUnknown : return false;
2227   }
2228   return false;
2229 }
2230
2231 //================================================================================
2232 /*!
2233  *  SMESH_Gen_i::GetMeshNames
2234  *
2235  *  Get names of meshes defined in file with the specified name
2236  */
2237 //================================================================================
2238 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2239 {
2240   SMESH::string_array_var aResult = new SMESH::string_array();
2241   MED::PWrapper aMed = MED::CrWrapper( theFileName );
2242   MED::TErr anErr;
2243   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2244   if( anErr >= 0 ) {
2245     aResult->length( aNbMeshes );
2246     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2247       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2248       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2249     }
2250   }
2251   return aResult._retn();
2252 }
2253
2254 //=============================================================================
2255 /*!
2256  *  SMESH_Gen_i::Save
2257  *
2258  *  Save SMESH module's data
2259  */
2260 //=============================================================================
2261 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2262                                       const char*              theURL,
2263                                       bool                     isMultiFile )
2264 {
2265   INFOS( "SMESH_Gen_i::Save" );
2266
2267   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2268   // san -- in case <myCurrentStudy> differs from theComponent's study,
2269   // use that of the component
2270   if ( myCurrentStudy->_is_nil() || 
2271     theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2272     SetCurrentStudy( theComponent->GetStudy() );
2273
2274   // Store study contents as a set of python commands
2275   SavePython(myCurrentStudy);
2276
2277   StudyContext* myStudyContext = GetCurrentStudyContext();
2278
2279   // Declare a byte stream
2280   SALOMEDS::TMPFile_var aStreamFile;
2281
2282   // Obtain a temporary dir
2283   TCollection_AsciiString tmpDir =
2284     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2285
2286   // Create a sequence of files processed
2287   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2288   aFileSeq->length( NUM_TMP_FILES );
2289
2290   TCollection_AsciiString aStudyName( "" );
2291   if ( isMultiFile ) 
2292     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2293
2294   // Set names of temporary files
2295   TCollection_AsciiString filename =
2296     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
2297   TCollection_AsciiString meshfile =
2298     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
2299   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
2300   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
2301   filename = tmpDir + filename;
2302   meshfile = tmpDir + meshfile;
2303
2304   HDFfile*    aFile;
2305   HDFdataset* aDataset;
2306   HDFgroup*   aTopGroup;
2307   HDFgroup*   aGroup;
2308   HDFgroup*   aSubGroup;
2309   HDFgroup*   aSubSubGroup;
2310   hdf_size    aSize[ 1 ];
2311
2312
2313   //Remove the files if they exist: BugID: 11225
2314 #ifndef WNT /* unix functionality */
2315   TCollection_AsciiString cmd("rm -f \"");
2316 #else /* windows */
2317   TCollection_AsciiString cmd("del /F \"");
2318 #endif
2319
2320   cmd+=filename;
2321   cmd+="\" \"";
2322   cmd+=meshfile;
2323   cmd+="\"";
2324   system(cmd.ToCString());
2325
2326   // MED writer to be used by storage process
2327   DriverMED_W_SMESHDS_Mesh myWriter;
2328   myWriter.SetFile( meshfile.ToCString() );
2329
2330   // Write data
2331   // ---> create HDF file
2332   aFile = new HDFfile( (char*) filename.ToCString() );
2333   aFile->CreateOnDisk();
2334
2335   // --> iterator for top-level objects
2336   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2337   for ( ; itBig->More(); itBig->Next() ) {
2338     SALOMEDS::SObject_var gotBranch = itBig->Value();
2339
2340     // --> hypotheses root branch (only one for the study)
2341     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
2342       // create hypotheses root HDF group
2343       aTopGroup = new HDFgroup( "Hypotheses", aFile );
2344       aTopGroup->CreateOnDisk();
2345
2346       // iterator for all hypotheses
2347       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2348       for ( ; it->More(); it->Next() ) {
2349         SALOMEDS::SObject_var mySObject = it->Value();
2350         CORBA::Object_var anObject = SObjectToObject( mySObject );
2351         if ( !CORBA::is_nil( anObject ) ) {
2352           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2353           if ( !myHyp->_is_nil() ) {
2354             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2355             if ( myImpl ) {
2356               string hypname = string( myHyp->GetName() );
2357               string libname = string( myHyp->GetLibName() );
2358               // BUG SWP13062
2359               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2360               // WNT and ".so" for X-system) must be deleted
2361               int libname_len = libname.length();
2362 #ifdef WNT
2363               if( libname_len > 4 )
2364                 libname.resize( libname_len - 4 );
2365 #else
2366               // PAL17753 (Regresion: missing hypothesis in restored study)
2367               // "lib" also should be removed from the beginning
2368               //if( libname_len > 3 )
2369                 //libname.resize( libname_len - 3 );
2370               if( libname_len > 6 )
2371                 libname = libname.substr( 3, libname_len - 3 - 3 );
2372 #endif
2373               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2374               int    id      = myStudyContext->findId( string( objStr.in() ) );
2375               string hypdata = string( myImpl->SaveTo() );
2376
2377               // for each hypothesis create HDF group basing on its id
2378               char hypGrpName[30];
2379               sprintf( hypGrpName, "Hypothesis %d", id );
2380               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2381               aGroup->CreateOnDisk();
2382               // --> type name of hypothesis
2383               aSize[ 0 ] = hypname.length() + 1;
2384               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2385               aDataset->CreateOnDisk();
2386               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2387               aDataset->CloseOnDisk();
2388               // --> server plugin library name of hypothesis
2389               aSize[ 0 ] = libname.length() + 1;
2390               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2391               aDataset->CreateOnDisk();
2392               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2393               aDataset->CloseOnDisk();
2394               // --> persistent data of hypothesis
2395               aSize[ 0 ] = hypdata.length() + 1;
2396               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2397               aDataset->CreateOnDisk();
2398               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2399               aDataset->CloseOnDisk();
2400               // close hypothesis HDF group
2401               aGroup->CloseOnDisk();
2402             }
2403           }
2404         }
2405       }
2406       // close hypotheses root HDF group
2407       aTopGroup->CloseOnDisk();
2408     }
2409     // --> algorithms root branch (only one for the study)
2410     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
2411       // create algorithms root HDF group
2412       aTopGroup = new HDFgroup( "Algorithms", aFile );
2413       aTopGroup->CreateOnDisk();
2414
2415       // iterator for all algorithms
2416       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2417       for ( ; it->More(); it->Next() ) {
2418         SALOMEDS::SObject_var mySObject = it->Value();
2419         CORBA::Object_var anObject = SObjectToObject( mySObject );
2420         if ( !CORBA::is_nil( anObject ) ) {
2421           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2422           if ( !myHyp->_is_nil() ) {
2423             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2424             if ( myImpl ) {
2425               string hypname = string( myHyp->GetName() );
2426               string libname = string( myHyp->GetLibName() );
2427               // BUG SWP13062
2428               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2429               // WNT and ".so" for X-system) must be deleted
2430               int libname_len = libname.length();
2431 #ifdef WNT
2432               if( libname_len > 4 )
2433                 libname.resize( libname_len - 4 );
2434 #else
2435               // PAL17753 (Regresion: missing hypothesis in restored study)
2436               // "lib" also should be removed from the beginning
2437               //if( libname_len > 3 )
2438                 //libname.resize( libname_len - 3 );
2439               if( libname_len > 6 )
2440                 libname = libname.substr( 3, libname_len - 3 - 3 );
2441 #endif
2442               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2443               int    id      = myStudyContext->findId( string( objStr.in() ) );
2444               string hypdata = string( myImpl->SaveTo() );
2445
2446               // for each algorithm create HDF group basing on its id
2447               char hypGrpName[30];
2448               sprintf( hypGrpName, "Algorithm %d", id );
2449               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2450               aGroup->CreateOnDisk();
2451               // --> type name of algorithm
2452               aSize[0] = hypname.length() + 1;
2453               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2454               aDataset->CreateOnDisk();
2455               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2456               aDataset->CloseOnDisk();
2457               // --> server plugin library name of hypothesis
2458               aSize[0] = libname.length() + 1;
2459               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2460               aDataset->CreateOnDisk();
2461               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2462               aDataset->CloseOnDisk();
2463               // --> persistent data of algorithm
2464               aSize[0] = hypdata.length() + 1;
2465               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2466               aDataset->CreateOnDisk();
2467               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2468               aDataset->CloseOnDisk();
2469               // close algorithm HDF group
2470               aGroup->CloseOnDisk();
2471             }
2472           }
2473         }
2474       }
2475       // close algorithms root HDF group
2476       aTopGroup->CloseOnDisk();
2477     }
2478     // --> mesh objects roots branches
2479     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2480       CORBA::Object_var anObject = SObjectToObject( gotBranch );
2481       if ( !CORBA::is_nil( anObject ) ) {
2482         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2483         if ( !myMesh->_is_nil() ) {
2484           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
2485           if ( myImpl ) {
2486             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2487             int id = myStudyContext->findId( string( objStr.in() ) );
2488             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
2489             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2490             bool hasShape = myLocMesh.HasShapeToMesh();
2491
2492             // for each mesh open the HDF group basing on its id
2493             char meshGrpName[ 30 ];
2494             sprintf( meshGrpName, "Mesh %d", id );
2495             aTopGroup = new HDFgroup( meshGrpName, aFile );
2496             aTopGroup->CreateOnDisk();
2497
2498             // --> put dataset to hdf file which is a flag that mesh has data
2499             string strHasData = "0";
2500             // check if the mesh is not empty
2501             if ( mySMESHDSMesh->NbNodes() > 0 ) {
2502               // write mesh data to med file
2503               myWriter.SetMesh( mySMESHDSMesh );
2504               myWriter.SetMeshId( id );
2505               strHasData = "1";
2506             }
2507             aSize[ 0 ] = strHasData.length() + 1;
2508             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
2509             aDataset->CreateOnDisk();
2510             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
2511             aDataset->CloseOnDisk();
2512
2513             // ouv : NPAL12872
2514             // for each mesh open the HDF group basing on its auto color parameter
2515             char meshAutoColorName[ 30 ];
2516             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
2517             int anAutoColor[1];
2518             anAutoColor[0] = myImpl->GetAutoColor();
2519             aSize[ 0 ] = 1;
2520             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
2521             aDataset->CreateOnDisk();
2522             aDataset->WriteOnDisk( anAutoColor );
2523             aDataset->CloseOnDisk();
2524
2525             // write reference on a shape if exists
2526             SALOMEDS::SObject_var myRef;
2527             bool shapeRefFound = false;
2528             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
2529             if ( found ) {
2530               SALOMEDS::SObject_var myShape;
2531               bool ok = myRef->ReferencedObject( myShape );
2532               if ( ok ) {
2533                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
2534                 string myRefOnObject = myShape->GetID();
2535                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
2536                   aSize[ 0 ] = myRefOnObject.length() + 1;
2537                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
2538                   aDataset->CreateOnDisk();
2539                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2540                   aDataset->CloseOnDisk();
2541                 }
2542               }
2543             }
2544
2545             // write applied hypotheses if exist
2546             SALOMEDS::SObject_var myHypBranch;
2547             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
2548             if ( found && !shapeRefFound && hasShape) { // remove applied hyps
2549               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
2550             }
2551             if ( found && (shapeRefFound || !hasShape) ) {
2552               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2553               aGroup->CreateOnDisk();
2554
2555               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
2556               int hypNb = 0;
2557               for ( ; it->More(); it->Next() ) {
2558                 SALOMEDS::SObject_var mySObject = it->Value();
2559                 SALOMEDS::SObject_var myRefOnHyp;
2560                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
2561                 if ( ok ) {
2562                   // san - it is impossible to recover applied hypotheses
2563                   //       using their entries within Load() method,
2564                   // for there are no AttributeIORs in the study when Load() is working. 
2565                   // Hence, it is better to store persistent IDs of hypotheses as references to them
2566
2567                   //string myRefOnObject = myRefOnHyp->GetID();
2568                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
2569                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2570                   int id = myStudyContext->findId( string( objStr.in() ) );
2571                   //if ( myRefOnObject.length() > 0 ) {
2572                   //aSize[ 0 ] = myRefOnObject.length() + 1;
2573                   char hypName[ 30 ], hypId[ 30 ];
2574                   sprintf( hypName, "Hyp %d", ++hypNb );
2575                   sprintf( hypId, "%d", id );
2576                   aSize[ 0 ] = strlen( hypId ) + 1;
2577                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
2578                   aDataset->CreateOnDisk();
2579                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2580                   aDataset->WriteOnDisk( hypId );
2581                   aDataset->CloseOnDisk();
2582                   //}
2583                 }
2584               }
2585               aGroup->CloseOnDisk();
2586             }
2587
2588             // write applied algorithms if exist
2589             SALOMEDS::SObject_var myAlgoBranch;
2590             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
2591             if ( found && !shapeRefFound && hasShape) { // remove applied algos
2592               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
2593             }
2594             if ( found && (shapeRefFound || !hasShape)) {
2595               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
2596               aGroup->CreateOnDisk();
2597
2598               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
2599               int algoNb = 0;
2600               for ( ; it->More(); it->Next() ) {
2601                 SALOMEDS::SObject_var mySObject = it->Value();
2602                 SALOMEDS::SObject_var myRefOnAlgo;
2603                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
2604                 if ( ok ) {
2605                   // san - it is impossible to recover applied algorithms
2606                   //       using their entries within Load() method,
2607                   // for there are no AttributeIORs in the study when Load() is working. 
2608                   // Hence, it is better to store persistent IDs of algorithms as references to them
2609
2610                   //string myRefOnObject = myRefOnAlgo->GetID();
2611                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
2612                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2613                   int id = myStudyContext->findId( string( objStr.in() ) );
2614                   //if ( myRefOnObject.length() > 0 ) {
2615                   //aSize[ 0 ] = myRefOnObject.length() + 1;
2616                   char algoName[ 30 ], algoId[ 30 ];
2617                   sprintf( algoName, "Algo %d", ++algoNb );
2618                   sprintf( algoId, "%d", id );
2619                   aSize[ 0 ] = strlen( algoId ) + 1;
2620                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
2621                   aDataset->CreateOnDisk();
2622                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2623                   aDataset->WriteOnDisk( algoId );
2624                   aDataset->CloseOnDisk();
2625                   //}
2626                 }
2627               }
2628               aGroup->CloseOnDisk();
2629             }
2630
2631             // --> submesh objects sub-branches
2632
2633             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
2634               SALOMEDS::SObject_var mySubmeshBranch;
2635               found = gotBranch->FindSubObject( i, mySubmeshBranch );
2636
2637               if ( found ) // check if there is shape reference in submeshes
2638               {
2639                 bool hasShapeRef = false;
2640                 SALOMEDS::ChildIterator_var itSM =
2641                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
2642                 for ( ; itSM->More(); itSM->Next() ) {
2643                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
2644                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
2645                     mySubRef->ReferencedObject( myShape );
2646                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
2647                     hasShapeRef = true;
2648                   else
2649                   { // remove one submesh
2650                     if ( shapeRefFound )
2651                     { // unassign hypothesis
2652                       SMESH::SMESH_subMesh_var mySubMesh =
2653                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
2654                       if ( !mySubMesh->_is_nil() ) {
2655                         int shapeID = mySubMesh->GetId();
2656                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
2657                         const list<const SMESHDS_Hypothesis*>& hypList =
2658                           mySMESHDSMesh->GetHypothesis( S );
2659                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
2660                         while ( hyp != hypList.end() ) {
2661                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
2662                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
2663                         }
2664                       }
2665                     }
2666                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
2667                   }
2668                 } // loop on submeshes of a type
2669                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
2670                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
2671                   found = false;
2672                 }
2673               }  // end check if there is shape reference in submeshes
2674               if ( found ) {
2675                 char name_meshgroup[ 30 ];
2676                 if ( i == GetSubMeshOnVertexTag() )
2677                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
2678                 else if ( i == GetSubMeshOnEdgeTag() )
2679                   strcpy( name_meshgroup, "SubMeshes On Edge" );
2680                 else if ( i == GetSubMeshOnWireTag() )
2681                   strcpy( name_meshgroup, "SubMeshes On Wire" );
2682                 else if ( i == GetSubMeshOnFaceTag() )
2683                   strcpy( name_meshgroup, "SubMeshes On Face" );
2684                 else if ( i == GetSubMeshOnShellTag() )
2685                   strcpy( name_meshgroup, "SubMeshes On Shell" );
2686                 else if ( i == GetSubMeshOnSolidTag() )
2687                   strcpy( name_meshgroup, "SubMeshes On Solid" );
2688                 else if ( i == GetSubMeshOnCompoundTag() )
2689                   strcpy( name_meshgroup, "SubMeshes On Compound" );
2690
2691                 // for each type of submeshes create container HDF group
2692                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2693                 aGroup->CreateOnDisk();
2694
2695                 // iterator for all submeshes of given type
2696                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
2697                 for ( ; itSM->More(); itSM->Next() ) {
2698                   SALOMEDS::SObject_var mySObject = itSM->Value();
2699                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
2700                   if ( !CORBA::is_nil( anSubObject ))
2701                   {
2702                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
2703                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
2704                     int subid = myStudyContext->findId( string( objStr.in() ) );
2705
2706                     // for each mesh open the HDF group basing on its id
2707                     char submeshGrpName[ 30 ];
2708                     sprintf( submeshGrpName, "SubMesh %d", subid );
2709                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
2710                     aSubGroup->CreateOnDisk();
2711
2712                     // write reference on a shape, already checked if it exists
2713                     SALOMEDS::SObject_var mySubRef, myShape;
2714                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
2715                       mySubRef->ReferencedObject( myShape );
2716                     string myRefOnObject = myShape->GetID();
2717                     if ( myRefOnObject.length() > 0 ) {
2718                       aSize[ 0 ] = myRefOnObject.length() + 1;
2719                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
2720                       aDataset->CreateOnDisk();
2721                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2722                       aDataset->CloseOnDisk();
2723                     }
2724
2725                     // write applied hypotheses if exist
2726                     SALOMEDS::SObject_var mySubHypBranch;
2727                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
2728                     if ( found ) {
2729                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
2730                       aSubSubGroup->CreateOnDisk();
2731
2732                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
2733                       int hypNb = 0;
2734                       for ( ; it->More(); it->Next() ) {
2735                         SALOMEDS::SObject_var mySubSObject = it->Value();
2736                         SALOMEDS::SObject_var myRefOnHyp;
2737                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
2738                         if ( ok ) {
2739                           //string myRefOnObject = myRefOnHyp->GetID();
2740                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
2741                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2742                           int id = myStudyContext->findId( string( objStr.in() ) );
2743                           //if ( myRefOnObject.length() > 0 ) {
2744                           //aSize[ 0 ] = myRefOnObject.length() + 1;
2745                           char hypName[ 30 ], hypId[ 30 ];
2746                           sprintf( hypName, "Hyp %d", ++hypNb );
2747                           sprintf( hypId, "%d", id );
2748                           aSize[ 0 ] = strlen( hypId ) + 1;
2749                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
2750                           aDataset->CreateOnDisk();
2751                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2752                           aDataset->WriteOnDisk( hypId );
2753                           aDataset->CloseOnDisk();
2754                           //}
2755                         }
2756                       }
2757                       aSubSubGroup->CloseOnDisk();
2758                     }
2759
2760                     // write applied algorithms if exist
2761                     SALOMEDS::SObject_var mySubAlgoBranch;
2762                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
2763                     if ( found ) {
2764                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
2765                       aSubSubGroup->CreateOnDisk();
2766
2767                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
2768                       int algoNb = 0;
2769                       for ( ; it->More(); it->Next() ) {
2770                         SALOMEDS::SObject_var mySubSObject = it->Value();
2771                         SALOMEDS::SObject_var myRefOnAlgo;
2772                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
2773                         if ( ok ) {
2774                           //string myRefOnObject = myRefOnAlgo->GetID();
2775                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
2776                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2777                           int id = myStudyContext->findId( string( objStr.in() ) );
2778                           //if ( myRefOnObject.length() > 0 ) {
2779                           //aSize[ 0 ] = myRefOnObject.length() + 1;
2780                           char algoName[ 30 ], algoId[ 30 ];
2781                           sprintf( algoName, "Algo %d", ++algoNb );
2782                           sprintf( algoId, "%d", id );
2783                           aSize[ 0 ] = strlen( algoId ) + 1;
2784                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
2785                           aDataset->CreateOnDisk();
2786                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2787                           aDataset->WriteOnDisk( algoId );
2788                           aDataset->CloseOnDisk();
2789                           //}
2790                         }
2791                       }
2792                       aSubSubGroup->CloseOnDisk();
2793                     }
2794                     // close submesh HDF group
2795                     aSubGroup->CloseOnDisk();
2796                   }
2797                 }
2798                 // close container of submeshes by type HDF group
2799                 aGroup->CloseOnDisk();
2800               }
2801             }
2802             // All sub-meshes will be stored in MED file
2803             // .. will NOT (PAL 12992)
2804             //if ( shapeRefFound )
2805             //myWriter.AddAllSubMeshes();
2806
2807             // store submesh order if any
2808             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
2809             if ( theOrderIds.size() ) {
2810               char order_list[ 30 ];
2811               strcpy( order_list, "Mesh Order" );
2812               // count number of submesh ids
2813               int nbIDs = 0;
2814               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
2815               for ( ; idIt != theOrderIds.end(); idIt++ )
2816                 nbIDs += (*idIt).size();
2817               // number of values = number of IDs +
2818               //                    number of lists (for separators) - 1
2819               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
2820               idIt = theOrderIds.begin();
2821               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
2822                 const TListOfInt& idList = *idIt;
2823                 if (idIt != theOrderIds.begin()) // not first list
2824                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
2825                 // dump submesh ids from current list
2826                 TListOfInt::const_iterator id_smId = idList.begin();
2827                 for( ; id_smId != idList.end(); id_smId++ )
2828                   smIDs[ i++ ] = *id_smId;
2829               }
2830               // write HDF group
2831               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
2832
2833               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
2834               aDataset->CreateOnDisk();
2835               aDataset->WriteOnDisk( smIDs );
2836               aDataset->CloseOnDisk();
2837               //
2838               delete[] smIDs;
2839             }
2840
2841             // groups root sub-branch
2842             SALOMEDS::SObject_var myGroupsBranch;
2843             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
2844               found = gotBranch->FindSubObject( i, myGroupsBranch );
2845               if ( found ) {
2846                 char name_group[ 30 ];
2847                 if ( i == GetNodeGroupsTag() )
2848                   strcpy( name_group, "Groups of Nodes" );
2849                 else if ( i == GetEdgeGroupsTag() )
2850                   strcpy( name_group, "Groups of Edges" );
2851                 else if ( i == GetFaceGroupsTag() )
2852                   strcpy( name_group, "Groups of Faces" );
2853                 else if ( i == GetVolumeGroupsTag() )
2854                   strcpy( name_group, "Groups of Volumes" );
2855
2856                 aGroup = new HDFgroup( name_group, aTopGroup );
2857                 aGroup->CreateOnDisk();
2858
2859                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
2860                 for ( ; it->More(); it->Next() ) {
2861                   SALOMEDS::SObject_var mySObject = it->Value();
2862                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
2863                   if ( !CORBA::is_nil( aSubObject ) ) {
2864                     SMESH_GroupBase_i* myGroupImpl =
2865                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
2866                     if ( !myGroupImpl )
2867                       continue;
2868                     
2869                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
2870                     int anId = myStudyContext->findId( string( objStr.in() ) );
2871                     
2872                     // For each group, create a dataset named "Group <group_persistent_id>"
2873                     // and store the group's user name into it
2874                     char grpName[ 30 ];
2875                     sprintf( grpName, "Group %d", anId );
2876                     char* aUserName = myGroupImpl->GetName();
2877                     aSize[ 0 ] = strlen( aUserName ) + 1;
2878                     
2879                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
2880                     aDataset->CreateOnDisk();
2881                     aDataset->WriteOnDisk( aUserName );
2882                     aDataset->CloseOnDisk();
2883
2884                     // ouv : NPAL12872
2885                     // For each group, create a dataset named "Group <group_persistent_id> Color"
2886                     // and store the group's color into it
2887                     char grpColorName[ 30 ];
2888                     sprintf( grpColorName, "ColorGroup %d", anId );
2889                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
2890                     double anRGB[3];
2891                     anRGB[ 0 ] = aColor.R;
2892                     anRGB[ 1 ] = aColor.G;
2893                     anRGB[ 2 ] = aColor.B;
2894                     aSize[ 0 ] = 3;
2895                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
2896                     aDataset->CreateOnDisk();
2897                     aDataset->WriteOnDisk( anRGB );
2898                     aDataset->CloseOnDisk();
2899
2900                     // Store the group contents into MED file
2901                     if ( myLocMesh.GetGroup( myGroupImpl->GetLocalID() ) ) {
2902                       
2903                       if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen_i::Save(): saving group with StoreName = "
2904                                           << grpName << " to MED file" );
2905                       SMESHDS_GroupBase* aGrpBaseDS =
2906                         myLocMesh.GetGroup( myGroupImpl->GetLocalID() )->GetGroupDS();
2907                       aGrpBaseDS->SetStoreName( grpName );
2908
2909                       // Pass SMESHDS_Group to MED writer 
2910                       SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
2911                       if ( aGrpDS )
2912                         myWriter.AddGroup( aGrpDS );
2913                       
2914                       // write reference on a shape if exists
2915                       SMESHDS_GroupOnGeom* aGeomGrp =
2916                         dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
2917                       if ( aGeomGrp ) {
2918                         SALOMEDS::SObject_var mySubRef, myShape;
2919                         if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
2920                             mySubRef->ReferencedObject( myShape ) &&
2921                             !CORBA::is_nil( myShape->GetObject() ))
2922                         {
2923                           string myRefOnObject = myShape->GetID();
2924                           if ( myRefOnObject.length() > 0 ) {
2925                             char aRefName[ 30 ];
2926                             sprintf( aRefName, "Ref on shape %d", anId);
2927                             aSize[ 0 ] = myRefOnObject.length() + 1;
2928                             aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
2929                             aDataset->CreateOnDisk();
2930                             aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2931                             aDataset->CloseOnDisk();
2932                           }
2933                         }
2934                         else // shape ref is invalid:
2935                         {
2936                           // save a group on geometry as ordinary group
2937                           myWriter.AddGroup( aGeomGrp );
2938                         }
2939                       }
2940                     }
2941                   }
2942                 }
2943                 aGroup->CloseOnDisk();
2944               }
2945             } // loop on groups 
2946             
2947             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
2948             {
2949               // Flush current mesh information into MED file
2950               myWriter.Perform();
2951               
2952               // maybe a shape was deleted in the study
2953               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
2954                 TopoDS_Shape nullShape;
2955                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
2956               }
2957               
2958               if ( !mySMESHDSMesh->SubMeshes().empty() )
2959               {
2960                 // Store submeshes
2961                 // ----------------
2962                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
2963                 aGroup->CreateOnDisk();
2964                 
2965                 // each element belongs to one or none submesh,
2966                 // so for each node/element, we store a submesh ID
2967                 
2968                 // Make maps of submesh IDs of elements sorted by element IDs
2969                 typedef int TElemID;
2970                 typedef int TSubMID;
2971                 map< TElemID, TSubMID > eId2smId, nId2smId;
2972                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
2973                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
2974                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
2975                 SMDS_NodeIteratorPtr itNode;
2976                 SMDS_ElemIteratorPtr itElem;
2977                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
2978                 {
2979                   TSubMID          aSubMeID = itSubM->first;
2980                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
2981                   if ( aSubMesh->IsComplexSubmesh() )
2982                     continue; // submesh containing other submeshs
2983                   // nodes
2984                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
2985                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
2986                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
2987                   // elements
2988                   hint = eId2smId.begin();
2989                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
2990                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
2991                 }
2992                 
2993                 // Care of elements that are not on submeshes
2994                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
2995                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
2996                     /*  --- stl_map.h says : */
2997                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
2998                     /*  first element (the key) is not already present in the %map.           */
2999                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
3000                 }
3001                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
3002                 if ( nbElems != eId2smId.size() ) {
3003                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
3004                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
3005                 }
3006                 
3007                 // Store submesh IDs
3008                 for ( int isNode = 0; isNode < 2; ++isNode )
3009                 {
3010                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
3011                   if ( id2smId.empty() ) continue;
3012                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
3013                   // make and fill array of submesh IDs
3014                   int* smIDs = new int [ id2smId.size() ];
3015                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
3016                     smIDs[ i ] = id_smId->second;
3017                   // write HDF group
3018                   aSize[ 0 ] = id2smId.size();
3019                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3020                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3021                   aDataset->CreateOnDisk();
3022                   aDataset->WriteOnDisk( smIDs );
3023                   aDataset->CloseOnDisk();
3024                   //
3025                   delete[] smIDs;
3026                 }
3027                 
3028                 // Store node positions on sub-shapes (SMDS_Position):
3029                 // ----------------------------------------------------
3030                 
3031                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3032                 aGroup->CreateOnDisk();
3033                 
3034                 // in aGroup, create 5 datasets to contain:
3035                 // "Nodes on Edges" - ID of node on edge
3036                 // "Edge positions" - U parameter on node on edge
3037                 // "Nodes on Faces" - ID of node on face
3038                 // "Face U positions" - U parameter of node on face
3039                 // "Face V positions" - V parameter of node on face
3040                 
3041                 // Find out nb of nodes on edges and faces
3042                 // Collect corresponing sub-meshes
3043                 int nbEdgeNodes = 0, nbFaceNodes = 0;
3044                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3045                 // loop on SMESHDS_SubMesh'es
3046                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3047                 {
3048                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
3049                   if ( aSubMesh->IsComplexSubmesh() )
3050                     continue; // submesh containing other submeshs
3051                   int nbNodes = aSubMesh->NbNodes();
3052                   if ( nbNodes == 0 ) continue;
3053                   
3054                   int aShapeID = (*itSubM).first;
3055                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3056                     continue;
3057                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3058                   // write only SMDS_FacePosition and SMDS_EdgePosition
3059                   switch ( aShapeType ) {
3060                   case TopAbs_FACE:
3061                     nbFaceNodes += nbNodes;
3062                     aFaceSM.push_back( aSubMesh );
3063                     break;
3064                   case TopAbs_EDGE:
3065                     nbEdgeNodes += nbNodes;
3066                     aEdgeSM.push_back( aSubMesh );
3067                     break;
3068                   default:
3069                     continue;
3070                   }
3071                 }
3072                 // Treat positions on edges or faces
3073                 for ( int onFace = 0; onFace < 2; onFace++ )
3074                 {
3075                   // Create arrays to store in datasets
3076                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3077                   if (!nbNodes) continue;
3078                   int* aNodeIDs = new int [ nbNodes ];
3079                   double* aUPos = new double [ nbNodes ];
3080                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3081                   
3082                   // Fill arrays
3083                   // loop on sub-meshes
3084                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3085                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3086                   for ( ; itSM != pListSM->end(); itSM++ )
3087                   {
3088                     SMESHDS_SubMesh* aSubMesh = (*itSM);
3089                     
3090                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3091                     // loop on nodes in aSubMesh
3092                     while ( itNode->more() )
3093                     {
3094                       //node ID
3095                       const SMDS_MeshNode* node = itNode->next();
3096                       aNodeIDs [ iNode ] = node->GetID();
3097                       
3098                       // Position
3099                       const SMDS_PositionPtr pos = node->GetPosition();
3100                       if ( onFace ) { // on FACE
3101                         const SMDS_FacePosition* fPos =
3102                           dynamic_cast<const SMDS_FacePosition*>( pos );
3103                         if ( fPos ) {
3104                           aUPos[ iNode ] = fPos->GetUParameter();
3105                           aVPos[ iNode ] = fPos->GetVParameter();
3106                           iNode++;
3107                         }
3108                         else
3109                           nbNodes--;
3110                       }
3111                       else { // on EDGE
3112                         const SMDS_EdgePosition* ePos =
3113                           dynamic_cast<const SMDS_EdgePosition*>( pos );
3114                         if ( ePos ) {
3115                           aUPos[ iNode ] = ePos->GetUParameter();
3116                           iNode++;
3117                         }
3118                         else
3119                           nbNodes--;
3120                       }
3121                     } // loop on nodes in aSubMesh
3122                   } // loop on sub-meshes
3123                   
3124                   // Write datasets
3125                   if ( nbNodes )
3126                   {
3127                     aSize[ 0 ] = nbNodes;
3128                     // IDS
3129                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3130                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3131                     aDataset->CreateOnDisk();
3132                     aDataset->WriteOnDisk( aNodeIDs );
3133                     aDataset->CloseOnDisk();
3134                 
3135                     // U Positions
3136                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
3137                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3138                     aDataset->CreateOnDisk();
3139                     aDataset->WriteOnDisk( aUPos );
3140                     aDataset->CloseOnDisk();
3141                     // V Positions
3142                     if ( onFace ) {
3143                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3144                       aDataset->CreateOnDisk();
3145                       aDataset->WriteOnDisk( aVPos );
3146                       aDataset->CloseOnDisk();
3147                     }
3148                   }
3149                   delete [] aNodeIDs;
3150                   delete [] aUPos;
3151                   if ( aVPos ) delete [] aVPos;
3152                   
3153                 } // treat positions on edges or faces
3154                 
3155                 // close "Node Positions" group
3156                 aGroup->CloseOnDisk(); 
3157                 
3158               } // if ( there are submeshes in SMESHDS_Mesh )
3159             } // if ( hasData )
3160             
3161             // close mesh HDF group
3162             aTopGroup->CloseOnDisk();
3163           }
3164         }
3165       }
3166     }
3167   }
3168   
3169   // close HDF file
3170   aFile->CloseOnDisk();
3171   delete aFile;
3172
3173   // Convert temporary files to stream
3174   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3175
3176   // Remove temporary files and directory
3177   if ( !isMultiFile ) 
3178     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3179
3180   INFOS( "SMESH_Gen_i::Save() completed" );
3181   return aStreamFile._retn();
3182 }
3183
3184 //=============================================================================
3185 /*!
3186  *  SMESH_Gen_i::SaveASCII
3187  *
3188  *  Save SMESH module's data in ASCII format
3189  */
3190 //=============================================================================
3191
3192 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3193                                            const char*              theURL,
3194                                            bool                     isMultiFile ) {
3195   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3196   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3197   return aStreamFile._retn();
3198
3199   //after usual saving needs to encipher binary to text string
3200   //Any binary symbol will be represent as "|xx" () hexadecimal format number
3201   int size = aStreamFile.in().length();
3202   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3203   for ( int i = 0; i < size; i++ )
3204     sprintf( (char*)&(buffer[i*3]), "|%02x", (char*)(aStreamFile[i]) );
3205
3206   buffer[size * 3] = '\0';
3207
3208   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3209   
3210   return anAsciiStreamFile._retn();
3211 }
3212
3213 //=============================================================================
3214 /*!
3215  *  SMESH_Gen_i::loadGeomData
3216  *
3217  *  Load GEOM module data
3218  */
3219 //=============================================================================
3220
3221 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3222 {
3223   if ( theCompRoot->_is_nil() )
3224     return;
3225
3226   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3227   if ( aStudy->_is_nil() )
3228     return;
3229
3230   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
3231   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3232 }
3233 //=============================================================================
3234 /*!
3235  * \brief Creates SMDS_Position according to shape type
3236  */
3237 //=============================================================================
3238
3239 class PositionCreator {
3240 public:
3241   SMDS_PositionPtr MakePosition(const TopAbs_ShapeEnum type) {
3242     return (this->*myFuncTable[ type ])();
3243   }
3244   PositionCreator() {
3245     myFuncTable.resize( (size_t) TopAbs_SHAPE, & PositionCreator::defaultPosition );
3246     myFuncTable[ TopAbs_FACE ] = & PositionCreator::facePosition;
3247     myFuncTable[ TopAbs_EDGE ] = & PositionCreator::edgePosition;
3248     myFuncTable[ TopAbs_VERTEX ] = & PositionCreator::vertexPosition;
3249   }
3250 private:
3251   SMDS_PositionPtr edgePosition()    const { return SMDS_PositionPtr( new SMDS_EdgePosition  ); }
3252   SMDS_PositionPtr facePosition()    const { return SMDS_PositionPtr( new SMDS_FacePosition  ); }
3253   SMDS_PositionPtr vertexPosition()  const { return SMDS_PositionPtr( new SMDS_VertexPosition); }
3254   SMDS_PositionPtr defaultPosition() const { return SMDS_SpacePosition::originSpacePosition();  }
3255   typedef SMDS_PositionPtr (PositionCreator:: * FmakePos)() const;
3256   vector<FmakePos> myFuncTable;
3257 };
3258
3259 //=============================================================================
3260 /*!
3261  *  SMESH_Gen_i::Load
3262  *
3263  *  Load SMESH module's data
3264  */
3265 //=============================================================================
3266
3267 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3268                         const SALOMEDS::TMPFile& theStream,
3269                         const char*              theURL,
3270                         bool                     isMultiFile )
3271 {
3272   INFOS( "SMESH_Gen_i::Load" );
3273
3274   if ( myCurrentStudy->_is_nil() || 
3275        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
3276     SetCurrentStudy( theComponent->GetStudy() );
3277
3278   /*  if( !theComponent->_is_nil() )
3279       {
3280       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
3281       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
3282       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
3283       }*/
3284
3285   StudyContext* myStudyContext = GetCurrentStudyContext();
3286
3287   // Get temporary files location
3288   TCollection_AsciiString tmpDir =
3289     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3290     
3291     INFOS( "THE URL++++++++++++++" )
3292     INFOS( theURL );
3293     INFOS( "THE TMP PATH+++++++++" );
3294     INFOS( tmpDir );
3295
3296   // Convert the stream into sequence of files to process
3297   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
3298                                                                             tmpDir.ToCString(),
3299                                                                             isMultiFile );
3300   TCollection_AsciiString aStudyName( "" );
3301   if ( isMultiFile ) 
3302     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3303
3304   // Set names of temporary files
3305   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
3306   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
3307
3308   int size;
3309   HDFfile*    aFile;
3310   HDFdataset* aDataset;
3311   HDFgroup*   aTopGroup;
3312   HDFgroup*   aGroup;
3313   HDFgroup*   aSubGroup;
3314   HDFgroup*   aSubSubGroup;
3315
3316   // Read data
3317   // ---> open HDF file
3318   aFile = new HDFfile( (char*) filename.ToCString() );
3319   try {
3320     aFile->OpenOnDisk( HDF_RDONLY );
3321   }
3322   catch ( HDFexception ) {
3323     INFOS( "Load(): " << filename << " not found!" );
3324     return false;
3325   }
3326
3327   DriverMED_R_SMESHDS_Mesh myReader;
3328   myReader.SetFile( meshfile.ToCString() );
3329
3330   // For PAL13473 ("Repetitive mesh") implementation.
3331   // New dependencies between SMESH objects are established:
3332   // now hypotheses can refer to meshes, shapes and other hypotheses.
3333   // To keep data consistent, the following order of data restoration
3334   // imposed:
3335   // 1. Create hypotheses
3336   // 2. Create all meshes
3337   // 3. Load hypotheses' data
3338   // 4. All the rest
3339
3340   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
3341   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
3342
3343   // get total number of top-level groups
3344   int aNbGroups = aFile->nInternalObjects(); 
3345   if ( aNbGroups > 0 ) {
3346     // --> in first turn we should read&create hypotheses
3347     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
3348       // open hypotheses root HDF group
3349       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
3350       aTopGroup->OpenOnDisk();
3351
3352       // get number of hypotheses
3353       int aNbObjects = aTopGroup->nInternalObjects(); 
3354       for ( int j = 0; j < aNbObjects; j++ ) {
3355         // try to identify hypothesis
3356         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3357         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3358
3359         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
3360           // open hypothesis group
3361           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
3362           aGroup->OpenOnDisk();
3363
3364           // --> get hypothesis id
3365           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
3366           string hypname;
3367           string libname;
3368           string hypdata;
3369
3370           // get number of datasets
3371           int aNbSubObjects = aGroup->nInternalObjects();
3372           for ( int k = 0; k < aNbSubObjects; k++ ) {
3373             // identify dataset
3374             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3375             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3376             // --> get hypothesis name
3377             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3378               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3379               aDataset->OpenOnDisk();
3380               size = aDataset->GetSize();
3381               char* hypname_str = new char[ size ];
3382               aDataset->ReadFromDisk( hypname_str );
3383               hypname = string( hypname_str );
3384               delete [] hypname_str;
3385               aDataset->CloseOnDisk();
3386             }
3387             // --> get hypothesis plugin library name
3388             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3389               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3390               aDataset->OpenOnDisk();
3391               size = aDataset->GetSize();
3392               char* libname_str = new char[ size ];
3393               aDataset->ReadFromDisk( libname_str );
3394               if(MYDEBUG) SCRUTE( libname_str );
3395               libname = string( libname_str );
3396               delete [] libname_str;
3397               aDataset->CloseOnDisk();
3398             }
3399             // --> get hypothesis data
3400             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3401               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3402               aDataset->OpenOnDisk();
3403               size = aDataset->GetSize();
3404               char* hypdata_str = new char[ size ];
3405               aDataset->ReadFromDisk( hypdata_str );
3406               hypdata = string( hypdata_str );
3407               delete [] hypdata_str;
3408               aDataset->CloseOnDisk();
3409             }
3410           }
3411           // close hypothesis HDF group
3412           aGroup->CloseOnDisk();
3413
3414           // --> restore hypothesis from data
3415           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3416             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
3417                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3418             SMESH::SMESH_Hypothesis_var myHyp;
3419
3420             try { // protect persistence mechanism against exceptions
3421               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3422             }
3423             catch (...) {
3424               INFOS( "Exception during hypothesis creation" );
3425             }
3426
3427             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3428             if ( myImpl ) {
3429               // myImpl->LoadFrom( hypdata.c_str() );
3430               hypDataList.push_back( make_pair( myImpl, hypdata ));
3431               string iorString = GetORB()->object_to_string( myHyp );
3432               int newId = myStudyContext->findId( iorString );
3433               myStudyContext->mapOldToNew( id, newId );
3434             }
3435             else
3436               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
3437           }
3438         }
3439       }
3440       // close hypotheses root HDF group
3441       aTopGroup->CloseOnDisk();
3442       aTopGroup = 0;
3443     }
3444
3445     // --> then we should read&create algorithms
3446     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
3447       // open algorithms root HDF group
3448       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
3449       aTopGroup->OpenOnDisk();
3450
3451       // get number of algorithms
3452       int aNbObjects = aTopGroup->nInternalObjects(); 
3453       for ( int j = 0; j < aNbObjects; j++ ) {
3454         // try to identify algorithm
3455         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3456         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3457
3458         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
3459           // open algorithm group
3460           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
3461           aGroup->OpenOnDisk();
3462
3463           // --> get algorithm id
3464           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
3465           string hypname;
3466           string libname;
3467           string hypdata;
3468
3469           // get number of datasets
3470           int aNbSubObjects = aGroup->nInternalObjects();
3471           for ( int k = 0; k < aNbSubObjects; k++ ) {
3472             // identify dataset
3473             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3474             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3475             // --> get algorithm name
3476             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3477               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3478               aDataset->OpenOnDisk();
3479               size = aDataset->GetSize();
3480               char* hypname_str = new char[ size ];
3481               aDataset->ReadFromDisk( hypname_str );
3482               hypname = string( hypname_str );
3483               delete [] hypname_str;
3484               aDataset->CloseOnDisk();
3485             }
3486             // --> get algorithm plugin library name
3487             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3488               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3489               aDataset->OpenOnDisk();
3490               size = aDataset->GetSize();
3491               char* libname_str = new char[ size ];
3492               aDataset->ReadFromDisk( libname_str );
3493               if(MYDEBUG) SCRUTE( libname_str );
3494               libname = string( libname_str );
3495               delete [] libname_str;
3496               aDataset->CloseOnDisk();
3497             }
3498             // --> get algorithm data
3499             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3500               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3501               aDataset->OpenOnDisk();
3502               size = aDataset->GetSize();
3503               char* hypdata_str = new char[ size ];
3504               aDataset->ReadFromDisk( hypdata_str );
3505               if(MYDEBUG) SCRUTE( hypdata_str );
3506               hypdata = string( hypdata_str );
3507               delete [] hypdata_str;
3508               aDataset->CloseOnDisk();
3509             }
3510           }
3511           // close algorithm HDF group
3512           aGroup->CloseOnDisk();
3513
3514           // --> restore algorithm from data
3515           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3516             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
3517                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3518             SMESH::SMESH_Hypothesis_var myHyp;
3519
3520             try { // protect persistence mechanism against exceptions
3521               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3522             }
3523             catch (...) {
3524               INFOS( "Exception during hypothesis creation" );
3525             }
3526
3527             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3528             if ( myImpl ) {
3529               //myImpl->LoadFrom( hypdata.c_str() );
3530               hypDataList.push_back( make_pair( myImpl, hypdata ));
3531               string iorString = GetORB()->object_to_string( myHyp );
3532               int newId = myStudyContext->findId( iorString );
3533               myStudyContext->mapOldToNew( id, newId );
3534             }
3535             else
3536               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
3537           }
3538         }
3539       }
3540       // close algorithms root HDF group
3541       aTopGroup->CloseOnDisk();
3542       aTopGroup = 0;
3543     }
3544
3545     // --> the rest groups should be meshes
3546     for ( int i = 0; i < aNbGroups; i++ ) {
3547       // identify next group
3548       char meshName[ HDF_NAME_MAX_LEN+1 ];
3549       aFile->InternalObjectIndentify( i, meshName );
3550
3551       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
3552         // --> get mesh id
3553         int id = atoi( string( meshName ).substr( 4 ).c_str() );
3554         if ( id <= 0 )
3555           continue;
3556
3557         // open mesh HDF group
3558         aTopGroup = new HDFgroup( meshName, aFile ); 
3559         aTopGroup->OpenOnDisk();
3560
3561         // get number of child HDF objects
3562         int aNbObjects = aTopGroup->nInternalObjects(); 
3563         if ( aNbObjects > 0 ) {
3564           // create mesh
3565           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
3566           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
3567           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
3568           if ( !myNewMeshImpl )
3569             continue;
3570           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
3571
3572           string iorString = GetORB()->object_to_string( myNewMesh );
3573           int newId = myStudyContext->findId( iorString );
3574           myStudyContext->mapOldToNew( id, newId );
3575
3576           // ouv : NPAL12872
3577           // try to read and set auto color flag
3578           char aMeshAutoColorName[ 30 ];
3579           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
3580           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
3581           {
3582             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
3583             aDataset->OpenOnDisk();
3584             size = aDataset->GetSize();
3585             int* anAutoColor = new int[ size ];
3586             aDataset->ReadFromDisk( anAutoColor );
3587             aDataset->CloseOnDisk();
3588             myNewMeshImpl->SetAutoColor( (bool)anAutoColor[0] );
3589           }
3590
3591           // try to read and set reference to shape
3592           GEOM::GEOM_Object_var aShapeObject;
3593           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
3594             // load mesh "Ref on shape" - it's an entry to SObject
3595             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
3596             aDataset->OpenOnDisk();
3597             size = aDataset->GetSize();
3598             char* refFromFile = new char[ size ];
3599             aDataset->ReadFromDisk( refFromFile );
3600             aDataset->CloseOnDisk();
3601             if ( strlen( refFromFile ) > 0 ) {
3602               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
3603
3604               // Make sure GEOM data are loaded first
3605               //loadGeomData( shapeSO->GetFatherComponent() );
3606
3607               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
3608               if ( !CORBA::is_nil( shapeObject ) ) {
3609                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
3610                 if ( !aShapeObject->_is_nil() )
3611                   myNewMeshImpl->SetShape( aShapeObject );
3612               }
3613             }
3614           }
3615         }
3616       }
3617     }
3618
3619     // As all object that can be referred by hypothesis are created,
3620     // we can restore hypothesis data
3621
3622     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
3623     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
3624     {
3625       SMESH_Hypothesis_i* hyp  = hyp_data->first;
3626       string &            data = hyp_data->second;
3627       hyp->LoadFrom( data.c_str() );
3628     }
3629
3630     // Restore the rest mesh data
3631
3632     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
3633     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
3634     {
3635       aTopGroup                   = meshi_group->second;
3636       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
3637       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
3638       SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3639
3640       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
3641       bool hasData = false;
3642
3643       // get mesh old id
3644       string iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
3645       int newId = myStudyContext->findId( iorString );
3646       int id = myStudyContext->getOldId( newId );
3647
3648       // try to find mesh data dataset
3649       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
3650         // load mesh "has data" flag
3651         aDataset = new HDFdataset( "Has data", aTopGroup );
3652         aDataset->OpenOnDisk();
3653         size = aDataset->GetSize();
3654         char* strHasData = new char[ size ];
3655         aDataset->ReadFromDisk( strHasData );
3656         aDataset->CloseOnDisk();
3657         if ( strcmp( strHasData, "1") == 0 ) {
3658           // read mesh data from MED file
3659           myReader.SetMesh( mySMESHDSMesh );
3660           myReader.SetMeshId( id );
3661           myReader.Perform();
3662           hasData = true;
3663         }
3664       }
3665
3666       // try to get applied algorithms
3667       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
3668         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3669         aGroup->OpenOnDisk();
3670         // get number of applied algorithms
3671         int aNbSubObjects = aGroup->nInternalObjects(); 
3672         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
3673         for ( int j = 0; j < aNbSubObjects; j++ ) {
3674           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3675           aGroup->InternalObjectIndentify( j, name_dataset );
3676           // check if it is an algorithm
3677           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
3678             aDataset = new HDFdataset( name_dataset, aGroup );
3679             aDataset->OpenOnDisk();
3680             size = aDataset->GetSize();
3681             char* refFromFile = new char[ size ];
3682             aDataset->ReadFromDisk( refFromFile );
3683             aDataset->CloseOnDisk();
3684
3685             // san - it is impossible to recover applied algorithms using their entries within Load() method
3686
3687             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3688             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3689             int id = atoi( refFromFile );
3690             string anIOR = myStudyContext->getIORbyOldId( id );
3691             if ( !anIOR.empty() ) {
3692               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3693               if ( !CORBA::is_nil( hypObject ) ) {
3694                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3695                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
3696                                            || !myNewMeshImpl->HasShapeToMesh()) )
3697                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
3698               }
3699             }
3700           }
3701         }
3702         aGroup->CloseOnDisk();
3703       }
3704
3705       // try to get applied hypotheses
3706       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
3707         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3708         aGroup->OpenOnDisk();
3709         // get number of applied hypotheses
3710         int aNbSubObjects = aGroup->nInternalObjects(); 
3711         for ( int j = 0; j < aNbSubObjects; j++ ) {
3712           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3713           aGroup->InternalObjectIndentify( j, name_dataset );
3714           // check if it is a hypothesis
3715           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
3716             aDataset = new HDFdataset( name_dataset, aGroup );
3717             aDataset->OpenOnDisk();
3718             size = aDataset->GetSize();
3719             char* refFromFile = new char[ size ];
3720             aDataset->ReadFromDisk( refFromFile );
3721             aDataset->CloseOnDisk();
3722
3723             // san - it is impossible to recover applied hypotheses using their entries within Load() method
3724
3725             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3726             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3727             int id = atoi( refFromFile );
3728             string anIOR = myStudyContext->getIORbyOldId( id );
3729             if ( !anIOR.empty() ) {
3730               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3731               if ( !CORBA::is_nil( hypObject ) ) {
3732                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3733                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
3734                                            || !myNewMeshImpl->HasShapeToMesh()) )
3735                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
3736               }
3737             }
3738           }
3739         }
3740         aGroup->CloseOnDisk();
3741       }
3742
3743       // --> try to find submeshes containers for each type of submesh
3744       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
3745         char name_meshgroup[ 30 ];
3746         if ( j == GetSubMeshOnVertexTag() )
3747           strcpy( name_meshgroup, "SubMeshes On Vertex" );
3748         else if ( j == GetSubMeshOnEdgeTag() )
3749           strcpy( name_meshgroup, "SubMeshes On Edge" );
3750         else if ( j == GetSubMeshOnWireTag() )
3751           strcpy( name_meshgroup, "SubMeshes On Wire" );
3752         else if ( j == GetSubMeshOnFaceTag() )
3753           strcpy( name_meshgroup, "SubMeshes On Face" );
3754         else if ( j == GetSubMeshOnShellTag() )
3755           strcpy( name_meshgroup, "SubMeshes On Shell" );
3756         else if ( j == GetSubMeshOnSolidTag() )
3757           strcpy( name_meshgroup, "SubMeshes On Solid" );
3758         else if ( j == GetSubMeshOnCompoundTag() )
3759           strcpy( name_meshgroup, "SubMeshes On Compound" );
3760
3761         // try to get submeshes container HDF group
3762         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
3763           // open submeshes containers HDF group
3764           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3765           aGroup->OpenOnDisk();
3766
3767           // get number of submeshes
3768           int aNbSubMeshes = aGroup->nInternalObjects(); 
3769           for ( int k = 0; k < aNbSubMeshes; k++ ) {
3770             // identify submesh
3771             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
3772             aGroup->InternalObjectIndentify( k, name_submeshgroup );
3773             if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
3774               // --> get submesh id
3775               int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
3776               if ( subid <= 0 )
3777                 continue;
3778               // open submesh HDF group
3779               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
3780               aSubGroup->OpenOnDisk();
3781
3782               // try to read and set reference to subshape
3783               GEOM::GEOM_Object_var aSubShapeObject;
3784               SMESH::SMESH_subMesh_var aSubMesh;
3785
3786               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
3787                 // load submesh "Ref on shape" - it's an entry to SObject
3788                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
3789                 aDataset->OpenOnDisk();
3790                 size = aDataset->GetSize();
3791                 char* refFromFile = new char[ size ];
3792                 aDataset->ReadFromDisk( refFromFile );
3793                 aDataset->CloseOnDisk();
3794                 if ( strlen( refFromFile ) > 0 ) {
3795                   SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
3796                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
3797                   if ( !CORBA::is_nil( subShapeObject ) ) {
3798                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
3799                     if ( !aSubShapeObject->_is_nil() )
3800                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
3801                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
3802                     if ( aSubMesh->_is_nil() )
3803                       continue;
3804                     string iorSubString = GetORB()->object_to_string( aSubMesh );
3805                     int newSubId = myStudyContext->findId( iorSubString );
3806                     myStudyContext->mapOldToNew( subid, newSubId );
3807                   }
3808                 }
3809               }
3810
3811               if ( aSubMesh->_is_nil() )
3812                 continue;
3813
3814               // VSR: Get submesh data from MED convertor
3815               //                  int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
3816               //                  if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
3817               //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
3818               //                            subid << " for subshape # " << anInternalSubmeshId);
3819               //                    SMESHDS_SubMesh* aSubMeshDS =
3820               //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
3821               //                    if ( !aSubMeshDS ) {
3822               //                      if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
3823               //                              anInternalSubmeshId << " in current mesh!");
3824               //                    }
3825               //                    else
3826               //                      myReader.GetSubMesh( aSubMeshDS, subid );
3827               //                  }
3828
3829               // try to get applied algorithms
3830               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
3831                 // open "applied algorithms" HDF group
3832                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3833                 aSubSubGroup->OpenOnDisk();
3834                 // get number of applied algorithms
3835                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
3836                 for ( int l = 0; l < aNbSubObjects; l++ ) {
3837                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3838                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
3839                   // check if it is an algorithm
3840                   if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
3841                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
3842                     aDataset->OpenOnDisk();
3843                     size = aDataset->GetSize();
3844                     char* refFromFile = new char[ size ];
3845                     aDataset->ReadFromDisk( refFromFile );
3846                     aDataset->CloseOnDisk();
3847
3848                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3849                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3850                     int id = atoi( refFromFile );
3851                     string anIOR = myStudyContext->getIORbyOldId( id );
3852                     if ( !anIOR.empty() ) {
3853                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3854                       if ( !CORBA::is_nil( hypObject ) ) {
3855                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3856                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
3857                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
3858                       }
3859                     }
3860                   }
3861                 }
3862                 // close "applied algorithms" HDF group
3863                 aSubSubGroup->CloseOnDisk();
3864               }
3865
3866               // try to get applied hypotheses
3867               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
3868                 // open "applied hypotheses" HDF group
3869                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3870                 aSubSubGroup->OpenOnDisk();
3871                 // get number of applied hypotheses
3872                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
3873                 for ( int l = 0; l < aNbSubObjects; l++ ) {
3874                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3875                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
3876                   // check if it is a hypothesis
3877                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
3878                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
3879                     aDataset->OpenOnDisk();
3880                     size = aDataset->GetSize();
3881                     char* refFromFile = new char[ size ];
3882                     aDataset->ReadFromDisk( refFromFile );
3883                     aDataset->CloseOnDisk();
3884
3885                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3886                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3887                     int id = atoi( refFromFile );
3888                     string anIOR = myStudyContext->getIORbyOldId( id );
3889                     if ( !anIOR.empty() ) {
3890                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3891                       if ( !CORBA::is_nil( hypObject ) ) {
3892                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3893                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
3894                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
3895                       }
3896                     }
3897                   }
3898                 }
3899                 // close "applied hypotheses" HDF group
3900                 aSubSubGroup->CloseOnDisk();
3901               }
3902
3903               // close submesh HDF group
3904               aSubGroup->CloseOnDisk();
3905             }
3906           }
3907           // close submeshes containers HDF group
3908           aGroup->CloseOnDisk();
3909         }
3910       }
3911
3912       if(hasData) {
3913
3914         // Read sub-meshes from MED
3915         // -------------------------
3916         if(MYDEBUG) MESSAGE("Create all sub-meshes");
3917         bool submeshesInFamilies = ( ! aTopGroup->ExistInternalObject( "Submeshes" ));
3918         if ( submeshesInFamilies )
3919         {
3920           // old way working before fix of PAL 12992
3921           myReader.CreateAllSubMeshes();
3922         }
3923         else
3924         {
3925           // open a group
3926           aGroup = new HDFgroup( "Submeshes", aTopGroup ); 
3927           aGroup->OpenOnDisk();
3928
3929           int maxID = mySMESHDSMesh->MaxShapeIndex();
3930           vector< SMESHDS_SubMesh * > subMeshes( maxID + 1, (SMESHDS_SubMesh*) 0 );
3931           vector< TopAbs_ShapeEnum  > smType   ( maxID + 1, TopAbs_SHAPE ); 
3932
3933           PositionCreator aPositionCreator;
3934
3935           SMDS_NodeIteratorPtr nIt = mySMESHDSMesh->nodesIterator();
3936           SMDS_ElemIteratorPtr eIt = mySMESHDSMesh->elementsIterator();
3937           for ( int isNode = 0; isNode < 2; ++isNode )
3938           {
3939             string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3940             if ( aGroup->ExistInternalObject( (char*) aDSName.c_str() ))
3941             {
3942               aDataset = new HDFdataset( (char*) aDSName.c_str(), aGroup );
3943               aDataset->OpenOnDisk();
3944               // read submesh IDs for all elements sorted by ID
3945               int nbElems = aDataset->GetSize();
3946               int* smIDs = new int [ nbElems ];
3947               aDataset->ReadFromDisk( smIDs );
3948               aDataset->CloseOnDisk();
3949
3950               // get elements sorted by ID
3951               TIDSortedElemSet elemSet;
3952               if ( isNode )
3953                 while ( nIt->more() ) elemSet.insert( nIt->next() );
3954               else
3955                 while ( eIt->more() ) elemSet.insert( eIt->next() );
3956               //ASSERT( elemSet.size() == nbElems ); -- issue 20182
3957               // -- Most probably a bad study was saved when there were
3958               // not fixed bugs in SMDS_MeshInfo
3959               if ( elemSet.size() < nbElems ) {
3960 #ifdef _DEBUG_
3961                 cout << "SMESH_Gen_i::Load(), warning: Node position data is invalid" << endl;
3962 #endif
3963                 nbElems = elemSet.size();
3964               }
3965               // add elements to submeshes
3966               TIDSortedElemSet::iterator iE = elemSet.begin();
3967               for ( int i = 0; i < nbElems; ++i, ++iE )
3968               {
3969                 int smID = smIDs[ i ];
3970                 if ( smID == 0 ) continue;
3971                 const SMDS_MeshElement* elem = *iE;
3972                 if( smID > maxID ) {
3973                   // corresponding subshape no longer exists: maybe geom group has been edited
3974                   if ( myNewMeshImpl->HasShapeToMesh() )
3975                     mySMESHDSMesh->RemoveElement( elem );
3976                   continue;
3977                 }
3978                 // get or create submesh
3979                 SMESHDS_SubMesh* & sm = subMeshes[ smID ];
3980                 if ( ! sm ) {
3981                   sm = mySMESHDSMesh->NewSubMesh( smID );
3982                   smType[ smID ] = mySMESHDSMesh->IndexToShape( smID ).ShapeType();
3983                 }
3984                 // add
3985                 if ( isNode ) {
3986                   SMDS_PositionPtr pos = aPositionCreator.MakePosition( smType[ smID ]);
3987                   pos->SetShapeId( smID );
3988                   SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>( static_cast<const SMDS_MeshNode*>( elem ));
3989                   node->SetPosition( pos );
3990                   sm->AddNode( node );
3991                 } else {
3992                   sm->AddElement( elem );
3993                 }
3994               }
3995               delete [] smIDs;
3996             }
3997           }
3998         } // end reading submeshes
3999
4000         // Read node positions on sub-shapes (SMDS_Position)
4001
4002         if ( aTopGroup->ExistInternalObject( "Node Positions" ))
4003         {
4004           // There are 5 datasets to read:
4005           // "Nodes on Edges" - ID of node on edge
4006           // "Edge positions" - U parameter on node on edge
4007           // "Nodes on Faces" - ID of node on face
4008           // "Face U positions" - U parameter of node on face
4009           // "Face V positions" - V parameter of node on face
4010           const char* aEid_DSName = "Nodes on Edges";
4011           const char* aEu_DSName  = "Edge positions";
4012           const char* aFu_DSName  = "Face U positions";
4013           //char* aFid_DSName = "Nodes on Faces";
4014           //char* aFv_DSName  = "Face V positions";
4015
4016           // data to retrieve
4017           int nbEids = 0, nbFids = 0;
4018           int *aEids = 0, *aFids  = 0;
4019           double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
4020
4021           // open a group
4022           aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
4023           aGroup->OpenOnDisk();
4024
4025           // loop on 5 data sets
4026           int aNbObjects = aGroup->nInternalObjects();
4027           for ( int i = 0; i < aNbObjects; i++ )
4028           {
4029             // identify dataset
4030             char aDSName[ HDF_NAME_MAX_LEN+1 ];
4031             aGroup->InternalObjectIndentify( i, aDSName );
4032             // read data
4033             aDataset = new HDFdataset( aDSName, aGroup );
4034             aDataset->OpenOnDisk();
4035             if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
4036             {
4037               double* pos = new double [ aDataset->GetSize() ];
4038               aDataset->ReadFromDisk( pos );
4039               // which one?
4040               if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
4041                 aEpos = pos;
4042               else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
4043                 aFupos = pos;
4044               else
4045                 aFvpos = pos;
4046             }
4047             else // NODE IDS
4048             {
4049               int aSize = aDataset->GetSize();
4050
4051               // for reading files, created from 18.07.2005 till 10.10.2005
4052               if (aDataset->GetType() == HDF_STRING)
4053                 aSize /= sizeof(int);
4054
4055               int* ids = new int [aSize];
4056               aDataset->ReadFromDisk( ids );
4057               // on face or nodes?
4058               if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
4059                 aEids = ids;
4060                 nbEids = aSize;
4061               }
4062               else {
4063                 aFids = ids;
4064                 nbFids = aSize;
4065               }
4066             }
4067             aDataset->CloseOnDisk();
4068           } // loop on 5 datasets
4069
4070           // Set node positions on edges or faces
4071           for ( int onFace = 0; onFace < 2; onFace++ )
4072           {
4073             int nbNodes = ( onFace ? nbFids : nbEids );
4074             if ( nbNodes == 0 ) continue;
4075             int* aNodeIDs = ( onFace ? aFids : aEids );
4076             double* aUPos = ( onFace ? aFupos : aEpos );
4077             double* aVPos = ( onFace ? aFvpos : 0 );
4078             // loop on node IDs
4079             for ( int iNode = 0; iNode < nbNodes; iNode++ )
4080             {
4081               const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
4082               if ( !node ) continue; // maybe removed while Loading() if geometry changed
4083               SMDS_PositionPtr aPos = node->GetPosition();
4084               ASSERT( aPos );
4085               if ( onFace ) {
4086                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );-- issue 20182
4087                 // -- Most probably a bad study was saved when there were
4088                 // not fixed bugs in SMDS_MeshInfo
4089                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
4090                   SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
4091                     ( static_cast<const SMDS_FacePosition*>( aPos ));
4092                   fPos->SetUParameter( aUPos[ iNode ]);
4093                   fPos->SetVParameter( aVPos[ iNode ]);
4094                 }
4095               }
4096               else {
4097                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );-- issue 20182
4098                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE ) {
4099                   SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
4100                     ( static_cast<const SMDS_EdgePosition*>( aPos ));
4101                   fPos->SetUParameter( aUPos[ iNode ]);
4102                 }
4103               }
4104             }
4105           }
4106           if ( aEids ) delete [] aEids;
4107           if ( aFids ) delete [] aFids;
4108           if ( aEpos ) delete [] aEpos;
4109           if ( aFupos ) delete [] aFupos;
4110           if ( aFvpos ) delete [] aFvpos;
4111
4112           aGroup->CloseOnDisk();
4113
4114         } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
4115       } // if ( hasData )
4116
4117       // Recompute State (as computed sub-meshes are restored from MED)
4118       if ( !aShapeObject->_is_nil() || !myNewMeshImpl->HasShapeToMesh()) {
4119         MESSAGE("Compute State Engine ...");
4120         TopoDS_Shape myLocShape;
4121         if(myNewMeshImpl->HasShapeToMesh())
4122           myLocShape = GeomObjectToShape( aShapeObject );
4123         else
4124           myLocShape = SMESH_Mesh::PseudoShape();
4125         
4126         myNewMeshImpl->GetImpl().GetSubMesh(myLocShape)->ComputeStateEngine
4127           (SMESH_subMesh::SUBMESH_RESTORED);
4128         MESSAGE("Compute State Engine finished");
4129       }
4130
4131       // try to get groups
4132       for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
4133         char name_group[ 30 ];
4134         if ( ii == GetNodeGroupsTag() )
4135           strcpy( name_group, "Groups of Nodes" );
4136         else if ( ii == GetEdgeGroupsTag() )
4137           strcpy( name_group, "Groups of Edges" );
4138         else if ( ii == GetFaceGroupsTag() )
4139           strcpy( name_group, "Groups of Faces" );
4140         else if ( ii == GetVolumeGroupsTag() )
4141           strcpy( name_group, "Groups of Volumes" );
4142
4143         if ( aTopGroup->ExistInternalObject( name_group ) ) {
4144           aGroup = new HDFgroup( name_group, aTopGroup );
4145           aGroup->OpenOnDisk();
4146           // get number of groups
4147           int aNbSubObjects = aGroup->nInternalObjects(); 
4148           for ( int j = 0; j < aNbSubObjects; j++ ) {
4149             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4150             aGroup->InternalObjectIndentify( j, name_dataset );
4151             // check if it is an group
4152             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4153               // --> get group id
4154               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4155               if ( subid <= 0 )
4156                 continue;
4157               aDataset = new HDFdataset( name_dataset, aGroup );
4158               aDataset->OpenOnDisk();
4159
4160               // Retrieve actual group name
4161               size = aDataset->GetSize();
4162               char* nameFromFile = new char[ size ];
4163               aDataset->ReadFromDisk( nameFromFile );
4164               aDataset->CloseOnDisk();
4165
4166               // Try to find a shape reference
4167               TopoDS_Shape aShape;
4168               char aRefName[ 30 ];
4169               sprintf( aRefName, "Ref on shape %d", subid);
4170               if ( aGroup->ExistInternalObject( aRefName ) ) {
4171                 // load mesh "Ref on shape" - it's an entry to SObject
4172                 aDataset = new HDFdataset( aRefName, aGroup );
4173                 aDataset->OpenOnDisk();
4174                 size = aDataset->GetSize();
4175                 char* refFromFile = new char[ size ];
4176                 aDataset->ReadFromDisk( refFromFile );
4177                 aDataset->CloseOnDisk();
4178                 if ( strlen( refFromFile ) > 0 ) {
4179                   SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4180                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4181                   if ( !CORBA::is_nil( shapeObject ) ) {
4182                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4183                     if ( !aShapeObject->_is_nil() )
4184                       aShape = GeomObjectToShape( aShapeObject );
4185                   }
4186                 }
4187               }
4188               // Create group servant
4189               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4190               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4191                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
4192               // Obtain a SMESHDS_Group object 
4193               if ( aNewGroup->_is_nil() )
4194                 continue;
4195
4196               string iorSubString = GetORB()->object_to_string( aNewGroup );
4197               int newSubId = myStudyContext->findId( iorSubString );
4198               myStudyContext->mapOldToNew( subid, newSubId );
4199
4200               SMESH_GroupBase_i* aGroupImpl =
4201                 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
4202               if ( !aGroupImpl )
4203                 continue;
4204
4205               SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
4206               if ( !aLocalGroup )
4207                 continue;
4208
4209               SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
4210               aGroupBaseDS->SetStoreName( name_dataset );
4211
4212               // ouv : NPAL12872
4213               // Read color of the group
4214               char aGroupColorName[ 30 ];
4215               sprintf( aGroupColorName, "ColorGroup %d", subid);
4216               if ( aGroup->ExistInternalObject( aGroupColorName ) )
4217               {
4218                 aDataset = new HDFdataset( aGroupColorName, aGroup );
4219                 aDataset->OpenOnDisk();
4220                 size = aDataset->GetSize();
4221                 double* anRGB = new double[ size ];
4222                 aDataset->ReadFromDisk( anRGB );
4223                 aDataset->CloseOnDisk();
4224                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4225                 aGroupBaseDS->SetColor( aColor );
4226               }
4227
4228               // Fill group with contents from MED file
4229               SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
4230               if ( aGrp )
4231                 myReader.GetGroup( aGrp );
4232             }
4233           }
4234           aGroup->CloseOnDisk();
4235         }
4236       }
4237       // read submeh order if any
4238       if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4239         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4240         aDataset->OpenOnDisk();
4241         size = aDataset->GetSize();
4242         int* smIDs = new int[ size ];
4243         aDataset->ReadFromDisk( smIDs );
4244         aDataset->CloseOnDisk();
4245         TListOfListOfInt anOrderIds;
4246         anOrderIds.push_back( TListOfInt() );
4247         for ( int i = 0; i < size; i++ )
4248           if ( smIDs[ i ] < 0 ) // is separator
4249             anOrderIds.push_back( TListOfInt() );
4250           else
4251             anOrderIds.back().push_back(smIDs[ i ]);
4252         
4253         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4254       }
4255     }
4256     // close mesh group
4257     if(aTopGroup)
4258       aTopGroup->CloseOnDisk();   
4259   }
4260   // close HDF file
4261   aFile->CloseOnDisk();
4262   delete aFile;
4263
4264   // Remove temporary files created from the stream
4265   if ( !isMultiFile ) 
4266     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4267
4268   INFOS( "SMESH_Gen_i::Load completed" );
4269   return true;
4270 }
4271
4272 //=============================================================================
4273 /*!
4274  *  SMESH_Gen_i::LoadASCII
4275  *
4276  *  Load SMESH module's data in ASCII format
4277  */
4278 //=============================================================================
4279
4280 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4281                              const SALOMEDS::TMPFile& theStream,
4282                              const char*              theURL,
4283                              bool                     isMultiFile ) {
4284   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4285   return Load( theComponent, theStream, theURL, isMultiFile );
4286
4287   //before call main ::Load method it's need for decipher text format to
4288   //binary ( "|xx" => x' )
4289   int size = theStream.length();
4290   if ( int((size / 3 )*3) != size ) //error size of buffer
4291     return false;
4292
4293   int real_size = int(size / 3);
4294
4295   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4296   char tmp[3];
4297   tmp[2]='\0';
4298   int c = -1;
4299   for ( int i = 0; i < real_size; i++ )
4300   {
4301     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4302     sscanf( tmp, "%x", &c );
4303     sprintf( (char*)&(buffer[i]), "%c", (char)c );
4304   }
4305
4306   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4307   
4308   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4309 }
4310
4311 //=============================================================================
4312 /*!
4313  *  SMESH_Gen_i::Close
4314  *
4315  *  Clears study-connected data when it is closed
4316  */
4317 //=============================================================================
4318
4319 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4320 {
4321   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4322
4323   // set correct current study
4324   if (theComponent->GetStudy()->StudyId() != GetCurrentStudyID())
4325     SetCurrentStudy(theComponent->GetStudy());
4326
4327   // Clear study contexts data
4328   int studyId = GetCurrentStudyID();
4329   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4330     delete myStudyContextMap[ studyId ];
4331     myStudyContextMap.erase( studyId );
4332   }
4333
4334   // delete SMESH_Mesh's
4335 //   See bug IPAL19437.
4336 //
4337 //   StudyContextStruct* context = myGen.GetStudyContext( studyId );
4338 //   map< int, SMESH_Mesh* >::iterator i_mesh = context->mapMesh.begin();
4339 //   for ( ; i_mesh != context->mapMesh.end(); ++i_mesh ) {
4340 //     printf( "--------------------------- SMESH_Gen_i::Close, delete aGroup = %p \n", i_mesh->second );
4341 //     delete i_mesh->second;
4342 //   }
4343   
4344
4345   // delete SMESHDS_Mesh's
4346   // it's too long on big meshes
4347 //   if ( context->myDocument ) {
4348 //     delete context->myDocument;
4349 //     context->myDocument = 0;
4350 //   }
4351   
4352   myCurrentStudy = SALOMEDS::Study::_nil();
4353   return;
4354 }
4355
4356 //=============================================================================
4357 /*!
4358  *  SMESH_Gen_i::ComponentDataType
4359  * 
4360  *  Get component data type
4361  */
4362 //=============================================================================
4363
4364 char* SMESH_Gen_i::ComponentDataType()
4365 {
4366   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4367   return CORBA::string_dup( "SMESH" );
4368 }
4369
4370     
4371 //=============================================================================
4372 /*!
4373  *  SMESH_Gen_i::IORToLocalPersistentID
4374  *  
4375  *  Transform data from transient form to persistent
4376  */
4377 //=============================================================================
4378
4379 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4380                                            const char*           IORString,
4381                                            CORBA::Boolean        /*isMultiFile*/,
4382                                            CORBA::Boolean        /*isASCII*/ )
4383 {
4384   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4385   StudyContext* myStudyContext = GetCurrentStudyContext();
4386   
4387   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4388     int anId = myStudyContext->findId( IORString );
4389     if ( anId ) {
4390       if(MYDEBUG) MESSAGE( "VSR " << anId )
4391       char strId[ 20 ];
4392       sprintf( strId, "%d", anId );
4393       return  CORBA::string_dup( strId );
4394     }
4395   }
4396   return CORBA::string_dup( "" );
4397 }
4398
4399 //=============================================================================
4400 /*!
4401  *  SMESH_Gen_i::LocalPersistentIDToIOR
4402  *
4403  *  Transform data from persistent form to transient
4404  */
4405 //=============================================================================
4406
4407 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4408                                            const char*           aLocalPersistentID,
4409                                            CORBA::Boolean        /*isMultiFile*/,
4410                                            CORBA::Boolean        /*isASCII*/ )
4411 {
4412   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4413   StudyContext* myStudyContext = GetCurrentStudyContext();
4414
4415   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4416     int anId = atoi( aLocalPersistentID );
4417     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4418   }
4419   return CORBA::string_dup( "" );
4420 }
4421
4422 //=======================================================================
4423 //function : RegisterObject
4424 //purpose  : 
4425 //=======================================================================
4426
4427 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4428 {
4429   StudyContext* myStudyContext = GetCurrentStudyContext();
4430   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4431     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4432     return myStudyContext->addObject( string( iorString.in() ) );
4433   }
4434   return 0;
4435 }
4436
4437 //================================================================================
4438 /*!
4439  * \brief Return id of registered object
4440   * \param theObject - the Object
4441   * \retval int - Object id
4442  */
4443 //================================================================================
4444
4445 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
4446 {
4447   StudyContext* myStudyContext = GetCurrentStudyContext();
4448   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4449     string iorString = GetORB()->object_to_string( theObject );
4450     return myStudyContext->findId( iorString );
4451   }
4452   return 0;
4453 }
4454
4455 //=============================================================================
4456 /*!
4457  *  SMESH_Gen_i::SetName
4458  *
4459  *  Set a new object name
4460  */
4461 //=============================================================================
4462 void SMESH_Gen_i::SetName(const char* theIOR,
4463                           const char* theName)
4464 {
4465   if ( theIOR && strcmp( theIOR, "" ) ) {
4466     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
4467     SALOMEDS::SObject_var aSO = ObjectToSObject( myCurrentStudy, anObject );
4468     if ( !aSO->_is_nil() ) {
4469       SetName( aSO, theName );
4470     }
4471   }
4472 }
4473
4474 int SMESH_Gen_i::GetCurrentStudyID()
4475 {
4476   return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
4477 }
4478     
4479 //=============================================================================
4480 /*! 
4481  *  SMESHEngine_factory
4482  *
4483  *  C factory, accessible with dlsym, after dlopen  
4484  */
4485 //=============================================================================
4486
4487 extern "C"
4488 { SMESH_I_EXPORT
4489   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
4490                                                  PortableServer::POA_ptr   poa, 
4491                                                  PortableServer::ObjectId* contId,
4492                                                  const char*               instanceName, 
4493                                                  const char*               interfaceName )
4494   {
4495     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
4496     if(MYDEBUG) SCRUTE(interfaceName);
4497     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
4498     return aSMESHGen->getId() ;
4499   }
4500 }