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