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