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