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