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