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