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