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