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