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