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