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