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