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