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