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