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