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