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