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