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