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