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