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