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