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