Salome HOME
Copyright update 2021
[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::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2319                                          GEOM::GEOM_Object_ptr theShapeObject)
2320 //                                     SMESH::long_array& theNbElems)
2321 {
2322   Unexpect aCatch(SALOME_SalomeException);
2323   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2324
2325   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2326     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2327
2328   if ( CORBA::is_nil( theMesh ) )
2329     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2330
2331   SMESH::long_array_var nbels = new SMESH::long_array;
2332   nbels->length(SMESH::Entity_Last);
2333   int i = SMESH::Entity_Node;
2334   for (; i < SMESH::Entity_Last; i++)
2335     nbels[i] = 0;
2336
2337   // Update Python script
2338   TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2339                 << theMesh << ", " << theShapeObject << ")";
2340
2341   try {
2342     // get mesh servant
2343     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2344     ASSERT( meshServant );
2345     if ( meshServant ) {
2346       meshServant->Load();
2347       // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2348       meshServant->CheckGeomModif();
2349       // get local TopoDS_Shape
2350       TopoDS_Shape myLocShape;
2351       if(theMesh->HasShapeToMesh())
2352         myLocShape = GeomObjectToShape( theShapeObject );
2353       else
2354         myLocShape = SMESH_Mesh::PseudoShape();
2355       // call implementation compute
2356       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2357       MapShapeNbElems aResMap;
2358       /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2359       MapShapeNbElemsItr anIt = aResMap.begin();
2360       for(; anIt!=aResMap.end(); anIt++) {
2361         const vector<int>& aVec = (*anIt).second;
2362         for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2363           int nbElem = aVec[i];
2364           if ( nbElem < 0 ) // algo failed, check that it has reported a message
2365           {
2366             SMESH_subMesh*            sm = anIt->first;
2367             SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2368             const SMESH_Algo*       algo = sm->GetAlgo();
2369             if ( (algo && !error.get()) || error->IsOK() )
2370               error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2371           }
2372           else
2373           {
2374             nbels[i] += aVec[i];
2375           }
2376         }
2377       }
2378       return nbels._retn();
2379     }
2380   }
2381   catch ( std::bad_alloc& ) {
2382     INFOS( "Evaluate(): lack of memory" );
2383   }
2384   catch ( SALOME_Exception& S_ex ) {
2385     INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2386   }
2387   catch ( ... ) {
2388     INFOS( "Evaluate(): unknown exception " );
2389   }
2390
2391   return nbels._retn();
2392 }
2393
2394 //================================================================================
2395 /*!
2396  * \brief Return geometrical object the given element is built on
2397  *  \param theMesh - the mesh the element is in
2398  *  \param theElementID - the element ID
2399  *  \param theGeomName - the name of the result geom object if it is not yet published
2400  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2401  */
2402 //================================================================================
2403
2404 GEOM::GEOM_Object_ptr
2405 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
2406                                        CORBA::Long            theElementID,
2407                                        const char*            theGeomName)
2408 {
2409   Unexpect aCatch(SALOME_SalomeException);
2410
2411   GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2412   if ( !geom->_is_nil() ) {
2413     GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2414     GEOM::GEOM_Gen_var    geomGen   = GetGeomEngine( geom );
2415
2416     // try to find the corresponding SObject
2417     SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2418     if ( SObj->_is_nil() ) // submesh can be not found even if published
2419     {
2420       // try to find published submesh
2421       GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2422       if ( !geom->IsMainShape() && list->length() == 1 ) {
2423         SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2424         SALOMEDS::ChildIterator_wrap it;
2425         if ( !mainSO->_is_nil() ) {
2426           it = getStudyServant()->NewChildIterator( mainSO );
2427         }
2428         if ( !it->_is_nil() ) {
2429           for ( it->InitEx(true); it->More(); it->Next() ) {
2430             SALOMEDS::SObject_wrap      so = it->Value();
2431             CORBA::Object_var         obj = SObjectToObject( so );
2432             GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2433             if ( !subGeom->_is_nil() ) {
2434               GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2435               if ( subList->length() == 1 && list[0] == subList[0] ) {
2436                 SObj = so;
2437                 geom = subGeom;
2438                 break;
2439               }
2440             }
2441           }
2442         }
2443       }
2444     }
2445     if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2446       SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2447
2448     // return only published geometry
2449     if ( !SObj->_is_nil() ) {
2450       //return geom._retn(); -- servant of geom must be UnRegister()ed;
2451       CORBA::Object_var    obj = SObjectToObject( SObj );
2452       GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2453       return go._retn();
2454     }
2455   }
2456   return GEOM::GEOM_Object::_nil();
2457 }
2458
2459 //================================================================================
2460 /*!
2461  * \brief Return geometrical object the given element is built on.
2462  *  \param theMesh - the mesh the element is in
2463  *  \param theElementID - the element ID
2464  *  \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2465  */
2466 //================================================================================
2467
2468 GEOM::GEOM_Object_ptr
2469 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
2470                                         CORBA::Long            theElementID)
2471 {
2472   Unexpect aCatch(SALOME_SalomeException);
2473   if ( CORBA::is_nil( theMesh ) )
2474     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2475
2476   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2477   GEOM::GEOM_Gen_var    geomGen   = GetGeomEngine( mainShape );
2478
2479   // get a core mesh DS
2480   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2481   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2482   {
2483     ::SMESH_Mesh & mesh = meshServant->GetImpl();
2484     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2485     // find the element in mesh
2486     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2487       // find a shape id by the element
2488       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2489         // get a geom object by the shape id
2490         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2491         if ( geom->_is_nil() ) {
2492           // try to find a published sub-shape
2493           SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2494           SALOMEDS::ChildIterator_wrap it;
2495           if ( !mainSO->_is_nil() ) {
2496             it = getStudyServant()->NewChildIterator( mainSO );
2497           }
2498           if ( !it->_is_nil() ) {
2499             for ( it->InitEx(true); it->More(); it->Next() ) {
2500               SALOMEDS::SObject_wrap     so = it->Value();
2501               CORBA::Object_var         obj = SObjectToObject( so );
2502               GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2503               if ( !subGeom->_is_nil() ) {
2504                 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2505                 if ( subList->length() == 1 && shapeID == subList[0] ) {
2506                   geom = subGeom;
2507                   break;
2508                 }
2509               }
2510             }
2511           }
2512         }
2513         if ( geom->_is_nil() ) {
2514           // explode
2515           GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2516           if ( !op->_is_nil() )
2517             geom = op->GetSubShape( mainShape, shapeID );
2518         }
2519         else {
2520           geom->Register();
2521         }
2522         if ( !geom->_is_nil() ) {
2523           GeomObjectToShape( geom ); // let geom client remember the found shape
2524           return geom._retn();
2525         }
2526       }
2527     }
2528   }
2529   return GEOM::GEOM_Object::_nil();
2530 }
2531
2532 //================================================================================
2533 /*!
2534  *  SMESH_Gen_i::Concatenate
2535  *
2536  *  Concatenate the given meshes into one mesh
2537  */
2538 //================================================================================
2539
2540 SMESH::SMESH_Mesh_ptr
2541 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2542                          CORBA::Boolean                theUniteIdenticalGroups,
2543                          CORBA::Boolean                theMergeNodesAndElements,
2544                          CORBA::Double                 theMergeTolerance,
2545                          SMESH::SMESH_Mesh_ptr         theMeshToAppendTo)
2546 {
2547   return ConcatenateCommon(theMeshesArray,
2548                            theUniteIdenticalGroups,
2549                            theMergeNodesAndElements,
2550                            theMergeTolerance,
2551                            false,
2552                            theMeshToAppendTo);
2553 }
2554
2555 //================================================================================
2556 /*!
2557  *  SMESH_Gen_i::ConcatenateWithGroups
2558  *
2559  *  Concatenate the given meshes into one mesh
2560  *  Create the groups of all elements from initial meshes
2561  */
2562 //================================================================================
2563
2564 SMESH::SMESH_Mesh_ptr
2565 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2566                                    CORBA::Boolean                theUniteIdenticalGroups,
2567                                    CORBA::Boolean                theMergeNodesAndElements,
2568                                    CORBA::Double                 theMergeTolerance,
2569                                    SMESH::SMESH_Mesh_ptr         theMeshToAppendTo)
2570 {
2571   return ConcatenateCommon(theMeshesArray,
2572                            theUniteIdenticalGroups,
2573                            theMergeNodesAndElements,
2574                            theMergeTolerance,
2575                            true,
2576                            theMeshToAppendTo);
2577 }
2578
2579 //================================================================================
2580 /*!
2581  *  SMESH_Gen_i::ConcatenateCommon
2582  *
2583  *  Concatenate the given meshes into one mesh
2584  */
2585 //================================================================================
2586
2587 SMESH::SMESH_Mesh_ptr
2588 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2589                                CORBA::Boolean                theUniteIdenticalGroups,
2590                                CORBA::Boolean                theMergeNodesAndElements,
2591                                CORBA::Double                 theMergeTolerance,
2592                                CORBA::Boolean                theCommonGroups,
2593                                SMESH::SMESH_Mesh_ptr         theMeshToAppendTo)
2594 {
2595   std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2596   TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2597
2598   // create mesh if theMeshToAppendTo not provided
2599   SMESH::SMESH_Mesh_var newMesh;
2600   if ( CORBA::is_nil( theMeshToAppendTo ))
2601     newMesh = CreateEmptyMesh();
2602   else
2603     newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2604   SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2605   if ( !newImpl ) return newMesh._retn();
2606   newImpl->Load();
2607
2608   ::SMESH_Mesh&   locMesh = newImpl->GetImpl();
2609   SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2610
2611   typedef std::list<SMESH::SMESH_Group_var>          TListOfNewGroups;
2612   typedef std::pair<string, SMESH::ElementType >     TNameAndType;
2613   typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2614   TGroupsMap       groupsMap;
2615   TListOfNewGroups listOfNewGroups;
2616
2617   if ( !CORBA::is_nil( theMeshToAppendTo ))
2618   {
2619     // fill groupsMap with existing groups
2620     SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2621     for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2622     {
2623       SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2624       if ( !group->_is_nil() )
2625       {
2626         CORBA::String_var  name = group->GetName();
2627         SMESH::ElementType type = group->GetType();
2628         groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2629       }
2630     }
2631   }
2632
2633   ::SMESH_MeshEditor               newEditor( &locMesh );
2634   ::SMESH_MeshEditor::ElemFeatures elemType;
2635
2636   // loop on sub-meshes
2637   for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2638   {
2639     if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2640     SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2641     SMESH_Mesh_i*         initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2642     if ( !initImpl ) continue;
2643     if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2644       continue;
2645     initImpl->Load();
2646
2647     // assure that IDs increment by one during iteration
2648     ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2649     SMESHDS_Mesh*  initMeshDS = initLocMesh.GetMeshDS();
2650     if ( initMeshDS->MaxNodeID()    > initMeshDS->NbNodes() ||
2651          initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2652     {
2653       initMeshDS->Modified();
2654       initMeshDS->CompactMesh();
2655     }
2656
2657     // remember nb of elements before filling in
2658     SMESH::long_array_var prevState =  newMesh->GetNbElementsByType();
2659
2660     // copy nodes
2661
2662     std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2663     SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2664     while ( elemIt->more() )
2665     {
2666       SMESH_NodeXYZ node = elemIt->next();
2667       newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2668     }
2669
2670     // copy elements
2671
2672     SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2673     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2674       continue;
2675     std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2676     elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2677     while ( elemIt->more() )
2678     {
2679       const SMDS_MeshElement* elem = elemIt->next();
2680       elemType.myNodes.resize( elem->NbNodes() );
2681
2682       SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2683       for ( int k = 0; itNodes->more(); k++)
2684       {
2685         const SMDS_MeshNode* node = itNodes->next();
2686         elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2687       }
2688
2689       // creates a corresponding element on existent nodes in new mesh
2690       newElems[ elem->GetID() ] =
2691         newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2692     }
2693     newEditor.ClearLastCreated(); // forget the history
2694
2695
2696     // create groups of just added elements
2697     SMESH::SMESH_Group_var newGroup;
2698     SMESH::ElementType     groupType;
2699     if ( theCommonGroups )
2700     {
2701       // type names
2702       const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2703       { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2704         const int nbNames = sizeof(typeNames) / sizeof(const char*);
2705         int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2706       }
2707
2708       SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2709
2710       for( groupType = SMESH::NODE;
2711            groupType < SMESH::NB_ELEMENT_TYPES;
2712            groupType = (SMESH::ElementType)( groupType + 1 ))
2713       {
2714         if ( curState[ groupType ] <= prevState[ groupType ])
2715           continue; // no elements of groupType added from the i-th mesh
2716
2717         // make a group name
2718         std::string groupName = "Gr";
2719         SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2720         if ( meshSO ) {
2721           CORBA::String_var name = meshSO->GetName();
2722           groupName += name;
2723         }
2724         groupName += "_";
2725         groupName += typeNames[ groupType ];
2726
2727         // make and fill a group
2728         newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2729         std::vector< const SMDS_MeshElement* > & elemVec =
2730           ( groupType == SMESH::NODE ) ? newNodes : newElems;
2731         if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2732         {
2733           if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2734           {
2735             for ( size_t j = 0; j < elemVec.size(); ++j )
2736             {
2737               if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2738                 grpDS->Add( elemVec[j] );
2739             }
2740           }
2741         }
2742         listOfNewGroups.clear();
2743         listOfNewGroups.push_back( newGroup );
2744         groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2745                                           listOfNewGroups ));
2746       }
2747     }
2748
2749     if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2750     {
2751       // copy groups
2752
2753       SMESH::SMESH_GroupBase_ptr group;
2754       CORBA::String_var          groupName;
2755       SMESH::long_array_var newIDs = new SMESH::long_array();
2756
2757       // loop on groups of a source mesh
2758       SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2759       for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2760       {
2761         group     = listOfGroups[iG];
2762         groupType = group->GetType();
2763         groupName = group->GetName();
2764         std::string name = groupName.in();
2765
2766         // convert a list of IDs
2767         newIDs->length( group->Size() );
2768         std::vector< const SMDS_MeshElement* > & elemVec =
2769           ( groupType == SMESH::NODE ) ? newNodes : newElems;
2770         SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2771         int nbElems = 0;
2772         while ( itGrElems->more() )
2773         {
2774           const SMDS_MeshElement*    elem = itGrElems->next();
2775           const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2776           if ( newElem )
2777             newIDs[ nbElems++ ] = newElem->GetID();
2778         }
2779         newIDs->length( nbElems );
2780
2781         // check that a current group name and type don't have identical ones in final mesh
2782         listOfNewGroups.clear();
2783         TNameAndType nameAndType( name, groupType );
2784         TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2785         if ( anIter == groupsMap.end() )
2786         {
2787           // add a new group in the mesh
2788           newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2789           newGroup->Add( newIDs );
2790
2791           listOfNewGroups.push_back( newGroup );
2792           groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2793         }
2794         else if ( theUniteIdenticalGroups )
2795         {
2796           // unite identical groups
2797           TListOfNewGroups& aNewGroups = anIter->second;
2798           aNewGroups.front()->Add( newIDs );
2799         }
2800         else
2801         {
2802           // rename identical groups
2803           newGroup = newImpl->CreateGroup( groupType, groupName );
2804           newGroup->Add( newIDs );
2805
2806           TListOfNewGroups& newGroups = anIter->second;
2807           std::string newGroupName;
2808           if ( newGroups.size() == 1 )
2809           {
2810             newGroupName = name + "_1";
2811             newGroups.front()->SetName( newGroupName.c_str() );
2812           }
2813           newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2814           newGroup->SetName( newGroupName.c_str() );
2815           newGroups.push_back( newGroup );
2816         }
2817       } // loop on groups
2818     } // if an IDSource is a mesh
2819   } //meshes loop
2820
2821   if ( theMergeNodesAndElements ) // merge nodes
2822   {
2823     TIDSortedNodeSet meshNodes; // no input nodes == treat all
2824     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2825     newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2826                                    /*SeparateCornersAndMedium=*/ false );
2827     newEditor.MergeNodes( groupsOfNodes );
2828     // merge elements
2829     newEditor.MergeEqualElements();
2830   }
2831
2832   // Update Python script
2833   pythonDump << newMesh << " = " << this
2834              << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2835              << theMeshesArray << ", "
2836              << theUniteIdenticalGroups << ", "
2837              << theMergeNodesAndElements << ", "
2838              << TVar( theMergeTolerance ) << ", "
2839              << theMeshToAppendTo << " )";
2840
2841   pPythonDump.reset(); // enable python dump from GetGroups()
2842
2843   // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2844   if ( !newMesh->_is_nil() )
2845   {
2846     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2847   }
2848
2849   // IPAL21468 Change icon of compound because it need not be computed.
2850   SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2851   SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2852
2853   newMeshDS->Modified();
2854
2855   return newMesh._retn();
2856 }
2857
2858 //================================================================================
2859 /*!
2860  * \brief Create a mesh by copying a part of another mesh
2861  *  \param meshPart - a part of mesh to copy
2862  *  \param toCopyGroups - to create in the new mesh groups
2863  *                        the copied elements belongs to
2864  *  \param toKeepIDs - to preserve IDs of the copied elements or not
2865  *  \retval SMESH::SMESH_Mesh_ptr - the new mesh
2866  */
2867 //================================================================================
2868
2869 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2870                                             const char*               meshName,
2871                                             CORBA::Boolean            toCopyGroups,
2872                                             CORBA::Boolean            toKeepIDs)
2873 {
2874   Unexpect aCatch(SALOME_SalomeException);
2875
2876   TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2877   std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2878
2879   // 1. Get source mesh
2880
2881   if ( CORBA::is_nil( meshPart ))
2882     THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2883
2884   SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2885   SMESH_Mesh_i*       srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2886   if ( !srcMesh_i )
2887     THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2888
2889   SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2890
2891   // 2. Make a new mesh
2892
2893   SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2894   SMESH_Mesh_i*       newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2895   if ( !newMesh_i )
2896     THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2897   SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2898   if ( !meshSO->_is_nil() )
2899   {
2900     SetName( meshSO, meshName, "Mesh" );
2901     SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2902   }
2903   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2904   ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2905   ::SMESH_MeshEditor::ElemFeatures elemType;
2906
2907   // 3. Get elements to copy
2908
2909   SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2910   TIDSortedElemSet srcElems;
2911   SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2912   if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2913   {
2914     srcMesh_i->Load();
2915     srcElemIt = srcMeshDS->elementsIterator();
2916     srcNodeIt = srcMeshDS->nodesIterator();
2917   }
2918   else
2919   {
2920     SMESH::long_array_var ids = meshPart->GetIDs();
2921     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2922     {
2923       for ( CORBA::ULong i=0; i < ids->length(); i++ )
2924         if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2925           srcElems.insert( elem );
2926     }
2927     else
2928     {
2929       for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2930         if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2931           srcElems.insert( elem );
2932     }
2933     if ( srcElems.empty() )
2934       return newMesh._retn();
2935
2936     typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2937     srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2938   }
2939
2940   // 4. Copy elements
2941
2942   typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2943   TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2944   TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2945   int iN;
2946   const SMDS_MeshNode *nSrc, *nTgt;
2947   vector< const SMDS_MeshNode* > nodes;
2948   while ( srcElemIt->more() )
2949   {
2950     const SMDS_MeshElement * elem = srcElemIt->next();
2951     // find / add nodes
2952     nodes.resize( elem->NbNodes());
2953     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2954     if ( toKeepIDs ) {
2955       for ( iN = 0; nIt->more(); ++iN )
2956       {
2957         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2958         nTgt = newMeshDS->FindNode( nSrc->GetID());
2959         if ( !nTgt )
2960           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2961         nodes[ iN ] = nTgt;
2962       }
2963     }
2964     else {
2965       for ( iN = 0; nIt->more(); ++iN )
2966       {
2967         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2968         TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2969         if ( !n2n->second )
2970           n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2971         nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2972       }
2973     }
2974     // add elements
2975     if ( elem->GetType() != SMDSAbs_Node )
2976     {
2977       elemType.Init( elem, /*basicOnly=*/false );
2978       if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2979
2980       const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2981       if ( toCopyGroups && !toKeepIDs )
2982         e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2983     }
2984   } // while ( srcElemIt->more() )
2985
2986   // 4(b). Copy free nodes
2987
2988   if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2989   {
2990     while ( srcNodeIt->more() )
2991     {
2992       nSrc = srcNodeIt->next();
2993       if ( nSrc->NbInverseElements() == 0 )
2994       {
2995         if ( toKeepIDs )
2996           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2997         else
2998           n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2999       }
3000     }
3001   }
3002
3003   // 5. Copy groups
3004
3005   int nbNewGroups = 0;
3006   if ( toCopyGroups )
3007   {
3008     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3009     while ( gIt->more() )
3010     {
3011       SMESH_Group* group = gIt->next();
3012       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3013
3014       // Check group type. We copy nodal groups containing nodes of copied element
3015       SMDSAbs_ElementType groupType = groupDS->GetType();
3016       if ( groupType != SMDSAbs_Node &&
3017            newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3018         continue; // group type differs from types of meshPart
3019
3020       // Find copied elements in the group
3021       vector< const SMDS_MeshElement* > groupElems;
3022       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3023       if ( toKeepIDs )
3024       {
3025         const SMDS_MeshElement* foundElem;
3026         if ( groupType == SMDSAbs_Node )
3027         {
3028           while ( eIt->more() )
3029             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3030               groupElems.push_back( foundElem );
3031         }
3032         else
3033         {
3034           while ( eIt->more() )
3035             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3036               groupElems.push_back( foundElem );
3037         }
3038       }
3039       else
3040       {
3041         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3042         if ( e2eMap.empty() ) continue;
3043         int minID = e2eMap.begin()->first->GetID();
3044         int maxID = e2eMap.rbegin()->first->GetID();
3045         TE2EMap::iterator e2e;
3046         while ( eIt->more() && groupElems.size() < e2eMap.size())
3047         {
3048           const SMDS_MeshElement* e = eIt->next();
3049           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3050           if ((e2e = e2eMap.find( e )) != e2eMap.end())
3051             groupElems.push_back( e2e->second );
3052         }
3053       }
3054       // Make a new group
3055       if ( !groupElems.empty() )
3056       {
3057         SMESH::SMESH_Group_var newGroupObj =
3058           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3059         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3060         {
3061           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3062           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3063           for ( unsigned i = 0; i < groupElems.size(); ++i )
3064             smdsGroup.Add( groupElems[i] );
3065
3066           nbNewGroups++;
3067         }
3068       }
3069     }
3070   }
3071
3072   newMeshDS->Modified();
3073
3074   *pyDump << newMesh << " = " << this
3075           << ".CopyMesh( " << meshPart << ", "
3076           << "'" << meshName << "', "
3077           << toCopyGroups << ", "
3078           << toKeepIDs << ")";
3079
3080   pyDumpDeleter.reset(); // allow dump in GetGroups()
3081
3082   if ( nbNewGroups > 0 ) // dump created groups
3083     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3084
3085   return newMesh._retn();
3086 }
3087
3088
3089 namespace // utils for CopyMeshWithGeom()
3090 {
3091   typedef std::map< std::string, std::string >             TStr2StrMap;
3092   typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3093   typedef std::map< std::set<int>, int >                   TIdSet2IndexMap;
3094   typedef std::map< std::string, int >                     TName2IndexMap;
3095
3096   //================================================================================
3097   /*!
3098    * \brief Return a new sub-shape corresponding to an old one
3099    */
3100   //================================================================================
3101
3102   struct ShapeMapper
3103   {
3104     SMESH_Mesh_i* mySrcMesh_i;
3105     SMESH_Mesh_i* myNewMesh_i;
3106     SMESH_Gen_i*  myGen_i;
3107     bool          myToPublish;
3108     bool          myIsSameGeom;
3109
3110     TStr2StrMap   myOld2NewEntryMap; // map of study entries
3111
3112     GEOM::ListOfGO_var         mySubshapes; // sub-shapes existing in the new geometry
3113     TIdSet2IndexMap            myIds2SubshapeIndex; // to find an existing sub-shape
3114     TName2IndexMap             myName2SubshapeIndex; // to find an existing sub-shape by name
3115
3116     bool                       myGIPMapDone;
3117     GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3118
3119     // not directly relating to shape search
3120     TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3121
3122     //================================================================================
3123     /*!
3124      * \brief Constructor
3125      */
3126     ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3127                  SMESH_Mesh_i* newMesh_i,
3128                  SMESH_Gen_i*  smeshGen_i )
3129       : mySrcMesh_i( srcMesh_i ),
3130         myNewMesh_i( newMesh_i ),
3131         myGen_i    ( smeshGen_i ),
3132         myToPublish( smeshGen_i->IsEnablePublish() ),
3133         myGIPMapDone( false )
3134     {
3135       // retrieve from the study shape mapping made thanks to
3136       // "Set presentation parameters and sub-shapes from arguments" option
3137
3138       GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3139       GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3140       SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3141       SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3142       if ( newSO->_is_nil() )
3143       {
3144         myToPublish = false;
3145         return;
3146       }
3147       if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3148         return;
3149       CORBA::String_var oldEntry = oldSO->GetID();
3150       CORBA::String_var newEntry = newSO->GetID();
3151       myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3152                                                 std::string( newEntry.in() )));
3153       std::string  newMainEntry = newEntry.in();
3154
3155       SALOMEDS::Study_var            study = myGen_i->getStudyServant();
3156       GEOM::GEOM_Gen_var           geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3157       GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3158       mySubshapes                          = op->GetExistingSubObjects( mainShapeNew,
3159                                                                         /*groupsOnly=*/false );
3160       for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3161       {
3162         newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3163         SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3164         bool refFound = false;
3165         for ( ; anIter->More(); anIter->Next() )
3166         {
3167           SALOMEDS::SObject_wrap so = anIter->Value();
3168           if ( so->ReferencedObject( oldSO.inout() ))
3169           {
3170             oldEntry = oldSO->GetID();
3171             newEntry = newSO->GetID();
3172             if (( refFound = ( newMainEntry != oldEntry.in() )))
3173               myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3174                                                         std::string( newEntry.in() )));
3175           }
3176         }
3177         if ( !refFound )
3178         {
3179           GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3180           if ( father->_is_equivalent( mainShapeNew ))
3181           {
3182             GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3183             std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3184             myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3185             CORBA::String_var name = newSO->GetName();
3186             if ( name.in()[0] )
3187               myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3188           }
3189         }
3190       }
3191     }
3192
3193     //================================================================================
3194     /*!
3195      * \brief Find a new sub-shape corresponding to an old one
3196      */
3197     GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3198     {
3199       if ( myIsSameGeom )
3200         return GEOM::GEOM_Object::_duplicate( oldShape );
3201
3202       GEOM::GEOM_Object_var newShape;
3203
3204       if ( CORBA::is_nil( oldShape ))
3205         return newShape._retn();
3206
3207       if ( !isChildOfOld( oldShape ))
3208         return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3209
3210       GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3211       GEOM::GEOM_Gen_var         geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3212
3213       // try to find by entry or name
3214       if ( myToPublish )
3215       {
3216         CORBA::String_var  oldEntry = oldShape->GetStudyEntry();
3217         TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3218         if ( o2nID != myOld2NewEntryMap.end() )
3219         {
3220           newShape = getShapeByEntry( o2nID->second );
3221         }
3222         if ( newShape->_is_nil() )
3223         {
3224           CORBA::String_var name = oldShape->GetName();
3225           TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3226           if ( n2ind != myName2SubshapeIndex.end() )
3227           {
3228             newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3229             GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3230             GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3231             if ( oldIndices->length() == 0 ||
3232                  newIndices->length() == 0 ||
3233                  getShapeType( myNewMesh_i, newIndices[0] ) !=
3234                  getShapeType( mySrcMesh_i, oldIndices[0] ))
3235               newShape = GEOM::GEOM_Object::_nil();
3236           }
3237         }
3238       }
3239
3240       if ( newShape->_is_nil() )
3241       {
3242         // try to construct a new sub-shape using myGIPMap
3243         buildGIPMap();
3244         std::vector< int >   newIndices;
3245         GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3246         for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3247         {
3248           findNewIDs( oldIndices[i], newIndices );
3249         }
3250         if ( newIndices.size() < oldIndices->length() ) // issue #17096
3251         {
3252           newIndices.clear();
3253           newShape = getInPlace( oldShape );
3254         }
3255         if ( !newIndices.empty() && newShape->_is_nil() )
3256         {
3257           // search for a sub-shape with same ids
3258           std::set< int > idSet( newIndices.begin(), newIndices.end() );
3259           TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3260           if ( ids2ind != myIds2SubshapeIndex.end() ) {
3261             newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3262           }
3263           if ( newShape->_is_nil() )
3264             try
3265             {
3266               // create a new shape
3267               if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3268               {
3269                 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3270
3271                 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3272                 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3273
3274                 GEOM::ListOfLong_var  newIndicesList = new GEOM::ListOfLong();
3275                 newIndicesList->length( newIndices.size() );
3276                 for ( size_t i = 0; i < newIndices.size(); ++i )
3277                   newIndicesList[ i ] = newIndices[ i ];
3278                 grOp->UnionIDs( newShape, newIndicesList );
3279               }
3280               else
3281               {
3282                 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3283                 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3284               }
3285             }
3286             catch (...)
3287             {
3288             }
3289         }
3290       }
3291
3292       if ( !newShape->_is_nil() && myToPublish )
3293       {
3294         CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3295         if ( !newEntry.in() || !newEntry.in()[0] )
3296         {
3297           CORBA::String_var    name = oldShape->GetName();
3298           SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3299           newEntry = newShape->GetStudyEntry();
3300           oldEntry = oldShape->GetStudyEntry();
3301           myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3302                                                     std::string( newEntry.in() )));
3303         }
3304       }
3305
3306       return newShape._retn();
3307     }
3308
3309     //================================================================================
3310     /*!
3311      * \brief Return a study entry of a new shape by study entry of the old one
3312      */
3313     std::string FindNew( const std::string & oldEntry )
3314     {
3315       if ( myIsSameGeom )
3316         return oldEntry;
3317
3318       TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3319       if ( o2nID != myOld2NewEntryMap.end() )
3320         return o2nID->second;
3321
3322       GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3323       if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3324         return oldEntry;
3325
3326       GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3327       if ( newShape->_is_nil() )
3328         return std::string();
3329
3330       CORBA::String_var newEntry = newShape->GetStudyEntry();
3331       return newEntry.in();
3332     }
3333
3334     //================================================================================
3335     /*!
3336      * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3337      *        Return zero if not found or there are more than one new ID
3338      */
3339     int FindNew( int oldID )
3340     {
3341       if ( myIsSameGeom )
3342         return oldID;
3343
3344       buildGIPMap();
3345
3346       int newID = 0;
3347
3348       if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3349       {
3350         if ( myGIPMap[ oldID ].length() == 1 )
3351         {
3352           newID = myGIPMap[ oldID ][ 0 ];
3353         }
3354         else if ( myGIPMap[ oldID ].length() > 1 &&
3355                   getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3356         {
3357           // select a meshed VERTEX
3358           SMESH_subMesh* newSM;
3359           for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3360             if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3361                 ( !newSM->IsEmpty() ))
3362               newID = myGIPMap[ oldID ][ i ];
3363         }
3364       }
3365       return newID;
3366     }
3367
3368     //================================================================================
3369     /*!
3370      * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3371      *        Return zero if the old shape is not kept as is in the new shape.
3372      */
3373     int FindNewNotChanged( SMESH_subMesh* oldSM )
3374     {
3375       if ( myIsSameGeom )
3376         return oldSM->GetId();
3377
3378       int newID = FindNew( oldSM->GetId() );
3379       if ( !newID )
3380         return 0;
3381
3382       SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3383       if ( !newSM )
3384         return 0;
3385
3386       // consider a sub-shape as not changed if all its sub-shapes are mapped into
3387       // one new sub-shape of the same type.
3388
3389       if ( oldSM->DependsOn().size() !=
3390            newSM->DependsOn().size() )
3391         return 0;
3392
3393       SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3394       while ( srcSMIt->more() )
3395       {
3396         oldSM = srcSMIt->next();
3397         int newSubID = FindNew( oldSM->GetId() );
3398         if ( getShapeType( myNewMesh_i, newSubID ) !=
3399              getShapeType( mySrcMesh_i, oldSM->GetId() ))
3400           return 0;
3401       }
3402       return newID;
3403     }
3404
3405     //================================================================================
3406     /*!
3407      * \brief Return shape by study entry
3408      */
3409     GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3410     {
3411       GEOM::GEOM_Object_var shape;
3412       SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3413       if ( !so->_is_nil() )
3414       {
3415         CORBA::Object_var obj = so->GetObject();
3416         shape = GEOM::GEOM_Object::_narrow( obj );
3417       }
3418       return shape._retn();
3419     }
3420
3421     //================================================================================
3422     /*!
3423      * \brief Fill myGIPMap by calling GetInPlaceMap()
3424      */
3425     void buildGIPMap()
3426     {
3427       if ( !myGIPMapDone )
3428       {
3429         myGIPMapDone = true;
3430
3431         GEOM::GEOM_Object_var   mainShapeNew = myNewMesh_i->GetShapeToMesh();
3432         GEOM::GEOM_Object_var   mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3433         GEOM::GEOM_Gen_var           geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3434         GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3435         try
3436         {
3437           myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3438         }
3439         catch( ... )
3440         {
3441           myGIPMap = new GEOM::ListOfListOfLong();
3442         }
3443       }
3444     }
3445
3446     //================================================================================
3447     /*!
3448      * \brief Get new sub-shape by calling GetInPlace()
3449      */
3450     GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3451     {
3452       GEOM::GEOM_Object_var newShape;
3453
3454       GEOM::GEOM_Object_var   mainShapeNew = myNewMesh_i->GetShapeToMesh();
3455       GEOM::GEOM_Gen_var           geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3456       GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3457       try
3458       {
3459         newShape = op->GetInPlace( mainShapeNew, oldShape );
3460       }
3461       catch( ... )
3462       {
3463       }
3464       return newShape._retn();
3465     }
3466
3467     //================================================================================
3468     /*!
3469      * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3470      *        number of found IDs
3471      */
3472     int findNewIDs( int oldID, std::vector< int >& newIDs  )
3473     {
3474       size_t prevNbIDs = newIDs.size();
3475
3476       if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3477       {
3478         for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3479           newIDs.push_back( myGIPMap[ oldID ][ i ]);
3480       }
3481       return newIDs.size() - prevNbIDs;
3482     }
3483
3484     //================================================================================
3485     /*!
3486      * \brief Check if an object relates to the old shape
3487      */
3488     bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3489     {
3490       if ( CORBA::is_nil( oldShape ))
3491         return false;
3492       GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3493       GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3494       return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3495                mainShapeOld1->_is_equivalent( oldShape ));
3496     }
3497
3498     //================================================================================
3499     /*!
3500      * \brief Return shape type by shape ID
3501      */
3502     TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3503     {
3504       SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3505       const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3506       return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3507     }
3508
3509     //================================================================================
3510     /*!
3511      * \brief Store a source sub-shape for which a counterpart not found and
3512      *        a smesh object invalid due to that
3513      */
3514     void AddInvalid( GEOM::GEOM_Object_var  srcShape,
3515                      SALOMEDS::SObject_wrap smeshSO )
3516     {
3517       CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3518       if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3519       {
3520         CORBA::String_var smeshEntry = smeshSO->GetID();
3521         myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3522       }
3523     }
3524
3525     //================================================================================
3526     /*!
3527      * \brief Store a source sub-shape for which a counterpart not found and
3528      *        a smesh object invalid due to that
3529      */
3530     void AddInvalid( std::string            geomEntry,
3531                      SALOMEDS::SObject_wrap smeshSO )
3532     {
3533       if ( !geomEntry.empty() )
3534       {
3535         CORBA::String_var smeshEntry = smeshSO->GetID();
3536         myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3537       }
3538     }
3539
3540     //================================================================================
3541     /*!
3542      * \brief Store a source sub-shape for which a counterpart not found and
3543      *        a smesh object invalid due to that
3544      */
3545     void AddInvalid( int                    oldGeomID,
3546                      SALOMEDS::SObject_wrap smeshSO )
3547     {
3548       int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3549       if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3550         return;
3551
3552       const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3553                                  "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3554
3555       SMESH_Comment geomName( typeName[ shapeType ]);
3556       geomName << " #" << oldGeomID;
3557
3558       CORBA::String_var smeshEntry = smeshSO->GetID();
3559       myInvalidMap[ geomName ].insert( smeshEntry.in() );
3560     }
3561
3562     //================================================================================
3563     /*!
3564      * \brief Return entries of a source sub-shape for which a counterpart not found and
3565      *        of smesh objects invalid due to that
3566      */
3567     void GetInvalid( SMESH::string_array_out &               theInvalidEntries,
3568                      std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3569     {
3570       int nbSO = 0;
3571       TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3572       for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3573       {
3574         nbSO += 1 + entry2entrySet->second.size();
3575       }
3576       int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3577       theInvalidEntries->length  ( nbSO );
3578       theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3579
3580       entry2entrySet = myInvalidMap.begin();
3581       for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3582       {
3583         theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3584
3585         std::set< std::string > & entrySet = entry2entrySet->second;
3586         std::set< std::string >::iterator entry = entrySet.begin();
3587         for ( ; entry != entrySet.end(); ++entry )
3588         {
3589           theInvalidEntries[ iEntry++ ] = entry->c_str();
3590
3591           SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3592           if ( !so->_is_nil() )
3593             theInvalidMeshSObjects[ iSO++ ] = so;
3594         }
3595       }
3596     }
3597
3598   }; // struct ShapeMapper
3599
3600   //================================================================================
3601   /*!
3602    * \brief Append an item to a CORBA sequence
3603    */
3604   template < class CORBA_seq, class ITEM >
3605   void append( CORBA_seq& seq, ITEM item )
3606   {
3607     if ( !CORBA::is_nil( item ))
3608     {
3609       seq->length( 1 + seq->length() );
3610       seq[ seq->length() - 1 ] = item;
3611     }
3612   }
3613 } // namespace // utils for CopyMeshWithGeom()
3614
3615 //================================================================================
3616 /*!
3617  * \brief Create a mesh by copying definitions of another mesh to a given geometry
3618  *  \param [in] sourceMesh - a mesh to copy
3619  *  \param [in] newGeometry - a new geometry
3620  *  \param [in] toCopyGroups - to create groups in the new mesh
3621  *  \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3622  *         otherwise new hypotheses with the same parameters will be created for the new mesh.
3623  *  \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3624  *  \param [out] newMesh - return a new mesh
3625  *  \param [out] newGroups - return new groups
3626  *  \param [out] newSubmeshes - return new sub-meshes
3627  *  \param [out] newHypotheses - return new algorithms and hypotheses
3628  *  \param [out] invalidEntries - return study entries of objects whose
3629  *         counterparts are not found in the newGeometry, followed by entries
3630  *         of mesh sub-objects that are invalid because they depend on a not found
3631  *         preceding sub-shape
3632  *  \return CORBA::Boolean - is a success
3633  */
3634 //================================================================================
3635
3636 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr       theSourceMesh,
3637                                               GEOM::GEOM_Object_ptr       theNewGeometry,
3638                                               const char*                 theMeshName,
3639                                               CORBA::Boolean              theToCopyGroups,
3640                                               CORBA::Boolean              theToReuseHypotheses,
3641                                               CORBA::Boolean              theToCopyElements,
3642                                               SMESH::SMESH_Mesh_out       theNewMesh,
3643                                               SMESH::ListOfGroups_out     theNewGroups,
3644                                               SMESH::submesh_array_out    theNewSubmeshes,
3645                                               SMESH::ListOfHypothesis_out theNewHypotheses,
3646                                               SMESH::string_array_out     theInvalidEntries)
3647 {
3648   if ( CORBA::is_nil( theSourceMesh ) ||
3649        CORBA::is_nil( theNewGeometry ))
3650     THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3651
3652   if ( !theSourceMesh->HasShapeToMesh() )
3653     THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3654
3655   bool ok = true;
3656   SMESH_TRY;
3657
3658   TPythonDump pyDump(this); // prevent dump from CreateMesh()
3659
3660   theNewMesh        = CreateMesh( theNewGeometry );
3661   theNewGroups      = new SMESH::ListOfGroups();
3662   theNewSubmeshes   = new SMESH::submesh_array();
3663   theNewHypotheses  = new SMESH::ListOfHypothesis();
3664   theInvalidEntries = new SMESH::string_array();
3665
3666   std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3667
3668   GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3669   GEOM::GEOM_Object_var geom, newGeom;
3670   SALOMEDS::SObject_wrap so;
3671
3672   SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3673   SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3674   srcMesh_i->Load();
3675
3676   ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3677
3678   // treat hypotheses of mesh and sub-meshes
3679   SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3680   for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3681   {
3682     bool isSubMesh = ( iSM < smList->length() );
3683     if ( isSubMesh )
3684     {
3685       // create a new sub-mesh
3686       SMESH::SMESH_subMesh_var newSM;
3687       geom = smList[iSM]->GetSubShape();
3688       so   = ObjectToSObject( smList[iSM] );
3689       CORBA::String_var name;
3690       if ( !so->_is_nil() )
3691         name = so->GetName();
3692       newGeom = shapeMapper.FindNew( geom );
3693       if ( newGeom->_is_nil() )
3694       {
3695         newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3696         shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3697         ok = false;
3698       }
3699       else
3700       {
3701         newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3702       }
3703       append( theNewSubmeshes, newSM );
3704
3705       if ( newGeom->_is_nil() )
3706         continue; // don't assign hypotheses
3707     }
3708     else
3709     {
3710       newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3711       geom    = srcGeom;
3712       so      = ObjectToSObject( theNewMesh );
3713       SetName( so, theMeshName, "Mesh" );
3714     }
3715
3716     // assign hypotheses
3717     SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3718     for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3719     {
3720       SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3721       SMESH_Hypothesis_i*       hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3722
3723       // get geometry hyp depends on
3724       std::vector< std::string > entryArray;
3725       std::vector< int >         subIDArray;
3726       bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3727
3728       if ( !theToReuseHypotheses || dependsOnGeom )
3729       {
3730         // create a new hypothesis
3731         CORBA::String_var type = hyp->GetName();
3732         CORBA::String_var lib  = hyp->GetLibName();
3733         CORBA::String_var data = hyp_i->SaveTo();
3734         if ( data.in()[0] )
3735         {
3736           hyp   = CreateHypothesis( type, lib );
3737           hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3738           hyp_i->LoadFrom( data.in() );
3739           append( theNewHypotheses, hyp );
3740         }
3741       }
3742
3743       // update geometry hyp depends on
3744       if ( dependsOnGeom )
3745       {
3746         for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3747         {
3748           if ( !entryArray[ iGeo ].empty() )
3749           {
3750             std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3751             if ( newEntry.empty() )
3752             {
3753               ok = false;
3754               shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3755               shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3756             }
3757             entryArray[ iGeo ] = newEntry;
3758           }
3759         }
3760         for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3761         {
3762           if ( subIDArray[ iGeo ] > 0 )
3763           {
3764             int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3765             if ( newID < 1 )
3766             {
3767               ok = false;
3768               shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3769               shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3770             }
3771             subIDArray[ iGeo ] = newID;
3772           }
3773         }
3774         if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3775           ok = false;
3776       }
3777
3778       CORBA::String_var errorText;
3779       theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3780       if ( errorText.in()[0] )
3781         ok = false;
3782
3783     } // loop on hypotheses
3784   } // loop on sub-meshes and mesh
3785
3786
3787   // copy mesh elements, keeping IDs
3788   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3789   if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3790   {
3791     ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3792     ::SMESH_MeshEditor::ElemFeatures elemData;
3793
3794     SMESH_subMesh*         srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3795     SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3796                                                                         /*vertexLast=*/false);
3797     while ( srcSMIt->more() )
3798     {
3799       SMESH_subMesh* srcSM = srcSMIt->next();
3800       if ( srcSM->IsEmpty() )
3801         continue; // not yet computed
3802       int newID = shapeMapper.FindNewNotChanged( srcSM );
3803       if ( newID < 1 )
3804         continue;
3805
3806       SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3807       SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3808       while ( nIt->more() )
3809       {
3810         SMESH_NodeXYZ node( nIt->next() );
3811         const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3812                                                                  node->GetID() );
3813         const SMDS_PositionPtr pos = node->GetPosition();
3814         const double*           uv = pos->GetParameters();
3815         switch ( pos->GetTypeOfPosition() )
3816         {
3817         case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID );               break;
3818         case SMDS_TOP_FACE:    newMeshDS->SetNodeOnFace  ( newNode, newID, uv[0], uv[1] ); break;
3819         case SMDS_TOP_EDGE:    newMeshDS->SetNodeOnEdge  ( newNode, newID, uv[0] );        break;
3820         case SMDS_TOP_VERTEX:  newMeshDS->SetNodeOnVertex( newNode, newID );               break;
3821         default: ;
3822         }
3823       }
3824       SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3825       while( eIt->more() )
3826       {
3827         const SMDS_MeshElement* e = eIt->next();
3828         elemData.Init( e, /*basicOnly=*/false );
3829         elemData.SetID( e->GetID() );
3830         elemData.myNodes.resize( e->NbNodes() );
3831         SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3832         size_t iN;
3833         for ( iN = 0; nnIt->more(); ++iN )
3834         {
3835           const SMDS_MeshNode* srcNode = nnIt->next();
3836           elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3837           if ( !elemData.myNodes[ iN ])
3838             break;
3839         }
3840         if ( iN == elemData.myNodes.size() )
3841           if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3842             newMeshDS->SetMeshElementOnShape( newElem, newID );
3843       }
3844       if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3845         newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3846     }
3847
3848     newMeshDS->Modified();
3849   }
3850
3851
3852   // treat groups
3853
3854   TStr2StrMap old2newGroupMap;
3855
3856   SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3857
3858   SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3859   CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3860   for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3861   {
3862     SMESH::SMESH_Group_var         stdlGroup = SMESH::SMESH_Group::_narrow        ( groups[ i ]);
3863     SMESH::SMESH_GroupOnGeom_var   geomGroup = SMESH::SMESH_GroupOnGeom::_narrow  ( groups[ i ]);
3864     SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3865
3866     CORBA::String_var      name = groups[ i ]->GetName();
3867     SMESH::ElementType elemType = groups[ i ]->GetType();
3868
3869     SMESH::SMESH_GroupBase_var newGroup;
3870
3871     if ( !stdlGroup->_is_nil() )
3872     {
3873       if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3874       {
3875         SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3876         const bool isElem = ( elemType != SMESH::NODE );
3877         CORBA::ULong iE = 0;
3878         for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3879           if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3880             break;
3881         if ( iE < elemIDs->length() )
3882         {
3883           stdlGroup = theNewMesh->CreateGroup( elemType, name );
3884           stdlGroup->Add( elemIDs );
3885           newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3886         }
3887       }
3888     }
3889     else if ( !geomGroup->_is_nil() )
3890     {
3891       GEOM::GEOM_Object_var    geom = geomGroup->GetShape();
3892       GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3893       if ( newGeom->_is_nil() )
3894       {
3895         newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3896         shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3897         ok = false;
3898       }
3899       else
3900       {
3901         newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3902       }
3903     }
3904     else if ( !fltrGroup->_is_nil() )
3905     {
3906       // replace geometry in a filter
3907       SMESH::Filter_var filter = fltrGroup->GetFilter();
3908       SMESH::Filter::Criteria_var criteria;
3909       filter->GetCriteria( criteria.out() );
3910
3911       bool isMissingGroup = false;
3912       std::vector< std::string > badEntries;
3913
3914       for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3915       {
3916         const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3917         switch ( criteria[ iCr ].Type )
3918         {
3919         case SMESH::FT_BelongToMeshGroup:
3920         {
3921           SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3922           btgg->SetGroupID( thresholdID );
3923           SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3924           SALOMEDS::SObject_wrap   refGroupSO = ObjectToSObject( refGroup );
3925           if ( refGroupSO->_is_nil() )
3926             break;
3927           CORBA::String_var     refID = refGroupSO->GetID();
3928           TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3929           if ( o2nID == old2newGroupMap.end() )
3930           {
3931             isMissingGroup = true; // corresponding new group not yet created
3932             break;
3933           }
3934           criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3935
3936           if ( o2nID->second.empty() ) // new referred group is invalid
3937             badEntries.push_back( refID.in() );
3938           break;
3939         }
3940         case SMESH::FT_BelongToGeom:
3941         case SMESH::FT_BelongToPlane:
3942         case SMESH::FT_BelongToCylinder:
3943         case SMESH::FT_BelongToGenSurface:
3944         case SMESH::FT_LyingOnGeom:
3945         {
3946           std::string newID = shapeMapper.FindNew( thresholdID );
3947           criteria[ iCr ].ThresholdID = newID.c_str();
3948           if ( newID.empty() )
3949             badEntries.push_back( thresholdID );
3950           break;
3951         }
3952         case SMESH::FT_ConnectedElements:
3953         {
3954           if ( thresholdID && thresholdID[0] )
3955           {
3956             std::string newID = shapeMapper.FindNew( thresholdID );
3957             criteria[ iCr ].ThresholdID = newID.c_str();
3958             if ( newID.empty() )
3959               badEntries.push_back( thresholdID );
3960           }
3961           break;
3962         }
3963         default:;
3964         }
3965       } // loop on criteria
3966
3967       if ( isMissingGroup && i < nbGroups )
3968       {
3969         // to treat the group again
3970         append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3971         ++nbAddedGroups;
3972         continue;
3973       }
3974       SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3975       newFilter->SetCriteria( criteria );
3976
3977       newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3978       newFilter->UnRegister();
3979
3980       SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3981       for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3982         shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3983
3984       if ( isMissingGroup ) // all groups treated but a referred groups still not found
3985       {
3986         invalidSObjects.push_back( ObjectToSObject( newGroup ));
3987         ok = false;
3988       }
3989       if ( !badEntries.empty() )
3990         ok = false;
3991
3992     } // treat a group on filter
3993
3994     append( theNewGroups, newGroup );
3995
3996     // fill old2newGroupMap
3997     SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3998     SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3999     if ( !srcSO->_is_nil() )
4000     {
4001       CORBA::String_var srcID, newID("");
4002       srcID = srcSO->GetID();
4003       if ( !newSO->_is_nil() )
4004         newID = newSO->GetID();
4005       old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4006                                               std::string( newID.in() )));
4007     }
4008
4009     if ( newGroup->_is_nil() )
4010       ok = false;
4011
4012   } // loop on groups
4013
4014   newMeshDS->CompactMesh();
4015
4016   // set mesh name
4017   if ( !theMeshName || !theMeshName[0] )
4018   {
4019     SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4020     SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4021     CORBA::String_var oldName = soOld->GetName();
4022     SetName( soNew, oldName.in(), "Mesh" );
4023   }
4024   // mark invalid objects
4025   shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4026
4027   for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4028     highLightInvalid( invalidSObjects[i].in(), true );
4029
4030   pyDump << "ok, "
4031          << theNewMesh << ", "
4032          << theNewGroups << ", "
4033          << *theNewSubmeshes.ptr() << ", "
4034          << *theNewHypotheses.ptr() << ", "
4035          << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4036          << theSourceMesh << ", "
4037          << theNewGeometry << ", "
4038          << "'" << theMeshName << "', "
4039          << theToCopyGroups << ", "
4040          << theToReuseHypotheses << ", "
4041          << theToCopyElements << " )";
4042
4043   SMESH_CATCH( SMESH::throwCorbaException );
4044
4045   return ok;
4046 }
4047
4048 //================================================================================
4049 /*!
4050  * \brief Get version of MED format being used.
4051  */
4052 //================================================================================
4053
4054 char* SMESH_Gen_i::GetMEDFileVersion()
4055 {
4056   MED::TInt majeur, mineur, release;
4057   majeur =  mineur = release = 0;
4058   MED::GetVersionRelease(majeur, mineur, release);
4059   std::ostringstream version;
4060   version << majeur << "." << mineur << "." << release;
4061   return CORBA::string_dup( version.str().c_str() );
4062 }
4063
4064 //================================================================================
4065 /*!
4066  *  SMESH_Gen_i::GetMEDVersion
4067  *
4068  *  Get MED version of the file by its name
4069  */
4070 //================================================================================
4071
4072 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4073 {
4074   std::string version = MED::GetMEDVersion( theFileName );
4075   return CORBA::string_dup( version.c_str() );
4076 }
4077
4078 //================================================================================
4079 /*!
4080  *  SMESH_Gen_i::CheckCompatibility
4081  *
4082  *  Check compatibility of file with MED format being used, read only.
4083  */
4084 //================================================================================
4085
4086 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4087 {
4088   return MED::CheckCompatibility( theFileName );
4089 }
4090
4091 //================================================================================
4092 /*!
4093  *  SMESH_Gen_i::CheckWriteCompatibility
4094  *
4095  *  Check compatibility of file with MED format being used, for append on write.
4096  */
4097 //================================================================================
4098
4099 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4100 {
4101   return MED::CheckCompatibility( theFileName, true );
4102 }
4103
4104 //================================================================================
4105 /*!
4106  *  SMESH_Gen_i::GetMeshNames
4107  *
4108  *  Get names of meshes defined in file with the specified name
4109  */
4110 //================================================================================
4111 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4112
4113 {
4114   SMESH::string_array_var aResult = new SMESH::string_array();
4115   MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4116   MED::TErr anErr;
4117   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4118   if( anErr >= 0 ) {
4119     aResult->length( aNbMeshes );
4120     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4121       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4122       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4123     }
4124   }
4125   return aResult._retn();
4126 }
4127
4128 //=============================================================================
4129 /*!
4130  *  SMESH_Gen_i::Save
4131  *
4132  *  Save SMESH module's data
4133  */
4134 //=============================================================================
4135
4136 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4137                                       const char*              theURL,
4138                                       bool                     isMultiFile )
4139 {
4140   // localizing
4141   Kernel_Utils::Localizer loc;
4142
4143   if (!myStudyContext)
4144     UpdateStudy();
4145
4146   // Store study contents as a set of python commands
4147   SavePython();
4148
4149   SALOMEDS::Study_var aStudy = getStudyServant();
4150
4151   // Declare a byte stream
4152   SALOMEDS::TMPFile_var aStreamFile;
4153
4154   // Obtain a temporary dir
4155   TCollection_AsciiString tmpDir =
4156     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4157
4158   // Create a sequence of files processed
4159   SALOMEDS_Tool::ListOfFiles aFileSeq;
4160   aFileSeq.reserve( NUM_TMP_FILES );
4161
4162   TCollection_AsciiString aStudyName( "" );
4163   if ( isMultiFile )
4164     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4165
4166   // Set names of temporary files
4167   TCollection_AsciiString filename =
4168     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
4169   TCollection_AsciiString meshfile =
4170     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
4171   aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4172   aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4173   filename = tmpDir + filename;
4174   meshfile = tmpDir + meshfile;
4175
4176   HDFfile*    aFile;
4177   HDFdataset* aDataset;
4178   HDFgroup*   aTopGroup;
4179   HDFgroup*   aGroup;
4180   HDFgroup*   aSubGroup;
4181   HDFgroup*   aSubSubGroup;
4182   hdf_size    aSize[ 1 ];
4183
4184
4185   //Remove the files if they exist: BugID: 11225
4186 #ifndef WIN32 /* unix functionality */
4187   TCollection_AsciiString cmd("rm -f \"");
4188 #else /* windows */
4189   TCollection_AsciiString cmd("del /F \"");
4190 #endif
4191
4192   cmd+=filename;
4193   cmd+="\" \"";
4194   cmd+=meshfile;
4195   cmd+="\"";
4196 #ifdef WIN32
4197   cmd+=" 2>NUL";
4198 #endif
4199   system(cmd.ToCString());
4200
4201   // MED writer to be used by storage process
4202   DriverMED_W_SMESHDS_Mesh myWriter;
4203   myWriter.SetFile( meshfile.ToCString() );
4204
4205   // IMP issue 20918
4206   // SetStoreName() to groups before storing hypotheses to let them refer to
4207   // groups using "store name", which is "Group <group_persistent_id>"
4208   {
4209     SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4210     for ( ; itBig->More(); itBig->Next() ) {
4211       SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4212       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4213         CORBA::Object_var anObject = SObjectToObject( gotBranch );
4214         if ( !CORBA::is_nil( anObject ) ) {
4215           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4216           if ( !myMesh->_is_nil() ) {
4217             myMesh->Load(); // load from study file if not yet done
4218             TPythonDump pd(this); // not to dump GetGroups()
4219             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4220             for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4221             {
4222               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4223               if ( grImpl )
4224               {
4225                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4226                 int anId = myStudyContext->findId( string( objStr.in() ) );
4227                 char grpName[ 30 ];
4228                 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4229                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4230                 aGrpBaseDS->SetStoreName( grpName );
4231               }
4232             }
4233           }
4234         }
4235       }
4236     }
4237   }
4238
4239   // Write data
4240   // ---> create HDF file
4241   aFile = new HDFfile( (char*) filename.ToCString() );
4242   aFile->CreateOnDisk();
4243
4244   // --> iterator for top-level objects
4245   SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4246   for ( ; itBig->More(); itBig->Next() ) {
4247     SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4248
4249     // --> hypotheses root branch (only one for the study)
4250     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4251       // create hypotheses root HDF group
4252       aTopGroup = new HDFgroup( "Hypotheses", aFile );
4253       aTopGroup->CreateOnDisk();
4254
4255       // iterator for all hypotheses
4256       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4257       for ( ; it->More(); it->Next() ) {
4258         SALOMEDS::SObject_wrap mySObject = it->Value();
4259         CORBA::Object_var anObject = SObjectToObject( mySObject );
4260         if ( !CORBA::is_nil( anObject ) ) {
4261           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4262           if ( !myHyp->_is_nil() ) {
4263             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4264             if ( myImpl ) {
4265               CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4266               std::string hypname = hn.in();
4267               std::string libname = ln.in();
4268               // BUG SWP13062
4269               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4270               // WIN32 and ".so" for X-system) must be deleted
4271               int libname_len = libname.length();
4272 #ifdef WIN32
4273               if( libname_len > 4 )
4274                 libname.resize( libname_len - 4 );
4275 #else
4276               // PAL17753 (Regression: missing hypothesis in restored study)
4277               // "lib" also should be removed from the beginning
4278               if( libname_len > 6 )
4279                 libname = libname.substr( 3, libname_len - 3 - 3 );
4280 #endif
4281               CORBA::String_var  objStr = GetORB()->object_to_string( anObject );
4282               CORBA::String_var hypdata = myImpl->SaveTo();
4283               int                    id = myStudyContext->findId( string( objStr.in() ));
4284
4285               // for each hypothesis create HDF group basing on its id
4286               char hypGrpName[30];
4287               sprintf( hypGrpName, "Hypothesis %d", id );
4288               aGroup = new HDFgroup( hypGrpName, aTopGroup );
4289               aGroup->CreateOnDisk();
4290               // --> type name of hypothesis
4291               aSize[ 0 ] = hypname.length() + 1;
4292               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4293               aDataset->CreateOnDisk();
4294               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4295               aDataset->CloseOnDisk();
4296               // --> server plugin library name of hypothesis
4297               aSize[ 0 ] = libname.length() + 1;
4298               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4299               aDataset->CreateOnDisk();
4300               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4301               aDataset->CloseOnDisk();
4302               // --> persistent data of hypothesis
4303               aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4304               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4305               aDataset->CreateOnDisk();
4306               aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4307               aDataset->CloseOnDisk();
4308               // close hypothesis HDF group
4309               aGroup->CloseOnDisk();
4310             }
4311           }
4312         }
4313       }
4314       // close hypotheses root HDF group
4315       aTopGroup->CloseOnDisk();
4316     }
4317     // --> algorithms root branch (only one for the study)
4318     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4319       // create algorithms root HDF group
4320       aTopGroup = new HDFgroup( "Algorithms", aFile );
4321       aTopGroup->CreateOnDisk();
4322
4323       // iterator for all algorithms
4324       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4325       for ( ; it->More(); it->Next() ) {
4326         SALOMEDS::SObject_wrap mySObject = it->Value();
4327         CORBA::Object_var anObject = SObjectToObject( mySObject );
4328         if ( !CORBA::is_nil( anObject ) ) {
4329           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4330           if ( !myHyp->_is_nil() ) {
4331             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4332             if ( myImpl ) {
4333               CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4334               std::string hypname = hn.in();
4335               std::string libname = ln.in();
4336               // BUG SWP13062
4337               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4338               // WIN32 and ".so" for X-system) must be deleted
4339               int libname_len = libname.length();
4340 #ifdef WIN32
4341               if( libname_len > 4 )
4342                 libname.resize( libname_len - 4 );
4343 #else
4344               // PAL17753 (Regression: missing hypothesis in restored study)
4345               // "lib" also should be removed from the beginning
4346               if( libname_len > 6 )
4347                 libname = libname.substr( 3, libname_len - 3 - 3 );
4348 #endif
4349               CORBA::String_var  objStr = GetORB()->object_to_string( anObject );
4350               CORBA::String_var hypdata = myImpl->SaveTo();
4351               int                    id = myStudyContext->findId( string( objStr.in() ) );
4352
4353               // for each algorithm create HDF group basing on its id
4354               char hypGrpName[30];
4355               sprintf( hypGrpName, "Algorithm %d", id );
4356               aGroup = new HDFgroup( hypGrpName, aTopGroup );
4357               aGroup->CreateOnDisk();
4358               // --> type name of algorithm
4359               aSize[0] = hypname.length() + 1;
4360               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4361               aDataset->CreateOnDisk();
4362               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4363               aDataset->CloseOnDisk();
4364               // --> server plugin library name of hypothesis
4365               aSize[0] = libname.length() + 1;
4366               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4367               aDataset->CreateOnDisk();
4368               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4369               aDataset->CloseOnDisk();
4370               // --> persistent data of algorithm
4371               aSize[0] = strlen( hypdata.in() ) + 1;
4372               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4373               aDataset->CreateOnDisk();
4374               aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4375               aDataset->CloseOnDisk();
4376               // close algorithm HDF group
4377               aGroup->CloseOnDisk();
4378             }
4379           }
4380         }
4381       }
4382       // close algorithms root HDF group
4383       aTopGroup->CloseOnDisk();
4384     }
4385     // --> mesh objects roots branches
4386     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4387       CORBA::Object_var anObject = SObjectToObject( gotBranch );
4388       if ( !CORBA::is_nil( anObject ) ) {
4389         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4390         if ( !myMesh->_is_nil() ) {
4391           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4392           if ( myImpl ) {
4393             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4394             int id = myStudyContext->findId( string( objStr.in() ) );
4395             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4396             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4397             bool hasShape = myLocMesh.HasShapeToMesh();
4398
4399             // for each mesh open the HDF group basing on its id
4400             char meshGrpName[ 30 ];
4401             sprintf( meshGrpName, "Mesh %d", id );
4402             aTopGroup = new HDFgroup( meshGrpName, aFile );
4403             aTopGroup->CreateOnDisk();
4404
4405             // --> put dataset to hdf file which is a flag that mesh has data
4406             string strHasData = "0";
4407             // check if the mesh is not empty
4408             if ( mySMESHDSMesh->NbNodes() > 0 ) {
4409               // write mesh data to med file
4410               myWriter.SetMesh( mySMESHDSMesh );
4411               myWriter.SetMeshId( id );
4412               strHasData = "1";
4413             }
4414             aSize[ 0 ] = strHasData.length() + 1;
4415             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4416             aDataset->CreateOnDisk();
4417             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4418             aDataset->CloseOnDisk();
4419
4420             // ouv : NPAL12872
4421             // for each mesh open the HDF group basing on its auto color parameter
4422             char meshAutoColorName[ 30 ];
4423             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4424             int anAutoColor[1];
4425             anAutoColor[0] = myImpl->GetAutoColor();
4426             aSize[ 0 ] = 1;
4427             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4428             aDataset->CreateOnDisk();
4429             aDataset->WriteOnDisk( anAutoColor );
4430             aDataset->CloseOnDisk();
4431
4432             // issue 0020693. Store _isModified flag
4433             int isModified = myLocMesh.GetIsModified();
4434             aSize[ 0 ] = 1;
4435             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4436             aDataset->CreateOnDisk();
4437             aDataset->WriteOnDisk( &isModified );
4438             aDataset->CloseOnDisk();
4439
4440             // issue 20918. Store Persistent Id of SMESHDS_Mesh
4441             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4442             aSize[ 0 ] = 1;
4443             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4444             aDataset->CreateOnDisk();
4445             aDataset->WriteOnDisk( &meshPersistentId );
4446             aDataset->CloseOnDisk();
4447
4448             // Store SMESH_Mesh_i::_mainShapeTick
4449             int shapeTick = myImpl->MainShapeTick();
4450             aSize[ 0 ] = 1;
4451             aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4452             aDataset->CreateOnDisk();
4453             aDataset->WriteOnDisk( &shapeTick );
4454             aDataset->CloseOnDisk();
4455
4456             // write reference on a shape if exists
4457             SALOMEDS::SObject_wrap myRef;
4458             bool shapeRefFound = false;
4459             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4460             if ( found ) {
4461               SALOMEDS::SObject_wrap myShape;
4462               bool ok = myRef->ReferencedObject( myShape.inout() );
4463               if ( ok ) {
4464                 CORBA::Object_var shapeObj = myShape->GetObject();
4465                 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4466                 CORBA::String_var myRefOnObject = myShape->GetID();
4467                 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4468                   aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4469                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4470                   aDataset->CreateOnDisk();
4471                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4472                   aDataset->CloseOnDisk();
4473                 }
4474               }
4475             }
4476
4477             // Store file info
4478             std::string info = myImpl->FileInfoToString();
4479             if ( !info.empty() )
4480             {
4481               aSize[ 0 ] = info.size();
4482               aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4483               aDataset->CreateOnDisk();
4484               aDataset->WriteOnDisk( (char*) info.data() );
4485               aDataset->CloseOnDisk();
4486             }
4487
4488             // write applied hypotheses if exist
4489             SALOMEDS::SObject_wrap myHypBranch;
4490             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4491             if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4492               aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4493             }
4494             if ( found && (shapeRefFound || !hasShape) ) {
4495               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4496               aGroup->CreateOnDisk();
4497
4498               SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4499               int hypNb = 0;
4500               for ( ; it->More(); it->Next() ) {
4501                 SALOMEDS::SObject_wrap mySObject = it->Value();
4502                 SALOMEDS::SObject_wrap myRefOnHyp;
4503                 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4504                 if ( ok ) {
4505                   // san - it is impossible to recover applied hypotheses
4506                   //       using their entries within Load() method,
4507                   // for there are no AttributeIORs in the study when Load() is working.
4508                   // Hence, it is better to store persistent IDs of hypotheses as references to them
4509
4510                   //string myRefOnObject = myRefOnHyp->GetID();
4511                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4512                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4513                   int id = myStudyContext->findId( string( objStr.in() ) );
4514                   //if ( myRefOnObject.length() > 0 ) {
4515                   //aSize[ 0 ] = myRefOnObject.length() + 1;
4516                   char hypName[ 30 ], hypId[ 30 ];
4517                   sprintf( hypName, "Hyp %d", ++hypNb );
4518                   sprintf( hypId, "%d", id );
4519                   aSize[ 0 ] = strlen( hypId ) + 1;
4520                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4521                   aDataset->CreateOnDisk();
4522                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4523                   aDataset->WriteOnDisk( hypId );
4524                   aDataset->CloseOnDisk();
4525                   //}
4526                 }
4527               }
4528               aGroup->CloseOnDisk();
4529             }
4530
4531             // write applied algorithms if exist
4532             SALOMEDS::SObject_wrap myAlgoBranch;
4533             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4534                                               myAlgoBranch.inout() );
4535             if ( found && !shapeRefFound && hasShape) { // remove applied algos
4536               aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4537             }
4538             if ( found && (shapeRefFound || !hasShape)) {
4539               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4540               aGroup->CreateOnDisk();
4541
4542               SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4543               int algoNb = 0;
4544               for ( ; it->More(); it->Next() ) {
4545                 SALOMEDS::SObject_wrap mySObject = it->Value();
4546                 SALOMEDS::SObject_wrap myRefOnAlgo;
4547                 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4548                 if ( ok ) {
4549                   // san - it is impossible to recover applied algorithms
4550                   //       using their entries within Load() method,
4551                   // for there are no AttributeIORs in the study when Load() is working.
4552                   // Hence, it is better to store persistent IDs of algorithms as references to them
4553
4554                   //string myRefOnObject = myRefOnAlgo->GetID();
4555                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4556                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4557                   int id = myStudyContext->findId( string( objStr.in() ) );
4558                   //if ( myRefOnObject.length() > 0 ) {
4559                   //aSize[ 0 ] = myRefOnObject.length() + 1;
4560                   char algoName[ 30 ], algoId[ 30 ];
4561                   sprintf( algoName, "Algo %d", ++algoNb );
4562                   sprintf( algoId, "%d", id );
4563                   aSize[ 0 ] = strlen( algoId ) + 1;
4564                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4565                   aDataset->CreateOnDisk();
4566                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4567                   aDataset->WriteOnDisk( algoId );
4568                   aDataset->CloseOnDisk();
4569                   //}
4570                 }
4571               }
4572               aGroup->CloseOnDisk();
4573             }
4574
4575             // --> submesh objects sub-branches
4576
4577             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4578               SALOMEDS::SObject_wrap mySubmeshBranch;
4579               found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4580
4581               if ( found ) // check if there is shape reference in submeshes
4582               {
4583                 bool hasShapeRef = false;
4584                 SALOMEDS::ChildIterator_wrap itSM =
4585                   aStudy->NewChildIterator( mySubmeshBranch );
4586                 for ( ; itSM->More(); itSM->Next() ) {
4587                   SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4588                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4589                     mySubRef->ReferencedObject( myShape.inout() );
4590                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4591                     hasShapeRef = true;
4592                   else
4593                   { // remove one submesh
4594                     if ( shapeRefFound )
4595                     { // unassign hypothesis
4596                       SMESH::SMESH_subMesh_var mySubMesh =
4597                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4598                       if ( !mySubMesh->_is_nil() ) {
4599                         int shapeID = mySubMesh->GetId();
4600                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4601                         const list<const SMESHDS_Hypothesis*>& hypList =
4602                           mySMESHDSMesh->GetHypothesis( S );
4603                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4604                         while ( hyp != hypList.end() ) {
4605                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
4606                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4607                         }
4608                       }
4609                     }
4610                     aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4611                   }
4612                 } // loop on submeshes of a type
4613                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4614                   aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4615                   found = false;
4616                 }
4617               }  // end check if there is shape reference in submeshes
4618               if ( found ) {
4619                 char name_meshgroup[ 30 ];
4620                 if ( i == GetSubMeshOnVertexTag() )
4621                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
4622                 else if ( i == GetSubMeshOnEdgeTag() )
4623                   strcpy( name_meshgroup, "SubMeshes On Edge" );
4624                 else if ( i == GetSubMeshOnWireTag() )
4625                   strcpy( name_meshgroup, "SubMeshes On Wire" );
4626                 else if ( i == GetSubMeshOnFaceTag() )
4627                   strcpy( name_meshgroup, "SubMeshes On Face" );
4628                 else if ( i == GetSubMeshOnShellTag() )
4629                   strcpy( name_meshgroup, "SubMeshes On Shell" );
4630                 else if ( i == GetSubMeshOnSolidTag() )
4631                   strcpy( name_meshgroup, "SubMeshes On Solid" );
4632                 else if ( i == GetSubMeshOnCompoundTag() )
4633                   strcpy( name_meshgroup, "SubMeshes On Compound" );
4634
4635                 // for each type of submeshes create container HDF group
4636                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4637                 aGroup->CreateOnDisk();
4638
4639                 // iterator for all submeshes of given type
4640                 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4641                 for ( ; itSM->More(); itSM->Next() ) {
4642                   SALOMEDS::SObject_wrap mySObject = itSM->Value();
4643                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4644                   if ( !CORBA::is_nil( anSubObject ))
4645                   {
4646                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4647                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4648                     int subid = myStudyContext->findId( string( objStr.in() ) );
4649
4650                     // for each mesh open the HDF group basing on its id
4651                     char submeshGrpName[ 30 ];
4652                     sprintf( submeshGrpName, "SubMesh %d", subid );
4653                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4654                     aSubGroup->CreateOnDisk();
4655
4656                     // write reference on a shape, already checked if it exists
4657                     SALOMEDS::SObject_wrap mySubRef, myShape;
4658                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4659                       mySubRef->ReferencedObject( myShape.inout() );
4660                     string myRefOnObject = myShape->GetID();
4661                     if ( myRefOnObject.length() > 0 ) {
4662                       aSize[ 0 ] = myRefOnObject.length() + 1;
4663                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4664                       aDataset->CreateOnDisk();
4665                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4666                       aDataset->CloseOnDisk();
4667                     }
4668
4669                     // write applied hypotheses if exist
4670                     SALOMEDS::SObject_wrap mySubHypBranch;
4671                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4672                                                       mySubHypBranch.inout() );
4673                     if ( found ) {
4674                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4675                       aSubSubGroup->CreateOnDisk();
4676
4677                       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4678                       int hypNb = 0;
4679                       for ( ; it->More(); it->Next() ) {
4680                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
4681                         SALOMEDS::SObject_wrap myRefOnHyp;
4682                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4683                         if ( ok ) {
4684                           //string myRefOnObject = myRefOnHyp->GetID();
4685                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4686                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4687                           int id = myStudyContext->findId( string( objStr.in() ) );
4688                           //if ( myRefOnObject.length() > 0 ) {
4689                           //aSize[ 0 ] = myRefOnObject.length() + 1;
4690                           char hypName[ 30 ], hypId[ 30 ];
4691                           sprintf( hypName, "Hyp %d", ++hypNb );
4692                           sprintf( hypId, "%d", id );
4693                           aSize[ 0 ] = strlen( hypId ) + 1;
4694                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4695                           aDataset->CreateOnDisk();
4696                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4697                           aDataset->WriteOnDisk( hypId );
4698                           aDataset->CloseOnDisk();
4699                           //}
4700                         }
4701                       }
4702                       aSubSubGroup->CloseOnDisk();
4703                     }
4704
4705                     // write applied algorithms if exist
4706                     SALOMEDS::SObject_wrap mySubAlgoBranch;
4707                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4708                                                       mySubAlgoBranch.inout() );
4709                     if ( found ) {
4710                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4711                       aSubSubGroup->CreateOnDisk();
4712
4713                       SALOMEDS::ChildIterator_wrap it =
4714                         aStudy->NewChildIterator( mySubAlgoBranch );
4715                       int algoNb = 0;
4716                       for ( ; it->More(); it->Next() ) {
4717                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
4718                         SALOMEDS::SObject_wrap myRefOnAlgo;
4719                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4720                         if ( ok ) {
4721                           //string myRefOnObject = myRefOnAlgo->GetID();
4722                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4723                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4724                           int id = myStudyContext->findId( string( objStr.in() ) );
4725                           //if ( myRefOnObject.length() > 0 ) {
4726                           //aSize[ 0 ] = myRefOnObject.length() + 1;
4727                           char algoName[ 30 ], algoId[ 30 ];
4728                           sprintf( algoName, "Algo %d", ++algoNb );
4729                           sprintf( algoId, "%d", id );
4730                           aSize[ 0 ] = strlen( algoId ) + 1;
4731                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4732                           aDataset->CreateOnDisk();
4733                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4734                           aDataset->WriteOnDisk( algoId );
4735                           aDataset->CloseOnDisk();
4736                           //}
4737                         }
4738                       }
4739                       aSubSubGroup->CloseOnDisk();
4740                     }
4741                     // close submesh HDF group
4742                     aSubGroup->CloseOnDisk();
4743                   }
4744                 }
4745                 // close container of submeshes by type HDF group
4746                 aGroup->CloseOnDisk();
4747               }
4748             }
4749
4750             // store submesh order if any
4751             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4752             const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4753             if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4754               char order_list[ 30 ];
4755               strcpy( order_list, "Mesh Order" );
4756               // count number of submesh ids
4757               int nbIDs = 0;
4758               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4759               for ( ; idIt != theOrderIds.end(); idIt++ )
4760                 nbIDs += (*idIt).size();
4761               // number of values = number of IDs +
4762               //                    number of lists (for separators) - 1
4763               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4764               idIt = theOrderIds.begin();
4765               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4766                 const TListOfInt& idList = *idIt;
4767                 if (idIt != theOrderIds.begin()) // not first list
4768                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4769                 // dump submesh ids from current list
4770                 TListOfInt::const_iterator id_smId = idList.begin();
4771                 for( ; id_smId != idList.end(); id_smId++ )
4772                   smIDs[ i++ ] = *id_smId;
4773               }
4774               // write HDF group
4775               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4776
4777               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4778               aDataset->CreateOnDisk();
4779               aDataset->WriteOnDisk( smIDs );
4780               aDataset->CloseOnDisk();
4781               //
4782               delete[] smIDs;
4783             }
4784             if ( !theOrderIds.empty() && isNewOrederVersion )
4785             {
4786               // convert ids to entries
4787               std::list< std::list< std::string > > orderEntryLists;
4788               for ( const TListOfInt& idList : theOrderIds )
4789               {
4790                 orderEntryLists.emplace_back();
4791                 std::list< std::string > & entryList = orderEntryLists.back();
4792                 for ( const int& id : idList )
4793                 {
4794                   const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4795                   GEOM::GEOM_Object_var  go = ShapeToGeomObject( shape );
4796                   SALOMEDS::SObject_var  so = ObjectToSObject( go );
4797                   if ( !so->_is_nil() )
4798                   {
4799                     CORBA::String_var entry = so->GetID();
4800                     entryList.emplace_back( entry.in() );
4801                   }
4802                 }
4803               }
4804               // convert orderEntryLists to string
4805               std::ostringstream ostream;
4806               boost::archive::text_oarchive( ostream ) << orderEntryLists;
4807               std::string orderEntryString = ostream.str();
4808
4809               // write HDF group
4810               aSize[ 0 ] = orderEntryString.size() + 1;
4811               aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4812               aDataset->CreateOnDisk();
4813               aDataset->WriteOnDisk((char*) orderEntryString.data() );
4814               aDataset->CloseOnDisk();
4815             }
4816
4817             // groups root sub-branch
4818             SALOMEDS::SObject_wrap myGroupsBranch;
4819             for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4820               found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4821               if ( found ) {
4822                 char name_group[ 30 ];
4823                 if ( i == GetNodeGroupsTag() )
4824                   strcpy( name_group, "Groups of Nodes" );
4825                 else if ( i == GetEdgeGroupsTag() )
4826                   strcpy( name_group, "Groups of Edges" );
4827                 else if ( i == GetFaceGroupsTag() )
4828                   strcpy( name_group, "Groups of Faces" );
4829                 else if ( i == GetVolumeGroupsTag() )
4830                   strcpy( name_group, "Groups of Volumes" );
4831                 else if ( i == Get0DElementsGroupsTag() )
4832                   strcpy( name_group, "Groups of 0D Elements" );
4833                 else if ( i == GetBallElementsGroupsTag() )
4834                   strcpy( name_group, "Groups of Balls" );
4835
4836                 aGroup = new HDFgroup( name_group, aTopGroup );
4837                 aGroup->CreateOnDisk();
4838
4839                 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4840                 for ( ; it->More(); it->Next() ) {
4841                   SALOMEDS::SObject_wrap mySObject = it->Value();
4842                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4843                   if ( !CORBA::is_nil( aSubObject ) ) {
4844                     SMESH_GroupBase_i* myGroupImpl =
4845                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4846                     if ( !myGroupImpl )
4847                       continue;
4848                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4849                     if ( !aGrpBaseDS )
4850                       continue;
4851
4852                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4853                     int anId = myStudyContext->findId( string( objStr.in() ) );
4854
4855                     // For each group, create a dataset named "Group <group_persistent_id>"
4856                     // and store the group's user name into it
4857                     const char*         grpName = aGrpBaseDS->GetStoreName();
4858                     CORBA::String_var aUserName = myGroupImpl->GetName();
4859                     aSize[ 0 ] = strlen( aUserName ) + 1;
4860
4861                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4862                     aDataset->CreateOnDisk();
4863                     aDataset->WriteOnDisk( aUserName );
4864                     aDataset->CloseOnDisk();
4865
4866                     // ouv : NPAL12872
4867                     // For each group, create a dataset named "Group <group_persistent_id> Color"
4868                     // and store the group's color into it
4869                     char grpColorName[ 30 ];
4870                     sprintf( grpColorName, "ColorGroup %d", anId );
4871                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
4872                     double anRGB[3];
4873                     anRGB[ 0 ] = aColor.R;
4874                     anRGB[ 1 ] = aColor.G;
4875                     anRGB[ 2 ] = aColor.B;
4876                     aSize[ 0 ] = 3;
4877                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4878                     aDataset->CreateOnDisk();
4879                     aDataset->WriteOnDisk( anRGB );
4880                     aDataset->CloseOnDisk();
4881
4882                     // Pass SMESHDS_Group to MED writer
4883                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4884                     if ( aGrpDS )
4885                       myWriter.AddGroup( aGrpDS );
4886
4887                     // write reference on a shape if exists
4888                     SMESHDS_GroupOnGeom* aGeomGrp =
4889                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4890                     if ( aGeomGrp ) {
4891                       SALOMEDS::SObject_wrap mySubRef, myShape;
4892                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4893                           mySubRef->ReferencedObject( myShape.inout() ) &&
4894                           !CORBA::is_nil( myShape->GetObject() ))
4895                       {
4896                         CORBA::String_var myRefOnObject = myShape->GetID();
4897                         if ( myRefOnObject.in()[0] ) {
4898                           char aRefName[ 30 ];
4899                           sprintf( aRefName, "Ref on shape %d", anId);
4900                           aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4901                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4902                           aDataset->CreateOnDisk();
4903                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4904                           aDataset->CloseOnDisk();
4905                         }
4906                       }
4907                       else // shape ref is invalid:
4908                       {
4909                         // save a group on geometry as ordinary group
4910                         myWriter.AddGroup( aGeomGrp );
4911                       }
4912                     }
4913                     else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4914                               dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4915                     {
4916                       std::string str = aFilterGrp_i->FilterToString();
4917                       std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4918                       aSize[ 0 ] = str.length() + 1;
4919                       aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4920                       aDataset->CreateOnDisk();
4921                       aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4922                       aDataset->CloseOnDisk();
4923                     }
4924                   }
4925                 }
4926                 aGroup->CloseOnDisk();
4927               }
4928             } // loop on groups
4929
4930             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4931             {
4932               // Flush current mesh information into MED file
4933               myWriter.Perform();
4934
4935               // save info on nb of elements
4936               SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4937
4938               // maybe a shape was deleted in the study
4939               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4940                 TopoDS_Shape nullShape;
4941                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4942               }
4943
4944               SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4945               if ( smIt->more() )
4946               {
4947                 // Store submeshes
4948                 // ----------------
4949                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4950                 aGroup->CreateOnDisk();
4951
4952                 // each element belongs to one or none submesh,
4953                 // so for each node/element, we store a submesh ID
4954
4955                 // Store submesh IDs
4956                 for ( int isNode = 0; isNode < 2; ++isNode )
4957                 {
4958                   SMDS_ElemIteratorPtr eIt =
4959                     mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4960                   int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4961                   if ( nbElems < 1 )
4962                     continue;
4963                   std::vector<int> smIDs; smIDs.reserve( nbElems );
4964                   while ( eIt->more() )
4965                     if ( const SMDS_MeshElement* e = eIt->next())
4966                       smIDs.push_back( e->getshapeId() );
4967                   // write HDF group
4968                   aSize[ 0 ] = nbElems;
4969                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4970                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4971                   aDataset->CreateOnDisk();
4972                   aDataset->WriteOnDisk( & smIDs[0] );
4973                   aDataset->CloseOnDisk();
4974                 }
4975
4976                 aGroup->CloseOnDisk();
4977
4978                 // Store node positions on sub-shapes (SMDS_Position):
4979                 // ----------------------------------------------------
4980
4981                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4982                 aGroup->CreateOnDisk();
4983
4984                 // in aGroup, create 5 datasets to contain:
4985                 // "Nodes on Edges" - ID of node on edge
4986                 // "Edge positions" - U parameter on node on edge
4987                 // "Nodes on Faces" - ID of node on face
4988                 // "Face U positions" - U parameter of node on face
4989                 // "Face V positions" - V parameter of node on face
4990
4991                 // Find out nb of nodes on edges and faces
4992                 // Collect corresponding sub-meshes
4993                 int nbEdgeNodes = 0, nbFaceNodes = 0;
4994                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4995                 // loop on SMESHDS_SubMesh'es
4996                 while ( smIt->more() )
4997                 {
4998                   SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4999                   if ( aSubMesh->IsComplexSubmesh() )
5000                     continue; // submesh containing other submeshs
5001                   int nbNodes = aSubMesh->NbNodes();
5002                   if ( nbNodes == 0 ) continue;
5003
5004                   int aShapeID = aSubMesh->GetID();
5005                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5006                     continue;
5007                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5008                   // write only SMDS_FacePosition and SMDS_EdgePosition
5009                   switch ( aShapeType ) {
5010                   case TopAbs_FACE:
5011                     nbFaceNodes += nbNodes;
5012                     aFaceSM.push_back( aSubMesh );
5013                     break;
5014                   case TopAbs_EDGE:
5015                     nbEdgeNodes += nbNodes;
5016                     aEdgeSM.push_back( aSubMesh );
5017                     break;
5018                   default:
5019                     continue;
5020                   }
5021                 }
5022                 // Treat positions on edges or faces
5023                 for ( int onFace = 0; onFace < 2; onFace++ )
5024                 {
5025                   // Create arrays to store in datasets
5026                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5027                   if (!nbNodes) continue;
5028                   int* aNodeIDs = new int [ nbNodes ];
5029                   double* aUPos = new double [ nbNodes ];
5030                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5031
5032                   // Fill arrays
5033                   // loop on sub-meshes
5034                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5035                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5036                   for ( ; itSM != pListSM->end(); itSM++ )
5037                   {
5038                     SMESHDS_SubMesh* aSubMesh = (*itSM);
5039
5040                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5041                     // loop on nodes in aSubMesh
5042                     while ( itNode->more() )
5043                     {
5044                       //node ID
5045                       const SMDS_MeshNode* node = itNode->next();
5046                       aNodeIDs [ iNode ] = node->GetID();
5047
5048                       // Position
5049                       const SMDS_PositionPtr pos = node->GetPosition();
5050                       if ( onFace ) { // on FACE
5051                         SMDS_FacePositionPtr fPos = pos;
5052                         if ( fPos ) {
5053                           aUPos[ iNode ] = fPos->GetUParameter();
5054                           aVPos[ iNode ] = fPos->GetVParameter();
5055                           iNode++;
5056                         }
5057                         else
5058                           nbNodes--;
5059                       }
5060                       else { // on EDGE
5061                         SMDS_EdgePositionPtr ePos = pos;
5062                         if ( ePos ) {
5063                           aUPos[ iNode ] = ePos->GetUParameter();
5064                           iNode++;
5065                         }
5066                         else
5067                           nbNodes--;
5068                       }
5069                     } // loop on nodes in aSubMesh
5070                   } // loop on sub-meshes
5071
5072                   // Write datasets
5073                   if ( nbNodes )
5074                   {
5075                     aSize[ 0 ] = nbNodes;
5076                     // IDS
5077                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5078                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5079                     aDataset->CreateOnDisk();
5080                     aDataset->WriteOnDisk( aNodeIDs );
5081                     aDataset->CloseOnDisk();
5082
5083                     // U Positions
5084                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
5085                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5086                     aDataset->CreateOnDisk();
5087                     aDataset->WriteOnDisk( aUPos );
5088                     aDataset->CloseOnDisk();
5089                     // V Positions
5090                     if ( onFace ) {
5091                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5092                       aDataset->CreateOnDisk();
5093                       aDataset->WriteOnDisk( aVPos );
5094                       aDataset->CloseOnDisk();
5095                     }
5096                   }
5097                   delete [] aNodeIDs;
5098                   delete [] aUPos;
5099                   if ( aVPos ) delete [] aVPos;
5100
5101                 } // treat positions on edges or faces
5102
5103                 // close "Node Positions" group
5104                 aGroup->CloseOnDisk();
5105
5106               } // if ( there are submeshes in SMESHDS_Mesh )
5107             } // if ( hasData )
5108
5109             // close mesh HDF group
5110             aTopGroup->CloseOnDisk();
5111           }
5112         }
5113       }
5114     }
5115   }
5116
5117   // close HDF file
5118   aFile->CloseOnDisk();
5119   delete aFile;
5120
5121   // Convert temporary files to stream
5122   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5123
5124   // Remove temporary files and directory
5125   if ( !isMultiFile )
5126     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5127
5128   return aStreamFile._retn();
5129 }
5130
5131 //=============================================================================
5132 /*!
5133  *  SMESH_Gen_i::SaveASCII
5134  *
5135  *  Save SMESH module's data in ASCII format
5136  */
5137 //=============================================================================
5138
5139 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5140                                            const char*              theURL,
5141                                            bool                     isMultiFile ) {
5142   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5143   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5144   return aStreamFile._retn();
5145
5146   //after usual saving needs to encipher binary to text string
5147   //Any binary symbol will be represent as "|xx" () hexadecimal format number
5148   int size = aStreamFile.in().length();
5149   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5150   for ( int i = 0; i < size; i++ )
5151     sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5152
5153   buffer[size * 3] = '\0';
5154
5155   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5156
5157   return anAsciiStreamFile._retn();
5158 }
5159
5160 //=============================================================================
5161 /*!
5162  *  SMESH_Gen_i::Load
5163  *
5164  *  Load SMESH module's data
5165  */
5166 //=============================================================================
5167
5168 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5169                         const SALOMEDS::TMPFile& theStream,
5170                         const char*              theURL,
5171                         bool                     isMultiFile )
5172 {
5173   UpdateStudy(); // load geom data
5174   Kernel_Utils::Localizer loc;
5175
5176   SALOMEDS::Study_var aStudy = getStudyServant();
5177
5178   // Get temporary files location
5179   TCollection_AsciiString tmpDir =
5180     ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5181
5182   // Convert the stream into sequence of files to process
5183   SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5184                                                                          tmpDir.ToCString(),
5185                                                                          isMultiFile );
5186   TCollection_AsciiString aStudyName( "" );
5187   if ( isMultiFile ) {
5188     CORBA::WString_var url = aStudy->URL();
5189     aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5190   }
5191   // Set names of temporary files
5192   TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5193   TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5194
5195   int size;
5196   HDFfile*    aFile;
5197   HDFdataset* aDataset;
5198   HDFgroup*   aTopGroup;
5199   HDFgroup*   aGroup;
5200   HDFgroup*   aSubGroup;
5201   HDFgroup*   aSubSubGroup;
5202
5203   // Read data
5204   // ---> open HDF file
5205   aFile = new HDFfile( (char*) filename.ToCString() );
5206   try {
5207     aFile->OpenOnDisk( HDF_RDONLY );
5208   }
5209   catch ( HDFexception ) {
5210     INFOS( "Load(): " << filename << " not found!" );
5211     return false;
5212   }
5213
5214   TPythonDump pd(this); // prevent dump during loading
5215
5216   // For PAL13473 ("Repetitive mesh") implementation.
5217   // New dependencies between SMESH objects are established:
5218   // now hypotheses can refer to meshes, shapes and other hypotheses.
5219   // To keep data consistent, the following order of data restoration
5220   // imposed:
5221   // 1. Create hypotheses
5222   // 2. Create all meshes
5223   // 3. Load hypotheses' data
5224   // 4. All the rest
5225
5226   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
5227   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
5228   list< SMESH::Filter_var >                      filters;
5229
5230   // get total number of top-level groups
5231   int aNbGroups = aFile->nInternalObjects();
5232   if ( aNbGroups > 0 ) {
5233     // --> in first turn we should read&create hypotheses
5234     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5235       // open hypotheses root HDF group
5236       aTopGroup = new HDFgroup( "Hypotheses", aFile );
5237       aTopGroup->OpenOnDisk();
5238
5239       // get number of hypotheses
5240       int aNbObjects = aTopGroup->nInternalObjects();
5241       for ( int j = 0; j < aNbObjects; j++ ) {
5242         // try to identify hypothesis
5243         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5244         aTopGroup->InternalObjectIndentify( j, hypGrpName );
5245
5246         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5247           // open hypothesis group
5248           aGroup = new HDFgroup( hypGrpName, aTopGroup );
5249           aGroup->OpenOnDisk();
5250
5251           // --> get hypothesis id
5252           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5253           string hypname;
5254           string libname;
5255           string hypdata;
5256
5257           // get number of datasets
5258           int aNbSubObjects = aGroup->nInternalObjects();
5259           for ( int k = 0; k < aNbSubObjects; k++ ) {
5260             // identify dataset
5261             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5262             aGroup->InternalObjectIndentify( k, name_of_subgroup );
5263             // --> get hypothesis name
5264             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
5265               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5266               aDataset->OpenOnDisk();
5267               size = aDataset->GetSize();
5268               char* hypname_str = new char[ size ];
5269               aDataset->ReadFromDisk( hypname_str );
5270               hypname = string( hypname_str );
5271               delete [] hypname_str;
5272               aDataset->CloseOnDisk();
5273             }
5274             // --> get hypothesis plugin library name
5275             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
5276               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5277               aDataset->OpenOnDisk();
5278               size = aDataset->GetSize();
5279               char* libname_str = new char[ size ];
5280               aDataset->ReadFromDisk( libname_str );
5281               if(MYDEBUG) SCRUTE( libname_str );
5282               libname = string( libname_str );
5283               delete [] libname_str;
5284               aDataset->CloseOnDisk();
5285             }
5286             // --> get hypothesis data
5287             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
5288               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5289               aDataset->OpenOnDisk();
5290               size = aDataset->GetSize();
5291               char* hypdata_str = new char[ size ];
5292               aDataset->ReadFromDisk( hypdata_str );
5293               hypdata = string( hypdata_str );
5294               delete [] hypdata_str;
5295               aDataset->CloseOnDisk();
5296             }
5297           }
5298           // close hypothesis HDF group
5299           aGroup->CloseOnDisk();
5300
5301           // --> restore hypothesis from data
5302           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5303             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5304                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5305             SMESH::SMESH_Hypothesis_var myHyp;
5306
5307             try { // protect persistence mechanism against exceptions
5308               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5309             }
5310             catch (...) {
5311               INFOS( "Exception during hypothesis creation" );
5312             }
5313
5314             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5315             if ( myImpl ) {
5316               // myImpl->LoadFrom( hypdata.c_str() );
5317               hypDataList.push_back( make_pair( myImpl, hypdata ));
5318               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5319               int newId = myStudyContext->findId( iorString.in() );
5320               myStudyContext->mapOldToNew( id, newId );
5321             }
5322             else
5323               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5324           }
5325         }
5326       }
5327       // close hypotheses root HDF group
5328       aTopGroup->CloseOnDisk();
5329       aTopGroup = 0;
5330     }
5331
5332     // --> then we should read&create algorithms
5333     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5334       // open algorithms root HDF group
5335       aTopGroup = new HDFgroup( "Algorithms", aFile );
5336       aTopGroup->OpenOnDisk();
5337
5338       // get number of algorithms
5339       int aNbObjects = aTopGroup->nInternalObjects();
5340       for ( int j = 0; j < aNbObjects; j++ ) {
5341         // try to identify algorithm
5342         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5343         aTopGroup->InternalObjectIndentify( j, hypGrpName );
5344
5345         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5346           // open algorithm group
5347           aGroup = new HDFgroup( hypGrpName, aTopGroup );
5348           aGroup->OpenOnDisk();
5349
5350           // --> get algorithm id
5351           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5352           string hypname;
5353           string libname;
5354           string hypdata;
5355
5356           // get number of datasets
5357           int aNbSubObjects = aGroup->nInternalObjects();
5358           for ( int k = 0; k < aNbSubObjects; k++ ) {
5359             // identify dataset
5360             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5361             aGroup->InternalObjectIndentify( k, name_of_subgroup );
5362             // --> get algorithm name
5363             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
5364               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5365               aDataset->OpenOnDisk();
5366               size = aDataset->GetSize();
5367               char* hypname_str = new char[ size ];
5368               aDataset->ReadFromDisk( hypname_str );
5369               hypname = string( hypname_str );
5370               delete [] hypname_str;
5371               aDataset->CloseOnDisk();
5372             }
5373             // --> get algorithm plugin library name
5374             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
5375               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5376               aDataset->OpenOnDisk();
5377               size = aDataset->GetSize();
5378               char* libname_str = new char[ size ];
5379               aDataset->ReadFromDisk( libname_str );
5380               if(MYDEBUG) SCRUTE( libname_str );
5381               libname = string( libname_str );
5382               delete [] libname_str;
5383               aDataset->CloseOnDisk();
5384             }
5385             // --> get algorithm data
5386             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
5387               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5388               aDataset->OpenOnDisk();
5389               size = aDataset->GetSize();
5390               char* hypdata_str = new char[ size ];
5391               aDataset->ReadFromDisk( hypdata_str );
5392               if(MYDEBUG) SCRUTE( hypdata_str );
5393               hypdata = string( hypdata_str );
5394               delete [] hypdata_str;
5395               aDataset->CloseOnDisk();
5396             }
5397           }
5398           // close algorithm HDF group
5399           aGroup->CloseOnDisk();
5400
5401           // --> restore algorithm from data
5402           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5403             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5404                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5405             SMESH::SMESH_Hypothesis_var myHyp;
5406
5407             try { // protect persistence mechanism against exceptions
5408               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5409             }
5410             catch( SALOME::SALOME_Exception& ex )
5411             {
5412               INFOS( "Exception during hypothesis creation: " << ex.details.text );
5413             }
5414             catch (...) {
5415               INFOS( "Exception during hypothesis creation" );
5416             }
5417
5418             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5419             if ( myImpl ) {
5420               //myImpl->LoadFrom( hypdata.c_str() );
5421               hypDataList.push_back( make_pair( myImpl, hypdata ));
5422               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5423               int newId = myStudyContext->findId( iorString.in() );
5424               myStudyContext->mapOldToNew( id, newId );
5425             }
5426             else
5427               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5428           }
5429         }
5430       }
5431       // close algorithms root HDF group
5432       aTopGroup->CloseOnDisk();
5433       aTopGroup = 0;
5434     }
5435
5436     // --> the rest groups should be meshes
5437     for ( int i = 0; i < aNbGroups; i++ ) {
5438       // identify next group
5439       char meshName[ HDF_NAME_MAX_LEN+1 ];
5440       aFile->InternalObjectIndentify( i, meshName );
5441
5442       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5443         // --> get mesh id
5444         int id = atoi( string( meshName ).substr( 4 ).c_str() );
5445         if ( id <= 0 )
5446           continue;
5447
5448         // open mesh HDF group
5449         aTopGroup = new HDFgroup( meshName, aFile );
5450         aTopGroup->OpenOnDisk();
5451
5452         // get number of child HDF objects
5453         int aNbObjects = aTopGroup->nInternalObjects();
5454         if ( aNbObjects > 0 ) {
5455           // create mesh
5456           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5457           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5458           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5459           if ( !myNewMeshImpl )
5460             continue;
5461           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5462
5463           CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5464           int newId = myStudyContext->findId( iorString.in() );
5465           myStudyContext->mapOldToNew( id, newId );
5466
5467           // ouv : NPAL12872
5468           // try to read and set auto color flag
5469           char aMeshAutoColorName[ 30 ];
5470           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5471           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5472           {
5473             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5474             aDataset->OpenOnDisk();
5475             size = aDataset->GetSize();
5476             int* anAutoColor = new int[ size ];
5477             aDataset->ReadFromDisk( anAutoColor );
5478             aDataset->CloseOnDisk();
5479             myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5480             delete [] anAutoColor;
5481           }
5482
5483           // try to read and set reference to shape
5484           GEOM::GEOM_Object_var aShapeObject;
5485           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5486             // load mesh "Ref on shape" - it's an entry to SObject
5487             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5488             aDataset->OpenOnDisk();
5489             size = aDataset->GetSize();
5490             char* refFromFile = new char[ size ];
5491             aDataset->ReadFromDisk( refFromFile );
5492             aDataset->CloseOnDisk();
5493             if ( strlen( refFromFile ) > 0 ) {
5494               SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5495               CORBA::Object_var  shapeObject = SObjectToObject( shapeSO );
5496               if ( !CORBA::is_nil( shapeObject ) ) {
5497                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5498                 if ( !aShapeObject->_is_nil() )
5499                   myNewMeshImpl->SetShape( aShapeObject );
5500               }
5501             }
5502             delete [] refFromFile;
5503           }
5504
5505           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5506           if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5507           {
5508             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5509             aDataset->OpenOnDisk();
5510             size = aDataset->GetSize();
5511             int* meshPersistentId = new int[ size ];
5512             aDataset->ReadFromDisk( meshPersistentId );
5513             aDataset->CloseOnDisk();
5514             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5515             delete [] meshPersistentId;
5516           }
5517
5518           // Restore SMESH_Mesh_i::_mainShapeTick
5519           if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5520           {
5521             aDataset = new HDFdataset( "shapeTick", aTopGroup );
5522             aDataset->OpenOnDisk();
5523             int* shapeTick = & myNewMeshImpl->MainShapeTick();
5524             aDataset->ReadFromDisk( shapeTick );
5525             aDataset->CloseOnDisk();
5526           }
5527
5528           // Restore file info
5529           if ( aTopGroup->ExistInternalObject( "file info" ))
5530           {
5531             aDataset = new HDFdataset( "file info", aTopGroup );
5532             aDataset->OpenOnDisk();
5533             size = aDataset->GetSize();
5534             std::string info( size, ' ');
5535             aDataset->ReadFromDisk( (char*) info.data() );
5536             aDataset->CloseOnDisk();
5537             myNewMeshImpl->FileInfoFromString( info );
5538           }
5539         }
5540       }
5541     } // reading MESHes
5542
5543     // As all object that can be referred by hypothesis are created,
5544     // we can restore hypothesis data
5545
5546     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5547     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5548     {
5549       SMESH_Hypothesis_i* hyp  = hyp_data->first;
5550       string &            data = hyp_data->second;
5551       hyp->LoadFrom( data.c_str() );
5552     }
5553
5554     // Restore the rest mesh data
5555
5556     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5557     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5558     {
5559       aTopGroup                   = meshi_group->second;
5560       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5561
5562       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5563       bool hasData = false;
5564
5565       // get mesh old id
5566       CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5567       int newId = myStudyContext->findId( iorString.in() );
5568       int meshOldId = myStudyContext->getOldId( newId );
5569
5570       // try to find mesh data dataset
5571       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5572         // load mesh "has data" flag
5573         aDataset = new HDFdataset( "Has data", aTopGroup );
5574         aDataset->OpenOnDisk();
5575         size = aDataset->GetSize();
5576         char* strHasData = new char[ size ];
5577         aDataset->ReadFromDisk( strHasData );
5578         aDataset->CloseOnDisk();
5579         if ( strcmp( strHasData, "1") == 0 ) {
5580           hasData = true;
5581         }
5582         delete [] strHasData;
5583       }
5584
5585       // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5586       // nodes and elements are not yet put into sub-meshes)
5587       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5588         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5589         aGroup->OpenOnDisk();
5590         // get number of applied algorithms
5591         int aNbSubObjects = aGroup->nInternalObjects();
5592         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5593         for ( int j = 0; j < aNbSubObjects; j++ ) {
5594           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5595           aGroup->InternalObjectIndentify( j, name_dataset );
5596           // check if it is an algorithm
5597           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5598             aDataset = new HDFdataset( name_dataset, aGroup );
5599             aDataset->OpenOnDisk();
5600             size = aDataset->GetSize();
5601             char* refFromFile = new char[ size ];
5602             aDataset->ReadFromDisk( refFromFile );
5603             aDataset->CloseOnDisk();
5604             // san - it is impossible to recover applied algorithms using their entries within Load() method
5605             int id = atoi( refFromFile );
5606             delete [] refFromFile;
5607             string anIOR = myStudyContext->getIORbyOldId( id );
5608             if ( !anIOR.empty() ) {
5609               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5610               if ( !CORBA::is_nil( hypObject ) ) {
5611                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5612                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5613                                            || !myNewMeshImpl->HasShapeToMesh()) )
5614                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5615               }
5616             }
5617           }
5618         }
5619         aGroup->CloseOnDisk();
5620       }
5621
5622       // try to get applied hypotheses
5623       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5624         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5625         aGroup->OpenOnDisk();
5626         // get number of applied hypotheses
5627         int aNbSubObjects = aGroup->nInternalObjects();
5628         for ( int j = 0; j < aNbSubObjects; j++ ) {
5629           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5630           aGroup->InternalObjectIndentify( j, name_dataset );
5631           // check if it is a hypothesis
5632           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5633             aDataset = new HDFdataset( name_dataset, aGroup );
5634             aDataset->OpenOnDisk();
5635             size = aDataset->GetSize();
5636             char* refFromFile = new char[ size ];
5637             aDataset->ReadFromDisk( refFromFile );
5638             aDataset->CloseOnDisk();
5639             // san - it is impossible to recover applied hypotheses using their entries within Load() method
5640             int id = atoi( refFromFile );
5641             delete [] refFromFile;
5642             string anIOR = myStudyContext->getIORbyOldId( id );
5643             if ( !anIOR.empty() ) {
5644               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5645               if ( !CORBA::is_nil( hypObject ) ) {
5646                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5647                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5648                                            || !myNewMeshImpl->HasShapeToMesh()) )
5649                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5650               }
5651             }
5652           }
5653         }
5654         aGroup->CloseOnDisk();
5655       }
5656
5657       // --> try to find SUB-MESHES containers for each type of submesh
5658       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5659         const char* name_meshgroup = 0;
5660         if ( j == GetSubMeshOnVertexTag() )
5661           name_meshgroup = "SubMeshes On Vertex";
5662         else if ( j == GetSubMeshOnEdgeTag() )
5663           name_meshgroup = "SubMeshes On Edge";
5664         else if ( j == GetSubMeshOnWireTag() )
5665           name_meshgroup = "SubMeshes On Wire";
5666         else if ( j == GetSubMeshOnFaceTag() )
5667           name_meshgroup = "SubMeshes On Face";
5668         else if ( j == GetSubMeshOnShellTag() )
5669           name_meshgroup = "SubMeshes On Shell";
5670         else if ( j == GetSubMeshOnSolidTag() )
5671           name_meshgroup = "SubMeshes On Solid";
5672         else if ( j == GetSubMeshOnCompoundTag() )
5673           name_meshgroup = "SubMeshes On Compound";
5674
5675         // try to get submeshes container HDF group
5676         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5677           // open submeshes containers HDF group
5678           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5679           aGroup->OpenOnDisk();
5680
5681           // get number of submeshes
5682           int aNbSubMeshes = aGroup->nInternalObjects();
5683           for ( int k = 0; k < aNbSubMeshes; k++ ) {
5684             // identify submesh
5685             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5686             aGroup->InternalObjectIndentify( k, name_submeshgroup );
5687             if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5688               // --> get submesh id
5689               int subid = atoi( name_submeshgroup + 7 );
5690               if ( subid <= 0 )
5691                 continue;
5692               // open submesh HDF group
5693               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5694               aSubGroup->OpenOnDisk();
5695
5696               // try to read and set reference to subshape
5697               GEOM::GEOM_Object_var aSubShapeObject;
5698               SMESH::SMESH_subMesh_var aSubMesh;
5699
5700               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5701                 // load submesh "Ref on shape" - it's an entry to SObject
5702                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5703                 aDataset->OpenOnDisk();
5704                 size = aDataset->GetSize();
5705                 char* refFromFile = new char[ size ];
5706                 aDataset->ReadFromDisk( refFromFile );
5707                 aDataset->CloseOnDisk();
5708                 if ( strlen( refFromFile ) > 0 ) {
5709                   SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5710                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5711                   if ( !CORBA::is_nil( subShapeObject ) ) {
5712                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5713                     if ( !aSubShapeObject->_is_nil() )
5714                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
5715                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5716                     if ( aSubMesh->_is_nil() )
5717                       continue;
5718                     string iorSubString = GetORB()->object_to_string( aSubMesh );
5719                     int newSubId = myStudyContext->findId( iorSubString );
5720                     myStudyContext->mapOldToNew( subid, newSubId );
5721                   }
5722                 }
5723                 delete [] refFromFile;
5724               }
5725
5726               if ( aSubMesh->_is_nil() )
5727                 continue;
5728
5729               // try to get applied algorithms
5730               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5731                 // open "applied algorithms" HDF group
5732                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5733                 aSubSubGroup->OpenOnDisk();
5734                 // get number of applied algorithms
5735                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5736                 for ( int l = 0; l < aNbSubObjects; l++ ) {
5737                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5738                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5739                   // check if it is an algorithm
5740                   if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5741                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5742                     aDataset->OpenOnDisk();
5743                     size = aDataset->GetSize();
5744                     char* refFromFile = new char[ size ];
5745                     aDataset->ReadFromDisk( refFromFile );
5746                     aDataset->CloseOnDisk();
5747
5748                     int id = atoi( refFromFile );
5749                     string anIOR = myStudyContext->getIORbyOldId( id );
5750                     if ( !anIOR.empty() ) {
5751                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5752                       if ( !CORBA::is_nil( hypObject ) ) {
5753                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5754                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5755                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5756                       }
5757                     }
5758                     delete [] refFromFile;
5759                   }
5760                 }
5761                 // close "applied algorithms" HDF group
5762                 aSubSubGroup->CloseOnDisk();
5763               }
5764
5765               // try to get applied hypotheses
5766               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5767                 // open "applied hypotheses" HDF group
5768                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5769                 aSubSubGroup->OpenOnDisk();
5770                 // get number of applied hypotheses
5771                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5772                 for ( int l = 0; l < aNbSubObjects; l++ ) {
5773                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5774                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5775                   // check if it is a hypothesis
5776                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5777                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5778                     aDataset->OpenOnDisk();
5779                     size = aDataset->GetSize();
5780                     char* refFromFile = new char[ size ];
5781                     aDataset->ReadFromDisk( refFromFile );
5782                     aDataset->CloseOnDisk();
5783
5784                     int id = atoi( refFromFile );
5785                     string anIOR = myStudyContext->getIORbyOldId( id );
5786                     if ( !anIOR.empty() ) {
5787                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5788                       if ( !CORBA::is_nil( hypObject ) ) {
5789                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5790                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5791                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5792                       }
5793                     }
5794                     delete [] refFromFile;
5795                   }
5796                 }
5797                 // close "APPLIED HYPOTHESES" hdf group
5798                 aSubSubGroup->CloseOnDisk();
5799               }
5800
5801               // close SUB-MESH hdf group
5802               aSubGroup->CloseOnDisk();
5803             }
5804           }
5805           // close SUB-MESHES containers hdf group
5806           aGroup->CloseOnDisk();
5807         }
5808       }
5809
5810       // try to get GROUPS
5811       for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5812         char name_group[ 30 ];
5813         if ( ii == GetNodeGroupsTag() )
5814           strcpy( name_group, "Groups of Nodes" );
5815         else if ( ii == GetEdgeGroupsTag() )
5816           strcpy( name_group, "Groups of Edges" );
5817         else if ( ii == GetFaceGroupsTag() )
5818           strcpy( name_group, "Groups of Faces" );
5819         else if ( ii == GetVolumeGroupsTag() )
5820           strcpy( name_group, "Groups of Volumes" );
5821         else if ( ii == Get0DElementsGroupsTag() )
5822           strcpy( name_group, "Groups of 0D Elements" );
5823         else if ( ii == GetBallElementsGroupsTag() )
5824           strcpy( name_group, "Groups of Balls" );
5825
5826         if ( aTopGroup->ExistInternalObject( name_group ) ) {
5827           aGroup = new HDFgroup( name_group, aTopGroup );
5828           aGroup->OpenOnDisk();
5829           // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5830           // within aGroup->ExistInternalObject( name )
5831           std::vector< std::string > subNames;
5832           TColStd_MapOfAsciiString mapOfNames;
5833           aGroup->GetAllObjects( subNames );
5834           for ( size_t iN = 0; iN < subNames.size(); ++iN )
5835             mapOfNames.Add( subNames[ iN ].c_str() );
5836           // loop on groups
5837           for ( size_t j = 0; j < subNames.size(); j++ ) {
5838             const std::string& name_dataset = subNames[ j ];
5839             // check if it is a group
5840             if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5841               // --> get group id
5842               char * endptr;
5843               int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5844               if ( subid <= 0 )
5845                 continue;
5846               int groupID = -1; // group local ID (also persistent)
5847               if ( *endptr )
5848                 groupID = atoi( endptr + 1 );
5849               aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5850               aDataset->OpenOnDisk();
5851
5852               // Retrieve actual group name
5853               size = aDataset->GetSize();
5854               char* nameFromFile = new char[ size ];
5855               aDataset->ReadFromDisk( nameFromFile );
5856               aDataset->CloseOnDisk();
5857
5858               // Try to find a shape reference
5859               TopoDS_Shape aShape;
5860               char aRefName[ 30 ];
5861               sprintf( aRefName, "Ref on shape %d", subid);
5862               if ( mapOfNames.Contains( aRefName ))
5863               {
5864                 // load mesh "Ref on shape" - it's an entry to SObject
5865                 aDataset = new HDFdataset( aRefName, aGroup );
5866                 aDataset->OpenOnDisk();
5867                 size = aDataset->GetSize();
5868                 char* refFromFile = new char[ size ];
5869                 aDataset->ReadFromDisk( refFromFile );
5870                 aDataset->CloseOnDisk();
5871                 if ( strlen( refFromFile ) > 0 ) {
5872                   SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5873                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5874                   if ( !CORBA::is_nil( shapeObject ) ) {
5875                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5876                     if ( !aShapeObject->_is_nil() )
5877                       aShape = GeomObjectToShape( aShapeObject );
5878                   }
5879                 }
5880                 delete [] refFromFile;
5881               }
5882               // Try to read a filter of SMESH_GroupOnFilter
5883               SMESH::Filter_var filter;
5884               SMESH_PredicatePtr predicate;
5885               std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5886               if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5887               {
5888                 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5889                 aDataset->OpenOnDisk();
5890                 size = aDataset->GetSize();
5891                 char* persistStr = new char[ size ];
5892                 aDataset->ReadFromDisk( persistStr );
5893                 aDataset->CloseOnDisk();
5894                 if ( strlen( persistStr ) > 0 ) {
5895                   filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5896                   predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5897                   filters.push_back( filter );
5898                 }
5899                 delete [] persistStr;
5900               }
5901
5902               // Create group servant
5903               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5904               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5905                 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5906               delete [] nameFromFile;
5907               // Obtain a SMESHDS_Group object
5908               if ( aNewGroup->_is_nil() )
5909                 continue;
5910
5911               string iorSubString = GetORB()->object_to_string( aNewGroup );
5912               int        newSubId = myStudyContext->findId( iorSubString );
5913               myStudyContext->mapOldToNew( subid, newSubId );
5914
5915               SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5916               if ( !aGroupImpl )
5917                 continue;
5918
5919               if ( SMESH_GroupOnFilter_i* aFilterGroup =
5920                    dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5921               {
5922                 aFilterGroup->SetFilter( filter );
5923                 filter->UnRegister();
5924               }
5925               SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5926               if ( !aGroupBaseDS )
5927                 continue;
5928
5929               aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5930
5931               // ouv : NPAL12872
5932               // Read color of the group
5933               char aGroupColorName[ 30 ];
5934               sprintf( aGroupColorName, "ColorGroup %d", subid);
5935               if ( mapOfNames.Contains( aGroupColorName ))
5936               {
5937                 aDataset = new HDFdataset( aGroupColorName, aGroup );
5938                 aDataset->OpenOnDisk();
5939                 size = aDataset->GetSize();
5940                 double* anRGB = new double[ size ];
5941                 aDataset->ReadFromDisk( anRGB );
5942                 aDataset->CloseOnDisk();
5943                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5944                 aGroupBaseDS->SetColor( aColor );
5945                 delete [] anRGB;
5946               }
5947             }
5948           }
5949           aGroup->CloseOnDisk();
5950         }
5951       } // reading GROUPs
5952
5953       // instead of reading mesh data, we read only brief information of all
5954       // objects: mesh, groups, sub-meshes (issue 0021208)
5955       if ( hasData )
5956       {
5957         SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5958                                          meshfile.ToCString(), filename.ToCString(),
5959                                          !isMultiFile );
5960       }
5961
5962       // read Sub-Mesh ORDER if any
5963       if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5964         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5965         aDataset->OpenOnDisk();
5966         size = aDataset->GetSize();
5967         int* smIDs = new int[ size ];
5968         aDataset->ReadFromDisk( smIDs );
5969         aDataset->CloseOnDisk();
5970         TListOfListOfInt anOrderIds;
5971         anOrderIds.push_back( TListOfInt() );
5972         for ( int i = 0; i < size; i++ )
5973           if ( smIDs[ i ] < 0 ) // is separator
5974             anOrderIds.push_back( TListOfInt() );
5975           else
5976             anOrderIds.back().push_back(smIDs[ i ]);
5977
5978         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5979         delete [] smIDs;
5980       }
5981       if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
5982       {
5983         aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
5984         aDataset->OpenOnDisk();
5985         size = aDataset->GetSize();
5986         std::string dataString; dataString.resize( size );
5987         aDataset->ReadFromDisk((char*) dataString.data() );
5988         aDataset->CloseOnDisk();
5989
5990         std::istringstream istream( dataString.data() );
5991         boost::archive::text_iarchive archive( istream );
5992         std::list< std::list< std::string > > orderEntryLists;
5993         try {
5994           archive >> orderEntryLists;
5995         }
5996         catch (...) {}
5997
5998         TListOfListOfInt anOrderIds;
5999         for ( const std::list< std::string >& entryList : orderEntryLists )
6000         {
6001           anOrderIds.emplace_back();
6002           for ( const std::string & entry : entryList )
6003           {
6004             GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6005             TopoDS_Shape       shape = GeomObjectToShape( go );
6006             if ( SMESH_subMesh*   sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6007               anOrderIds.back().emplace_back( sm->GetId() );
6008           }
6009         }
6010         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6011       }
6012     } // loop on meshes
6013
6014     // update hyps needing full mesh data restored (issue 20918)
6015     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6016     {
6017       SMESH_Hypothesis_i* hyp  = hyp_data->first;
6018       hyp->UpdateAsMeshesRestored();
6019     }
6020
6021     // notify algos on completed restoration to set sub-mesh event listeners
6022     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6023     {
6024       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6025       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
6026
6027       TopoDS_Shape myLocShape;
6028       if(myLocMesh.HasShapeToMesh())
6029         myLocShape = myLocMesh.GetShapeToMesh();
6030       else
6031         myLocShape = SMESH_Mesh::PseudoShape();
6032
6033       myLocMesh.GetSubMesh(myLocShape)->
6034         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6035     }
6036
6037     // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6038     list< SMESH::Filter_var >::iterator f = filters.begin();
6039     for ( ; f != filters.end(); ++f )
6040       if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6041         fi->FindBaseObjects();
6042
6043
6044     // close mesh group
6045     if(aTopGroup)
6046       aTopGroup->CloseOnDisk();
6047   }
6048   // close HDF file
6049   aFile->CloseOnDisk();
6050   delete aFile;
6051
6052   // Remove temporary files created from the stream
6053   if ( !isMultiFile )
6054   {
6055     SMESH_File meshFile( meshfile.ToCString() );
6056     if ( !meshFile ) // no meshfile exists
6057     {
6058       SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6059     }
6060     else
6061     {
6062       Engines::Container_var container = GetContainerRef();
6063       if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6064       {
6065         container_i->registerTemporaryFile( filename.ToCString() );
6066         container_i->registerTemporaryFile( meshfile.ToCString() );
6067         container_i->registerTemporaryFile( tmpDir.ToCString() );
6068       }
6069     }
6070   }
6071
6072   // creation of tree nodes for all data objects in the study
6073   // to support tree representation customization and drag-n-drop:
6074   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6075   if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6076     useCaseBuilder->SetRootCurrent();
6077     useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6078     SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6079     for (it->InitEx(true); it->More(); it->Next()) {
6080       useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6081     }
6082   }
6083
6084   return true;
6085 }
6086
6087 //=============================================================================
6088 /*!
6089  *  SMESH_Gen_i::LoadASCII
6090  *
6091  *  Load SMESH module's data in ASCII format
6092  */
6093 //=============================================================================
6094
6095 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6096                              const SALOMEDS::TMPFile& theStream,
6097                              const char*              theURL,
6098                              bool                     isMultiFile ) {
6099   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6100   return Load( theComponent, theStream, theURL, isMultiFile );
6101
6102   //before call main ::Load method it's need for decipher text format to
6103   //binary ( "|xx" => x' )
6104   int size = theStream.length();
6105   if ( int((size / 3 )*3) != size ) //error size of buffer
6106     return false;
6107
6108   int real_size = int(size / 3);
6109
6110   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6111   char tmp[3];
6112   tmp[2]='\0';
6113   unsigned int c = -1;
6114   for ( int i = 0; i < real_size; i++ )
6115   {
6116     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6117     sscanf( tmp, "%x", &c );
6118     sprintf( (char*)&(buffer[i]), "%c", (char)c );
6119   }
6120
6121   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6122
6123   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6124 }
6125
6126 //=============================================================================
6127 /*!
6128  *  SMESH_Gen_i::Close
6129  *
6130  *  Clears study-connected data when it is closed
6131  */
6132 //=============================================================================
6133
6134 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6135 {
6136   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6137
6138   // Clear study contexts data
6139   myStudyContext->Clear();
6140
6141   // remove the tmp files meshes are loaded from
6142   SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6143
6144   // Clean trace of API methods calls
6145   CleanPythonTrace();
6146
6147   return;
6148 }
6149
6150 //=============================================================================
6151 /*!
6152  *  SMESH_Gen_i::ComponentDataType
6153  *
6154  *  Get component data type
6155  */
6156 //=============================================================================
6157
6158 char* SMESH_Gen_i::ComponentDataType()
6159 {
6160   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6161   return CORBA::string_dup( "SMESH" );
6162 }
6163
6164
6165 //=============================================================================
6166 /*!
6167  *  SMESH_Gen_i::IORToLocalPersistentID
6168  *
6169  *  Transform data from transient form to persistent
6170  */
6171 //=============================================================================
6172
6173 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6174                                            const char*           IORString,
6175                                            CORBA::Boolean        /*isMultiFile*/,
6176                                            CORBA::Boolean        /*isASCII*/ )
6177 {
6178   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6179
6180   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6181     int anId = myStudyContext->findId( IORString );
6182     if ( anId ) {
6183       if(MYDEBUG) MESSAGE( "VSR " << anId )
6184       char strId[ 20 ];
6185       sprintf( strId, "%d", anId );
6186       return  CORBA::string_dup( strId );
6187     }
6188   }
6189   return CORBA::string_dup( "" );
6190 }
6191
6192 //=============================================================================
6193 /*!
6194  *  SMESH_Gen_i::LocalPersistentIDToIOR
6195  *
6196  *  Transform data from persistent form to transient
6197  */
6198 //=============================================================================
6199
6200 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6201                                            const char*           aLocalPersistentID,
6202                                            CORBA::Boolean        /*isMultiFile*/,
6203                                            CORBA::Boolean        /*isASCII*/ )
6204 {
6205   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6206
6207   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6208     int anId = atoi( aLocalPersistentID );
6209     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6210   }
6211   return CORBA::string_dup( "" );
6212 }
6213
6214 //=======================================================================
6215 //function : RegisterObject
6216 //purpose  :
6217 //=======================================================================
6218
6219 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6220 {
6221   if ( myStudyContext && !CORBA::is_nil( theObject )) {
6222     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6223     return myStudyContext->addObject( string( iorString.in() ) );
6224   }
6225   return 0;
6226 }
6227
6228 //================================================================================
6229 /*!
6230  * \brief Return id of registered object
6231   * \param theObject - the Object
6232   * \retval int - Object id
6233  */
6234 //================================================================================
6235
6236 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6237 {
6238   if ( myStudyContext && !CORBA::is_nil( theObject )) {
6239     string iorString = GetORB()->object_to_string( theObject );
6240     return myStudyContext->findId( iorString );
6241   }
6242   return 0;
6243 }
6244
6245 //=============================================================================
6246 /*!
6247  *  SMESH_Gen_i::SetName
6248  *
6249  *  Set a new object name
6250  */
6251 //=============================================================================
6252
6253 void SMESH_Gen_i::SetName(const char* theIOR,
6254                           const char* theName)
6255 {
6256   if ( theIOR && strcmp( theIOR, "" ) ) {
6257     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6258     SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6259     if ( !aSO->_is_nil() ) {
6260       SetName( aSO, theName );
6261     }
6262   }
6263 }
6264
6265 // Version information
6266 char* SMESH_Gen_i::getVersion()
6267 {
6268 #if SMESH_DEVELOPMENT
6269   return CORBA::string_dup(SMESH_VERSION_STR"dev");
6270 #else
6271   return CORBA::string_dup(SMESH_VERSION_STR);
6272 #endif
6273 }
6274
6275 //=================================================================================
6276 // function : Move()
6277 // purpose  : Moves objects to the specified position.
6278 //            Is used in the drag-n-drop functionality.
6279 //=================================================================================
6280
6281 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6282                         SALOMEDS::SObject_ptr      where,
6283                         CORBA::Long                row )
6284 {
6285   if ( CORBA::is_nil( where ) ) return;
6286
6287   SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6288   SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6289   SALOMEDS::SComponent_var father = where->GetFatherComponent();
6290   std::string dataType = father->ComponentDataType();
6291   if ( dataType != "SMESH" ) return; // not a SMESH component
6292
6293   SALOMEDS::SObject_var objAfter;
6294   if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6295     // insert at given row -> find insertion position
6296     SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6297     int i;
6298     for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6299     if ( i == row && useCaseIt->More() ) {
6300       objAfter = useCaseIt->Value();
6301     }
6302   }
6303
6304   for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6305     SALOMEDS::SObject_var sobj = what[i];
6306     if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6307     // insert the object to the use case tree
6308     if ( !CORBA::is_nil( objAfter ) )
6309       useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6310     else
6311       useCaseBuilder->AppendTo( where, sobj );        // append to the end of list
6312   }
6313 }
6314 //================================================================================
6315 /*!
6316  * \brief Returns true if algorithm can be used to mesh a given geometry
6317  *  \param [in] theAlgoType - the algorithm type
6318  *  \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6319  *  \param [in] theGeomObject - the geometry to mesh
6320  *  \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6321  *         else, returns \c True if at least one shape is meshable
6322  *  \return CORBA::Boolean - can or can't
6323  */
6324 //================================================================================
6325
6326 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char*           theAlgoType,
6327                                            const char*           theLibName,
6328                                            GEOM::GEOM_Object_ptr theGeomObject,
6329                                            CORBA::Boolean        toCheckAll)
6330 {
6331   SMESH_TRY;
6332
6333   std::string aPlatformLibName;
6334   GenericHypothesisCreator_i* aCreator =
6335     getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6336   if (aCreator)
6337   {
6338     TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6339     const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6340     return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6341   }
6342   else
6343   {
6344     return false;
6345   }
6346
6347   SMESH_CATCH( SMESH::doNothing );
6348
6349 #ifdef _DEBUG_
6350   cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6351 #endif
6352   return true;
6353 }
6354
6355 //================================================================================
6356 /*!
6357  * \brief Collect indices of elements, which are located inside the sphere
6358  */
6359 //================================================================================
6360
6361 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6362                                                  SMESH::ElementType     theElemType,
6363                                                  CORBA::Double         theX,
6364                                                  CORBA::Double         theY,
6365                                                  CORBA::Double         theZ,
6366                                                  CORBA::Double         theR)
6367 {
6368   SMESH::long_array_var aResult = new SMESH::long_array();
6369   if ( meshPart->_is_nil() )
6370     return aResult._retn();
6371
6372   // 1. Create geometrical object
6373   gp_Pnt aP( theX, theY, theZ );
6374   TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6375
6376   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6377
6378   if ( lst.size() > 0 ) {
6379     aResult->length( lst.size() );
6380     for ( size_t i = 0; i < lst.size(); i++ ) {
6381       aResult[i] = lst[i];
6382     }
6383   }
6384   return aResult._retn();
6385 }
6386
6387 //================================================================================
6388 /*!
6389  * \brief Collect indices of elements, which are located inside the box
6390  */
6391 //================================================================================
6392
6393 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6394                                               SMESH::ElementType        theElemType,
6395                                               CORBA::Double             theX1,
6396                                               CORBA::Double             theY1,
6397                                               CORBA::Double             theZ1,
6398                                               CORBA::Double             theX2,
6399                                               CORBA::Double             theY2,
6400                                               CORBA::Double             theZ2)
6401 {
6402   SMESH::long_array_var aResult = new SMESH::long_array();
6403   if( meshPart->_is_nil() )
6404     return aResult._retn();
6405
6406   TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6407                                              gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6408
6409   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6410
6411   if( lst.size() > 0 ) {
6412     aResult->length( lst.size() );
6413     for ( size_t i = 0; i < lst.size(); i++ ) {
6414       aResult[i] = lst[i];
6415     }
6416   }
6417   return aResult._retn();
6418 }
6419
6420 //================================================================================
6421 /*!
6422  * \brief Collect indices of elements, which are located inside the cylinder
6423  */
6424 //================================================================================
6425
6426 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6427                                                    SMESH::ElementType        theElemType,
6428                                                    CORBA::Double             theX,
6429                                                    CORBA::Double             theY,
6430                                                    CORBA::Double             theZ,
6431                                                    CORBA::Double             theDX,
6432                                                    CORBA::Double             theDY,
6433                                                    CORBA::Double             theDZ,
6434                                                    CORBA::Double             theH,
6435                                                    CORBA::Double             theR )
6436 {
6437   SMESH::long_array_var aResult = new SMESH::long_array();
6438   if( meshPart->_is_nil() )
6439     return aResult._retn();
6440
6441   gp_Pnt aP( theX, theY, theZ );
6442   gp_Vec aV( theDX, theDY, theDZ );
6443   gp_Ax2 anAxes (aP, aV);
6444
6445   TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6446
6447   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6448
6449   if( lst.size() > 0 ) {
6450     aResult->length( lst.size() );
6451     for ( size_t i = 0; i < lst.size(); i++ ) {
6452       aResult[i] = lst[i];
6453     }
6454   }
6455   return aResult._retn();
6456 }
6457
6458 //================================================================================
6459 /*!
6460  * \brief Collect indices of elements, which are located inside the geom object
6461  */
6462 //================================================================================
6463
6464 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6465                                            SMESH::ElementType        theElemType,
6466                                            GEOM::GEOM_Object_ptr     theGeom,
6467                                            CORBA::Double             theTolerance )
6468 {
6469   SMESH::long_array_var aResult = new SMESH::long_array();
6470   if( meshPart->_is_nil() || theGeom->_is_nil() )
6471     return aResult._retn();
6472
6473   TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6474
6475   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6476
6477   if( lst.size() > 0 ) {
6478     aResult->length( lst.size() );
6479     for ( size_t i = 0; i < lst.size(); i++ ) {
6480       aResult[i] = lst[i];
6481     }
6482   }
6483   return aResult._retn();
6484 }
6485
6486 //================================================================================
6487 /*!
6488  * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6489  */
6490 //================================================================================
6491
6492 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6493                                            SMESH::ElementType        theElemType,
6494                                            const TopoDS_Shape&       theShape,
6495                                            double*                   theTolerance) {
6496
6497   std::vector<long> res;
6498   SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6499
6500   if ( mesh->_is_nil() )
6501     return res;
6502
6503   SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6504   if ( !anImpl )
6505     return res;
6506
6507   const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6508
6509   if ( !meshDS )
6510     return res;
6511
6512   SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6513   SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6514   anElementsOnShape->SetAllNodes( true );
6515   anElementsOnShape->SetMesh( meshDS );
6516   anElementsOnShape->SetShape( theShape, aType );
6517
6518   if(theTolerance)
6519     anElementsOnShape->SetTolerance(*theTolerance);
6520
6521   SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6522   if ( !msource->_is_nil() ) { // Mesh case
6523     SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6524     if ( elemIt ) {
6525       while ( elemIt->more() ) {
6526         const SMDS_MeshElement* anElem = elemIt->next();
6527         long anId = anElem->GetID();
6528         if ( anElementsOnShape->IsSatisfy( anId ) )
6529           res.push_back( anId );
6530       }
6531     }
6532   }
6533   SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6534   if ( !gsource->_is_nil() ) {
6535     if(theElemType == SMESH::NODE) {
6536       SMESH::long_array_var nodes = gsource->GetNodeIDs();
6537       for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6538         if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6539           long anId = node->GetID();
6540           if ( anElementsOnShape->IsSatisfy( anId ) )
6541             res.push_back( anId );
6542         }
6543       }
6544     } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6545       SMESH::long_array_var elems = gsource->GetListOfID();
6546       for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6547         if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6548           long anId = elem->GetID();
6549           if ( anElementsOnShape->IsSatisfy( anId ) )
6550             res.push_back( anId );
6551         }
6552       }
6553     }
6554   }
6555   SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6556   if ( !smsource->_is_nil() ) {
6557     SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6558     for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6559       const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6560       if (elem) {
6561         long anId = elem->GetID();
6562         if ( anElementsOnShape->IsSatisfy( anId ) )
6563           res.push_back( anId );
6564       }
6565     }
6566   }
6567   return res;
6568 }