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