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