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