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