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