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