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