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