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