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