Salome HOME
MEDCoupling Memory output from SMESH engine now deal with fields too.
[modules/smesh.git] / src / SMESH_I / SMESH_Mesh_i.cxx
1 // Copyright (C) 2007-2021  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_Mesh_i.cxx
23 //  Author : Paul RASCLE, EDF
24 //  Module : SMESH
25
26 #include "SMESH_Mesh_i.hxx"
27
28 #include "DriverMED_R_SMESHDS_Mesh.h"
29 #include "DriverMED_W_Field.h"
30 #include "DriverMED_W_SMESHDS_Mesh.h"
31 #include "MED_Factory.hxx"
32 #include "SMDS_LinearEdge.hxx"
33 #include "SMDS_EdgePosition.hxx"
34 #include "SMDS_ElemIterator.hxx"
35 #include "SMDS_FacePosition.hxx"
36 #include "SMDS_IteratorOnIterators.hxx"
37 #include "SMDS_MeshGroup.hxx"
38 #include "SMDS_SetIterator.hxx"
39 #include "SMDS_StdIterator.hxx"
40 #include "SMDS_VolumeTool.hxx"
41 #include "SMESHDS_Command.hxx"
42 #include "SMESHDS_CommandType.hxx"
43 #include "SMESHDS_Group.hxx"
44 #include "SMESHDS_GroupOnGeom.hxx"
45 #include "SMESH_Controls.hxx"
46 #include "SMESH_File.hxx"
47 #include "SMESH_Filter_i.hxx"
48 #include "SMESH_Gen_i.hxx"
49 #include "SMESH_Group.hxx"
50 #include "SMESH_Group_i.hxx"
51 #include "SMESH_Mesh.hxx"
52 #include "SMESH_MeshAlgos.hxx"
53 #include "SMESH_MeshEditor.hxx"
54 #include "SMESH_MeshEditor_i.hxx"
55 #include "SMESH_MeshPartDS.hxx"
56 #include "SMESH_MesherHelper.hxx"
57 #include "SMESH_PreMeshInfo.hxx"
58 #include "SMESH_PythonDump.hxx"
59 #include "SMESH_subMesh_i.hxx"
60
61 #include <SALOMEDS_Attributes_wrap.hxx>
62 #include <SALOMEDS_wrap.hxx>
63 #include <Utils_ExceptHandlers.hxx>
64 #include <utilities.h>
65
66 #include <GEOMImpl_Types.hxx>
67 #include <GEOM_wrap.hxx>
68
69 // OCCT Includes
70 #include <BRep_Builder.hxx>
71 #include <Standard_ErrorHandler.hxx>
72 #include <TColStd_MapOfInteger.hxx>
73 #include <TopExp.hxx>
74 #include <TopExp_Explorer.hxx>
75 #include <TopTools_DataMapOfShapeShape.hxx>
76 #include <TopTools_MapIteratorOfMapOfShape.hxx>
77 #include <TopTools_MapOfShape.hxx>
78 #include <TopoDS_Compound.hxx>
79
80 // STL Includes
81 #include <algorithm>
82 #include <iostream>
83 #include <sstream>
84
85 #include <vtkUnstructuredGridWriter.h>
86
87 // to pass CORBA exception and TooLargeForExport exception through SMESH_TRY
88 #define SMY_OWN_CATCH                                                                           \
89   catch( SALOME::SALOME_Exception& se ) { throw se; }                                           \
90   catch( ::SMESH_Mesh::TooLargeForExport& ex )                                                  \
91   { SALOME::ExceptionStruct se = {                                                              \
92       SALOME::COMM,                                                                             \
93       CORBA::string_dup(SMESH_Comment("Mesh is too large for export in format ") << ex.what()), \
94       CORBA::string_dup(SMESH_Comment("format=") <<  ex.what() ), 0 };                          \
95     throw SALOME::SALOME_Exception( se );  }
96
97 #include "SMESH_TryCatch.hxx" // include after OCCT headers!
98
99 #ifdef _DEBUG_
100 static int MYDEBUG = 0;
101 #else
102 static int MYDEBUG = 0;
103 #endif
104
105 using namespace std;
106 using SMESH::TPythonDump;
107 using SMESH::TVar;
108
109 int SMESH_Mesh_i::_idGenerator = 0;
110
111 //=============================================================================
112 /*!
113  *  Constructor
114  */
115 //=============================================================================
116
117 SMESH_Mesh_i::SMESH_Mesh_i( PortableServer::POA_ptr thePOA,
118                             SMESH_Gen_i*            gen_i )
119 : SALOME::GenericObj_i( thePOA )
120 {
121   _impl          = NULL;
122   _gen_i         = gen_i;
123   _id            = _idGenerator++;
124   _nbInvalidHypos= -1;
125   _editor        = NULL;
126   _previewEditor = NULL;
127   _preMeshInfo   = NULL;
128   _mainShapeTick = 0;
129 }
130
131 //=============================================================================
132 /*!
133  *  Destructor
134  */
135 //=============================================================================
136
137 SMESH_Mesh_i::~SMESH_Mesh_i()
138 {
139   // destroy groups
140   map<int, SMESH::SMESH_GroupBase_ptr>::iterator itGr;
141   for (itGr = _mapGroups.begin(); itGr != _mapGroups.end(); itGr++)
142     if (SMESH_GroupBase_i* aGroup = SMESH::DownCast<SMESH_GroupBase_i*>(itGr->second))
143     {
144       aGroup->UnRegister();
145       SMESH::SMESH_GroupBase_var( itGr->second );
146     }
147   _mapGroups.clear();
148
149   // destroy submeshes
150   map<int, SMESH::SMESH_subMesh_ptr>::iterator itSM;
151   for ( itSM = _mapSubMeshIor.begin(); itSM != _mapSubMeshIor.end(); itSM++ )
152     if ( SMESH_subMesh_i* aSubMesh = SMESH::DownCast<SMESH_subMesh_i*>( itSM->second ))
153     {
154       aSubMesh->UnRegister();
155       SMESH::SMESH_subMesh_var( itSM->second );
156     }
157   _mapSubMeshIor.clear();
158
159   // destroy hypotheses. _mapHypo contains all hyps ever been assigned
160   map<int, SMESH::SMESH_Hypothesis_ptr>::iterator itH;
161   for ( itH = _mapHypo.begin(); itH != _mapHypo.end(); itH++ ) {
162     if ( SMESH_Hypothesis_i* hyp_i = SMESH::DownCast<SMESH_Hypothesis_i*>( itH->second ))
163       if ( SMESH_Hypothesis * smHyp = _impl->GetHypothesis( itH->first ))
164         if ( _impl->GetMeshDS()->IsUsedHypothesis( smHyp ))
165           hyp_i->UnRegister();
166
167     SMESH::SMESH_Hypothesis_var( itH->second ); // decref CORBA object
168   }
169   _mapHypo.clear();
170
171   // clear cached shapes if no more meshes remain; (the cache is blame,
172   // together with publishing, of spent time increasing in issue 22874)
173   if ( _impl->NbMeshes() == 1 )
174     _gen_i->GetShapeReader()->ClearClientBuffer();
175
176   delete _editor; _editor = NULL;
177   delete _previewEditor; _previewEditor = NULL;
178   delete _impl; _impl = NULL;
179   delete _preMeshInfo; _preMeshInfo = NULL;
180 }
181
182 //=============================================================================
183 /*!
184  *  SetShape
185  *
186  *  Associate <this> mesh with <theShape> and put a reference
187  *  to <theShape> into the current study;
188  *  the previous shape is substituted by the new one.
189  */
190 //=============================================================================
191
192 void SMESH_Mesh_i::SetShape( GEOM::GEOM_Object_ptr theShapeObject )
193 {
194   Unexpect aCatch(SALOME_SalomeException);
195   try {
196     _impl->ShapeToMesh( _gen_i->GeomObjectToShape( theShapeObject ));
197   }
198   catch(SALOME_Exception & S_ex) {
199     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
200   }
201   // to track changes of GEOM groups
202   SMESH::SMESH_Mesh_var mesh = _this();
203   addGeomGroupData( theShapeObject, mesh );
204   if ( !CORBA::is_nil( theShapeObject ))
205     _mainShapeTick = theShapeObject->GetTick();
206 }
207
208 //================================================================================
209 /*!
210  * \brief Return true if mesh has a shape to build a shape on
211  */
212 //================================================================================
213
214 CORBA::Boolean SMESH_Mesh_i::HasShapeToMesh()
215 {
216   Unexpect aCatch(SALOME_SalomeException);
217   bool res = false;
218   try {
219     res = _impl->HasShapeToMesh();
220   }
221   catch(SALOME_Exception & S_ex) {
222     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
223   }
224   return res;
225 }
226
227 //================================================================================
228 /*!
229  * \brief Return the shape to mesh
230  */
231 //================================================================================
232
233 GEOM::GEOM_Object_ptr SMESH_Mesh_i::GetShapeToMesh()
234 {
235   Unexpect aCatch(SALOME_SalomeException);
236   GEOM::GEOM_Object_var aShapeObj;
237   try {
238     TopoDS_Shape S = _impl->GetMeshDS()->ShapeToMesh();
239     if ( !S.IsNull() )
240     {
241       aShapeObj = _gen_i->ShapeToGeomObject( S );
242       if ( aShapeObj->_is_nil() )
243       {
244         // S was removed from GEOM_Client by newGroupShape() called by other mesh;
245         // find GEOM_Object by entry (IPAL52735)
246         list<TGeomGroupData>::iterator data = _geomGroupData.begin();
247         for ( ; data != _geomGroupData.end(); ++data )
248           if ( data->_smeshObject->_is_equivalent( _this() ))
249           {
250             SALOMEDS::SObject_wrap so = _gen_i->getStudyServant()->FindObjectID( data->_groupEntry.c_str() );
251             CORBA::Object_var     obj = _gen_i->SObjectToObject( so );
252             aShapeObj = GEOM::GEOM_Object::_narrow( obj );
253             break;
254           }
255       }
256     }
257   }
258   catch(SALOME_Exception & S_ex) {
259     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
260   }
261   return aShapeObj._retn();
262 }
263
264 //================================================================================
265 /*!
266  * \brief Return false if the mesh is not yet fully loaded from the study file
267  */
268 //================================================================================
269
270 CORBA::Boolean SMESH_Mesh_i::IsLoaded()
271 {
272   Unexpect aCatch(SALOME_SalomeException);
273   return !_preMeshInfo;
274 }
275
276 //================================================================================
277 /*!
278  * \brief Load full mesh data from the study file
279  */
280 //================================================================================
281
282 void SMESH_Mesh_i::Load()
283 {
284   Unexpect aCatch(SALOME_SalomeException);
285   if ( _preMeshInfo )
286     _preMeshInfo->FullLoadFromFile();
287 }
288
289 //================================================================================
290 /*!
291  * \brief Remove all nodes and elements
292  */
293 //================================================================================
294
295 void SMESH_Mesh_i::Clear()
296 {
297   Unexpect aCatch(SALOME_SalomeException);
298   if ( _preMeshInfo )
299     _preMeshInfo->ForgetOrLoad(); // load in case if !HasShapeToMesh()
300
301   try {
302     _impl->Clear();
303     //CheckGeomGroupModif(); // issue 20145
304   }
305   catch(SALOME_Exception & S_ex) {
306     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
307   }
308
309   TPythonDump() <<  SMESH::SMESH_Mesh_var(_this()) << ".Clear()";
310
311   SMESH::SMESH_Mesh_var mesh = _this();
312   _gen_i->UpdateIcons( mesh );
313 }
314
315 //================================================================================
316 /*!
317  * \brief Remove all nodes and elements for indicated shape
318  */
319 //================================================================================
320
321 void SMESH_Mesh_i::ClearSubMesh(CORBA::Long ShapeID)
322 {
323   Unexpect aCatch(SALOME_SalomeException);
324   if ( _preMeshInfo )
325     _preMeshInfo->FullLoadFromFile();
326
327   try {
328     _impl->ClearSubMesh( ShapeID );
329   }
330   catch(SALOME_Exception & S_ex) {
331     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
332   }
333   _impl->GetMeshDS()->Modified();
334
335   TPythonDump() <<  SMESH::SMESH_Mesh_var(_this()) << ".ClearSubMesh( " << ShapeID << " )";
336 }
337
338 //=============================================================================
339 /*!
340  * Convert enum Driver_Mesh::Status to SMESH::DriverMED_ReadStatus
341  */
342 //=============================================================================
343
344 static SMESH::DriverMED_ReadStatus ConvertDriverMEDReadStatus (int theStatus)
345 {
346   SMESH::DriverMED_ReadStatus res;
347   switch (theStatus)
348   {
349   case DriverMED_R_SMESHDS_Mesh::DRS_OK:
350     res = SMESH::DRS_OK; break;
351   case DriverMED_R_SMESHDS_Mesh::DRS_EMPTY:
352     res = SMESH::DRS_EMPTY; break;
353   case DriverMED_R_SMESHDS_Mesh::DRS_WARN_RENUMBER:
354     res = SMESH::DRS_WARN_RENUMBER; break;
355   case DriverMED_R_SMESHDS_Mesh::DRS_WARN_SKIP_ELEM:
356     res = SMESH::DRS_WARN_SKIP_ELEM; break;
357   case DriverMED_R_SMESHDS_Mesh::DRS_WARN_DESCENDING:
358     res = SMESH::DRS_WARN_DESCENDING; break;
359   case DriverMED_R_SMESHDS_Mesh::DRS_FAIL:
360   default:
361     res = SMESH::DRS_FAIL; break;
362   }
363   return res;
364 }
365
366 //=============================================================================
367 /*!
368  * Convert ::SMESH_ComputeError to SMESH::ComputeError
369  */
370 //=============================================================================
371
372 static SMESH::ComputeError* ConvertComputeError( SMESH_ComputeErrorPtr errorPtr )
373 {
374   SMESH::ComputeError_var errVar = new SMESH::ComputeError();
375   errVar->subShapeID = -1;
376   errVar->hasBadMesh = false;
377
378   if ( !errorPtr || errorPtr->IsOK() )
379   {
380     errVar->code = SMESH::COMPERR_OK;
381   }
382   else
383   {
384     errVar->code    = ConvertDriverMEDReadStatus( errorPtr->myName );
385     errVar->comment = errorPtr->myComment.c_str();
386   }
387   return errVar._retn();
388 }
389
390 //=============================================================================
391 /*!
392  *  ImportMEDFile
393  *
394  *  Import mesh data from MED file
395  */
396 //=============================================================================
397
398 SMESH::DriverMED_ReadStatus
399 SMESH_Mesh_i::ImportMEDFile( const char* theFileName, const char* theMeshName )
400 {
401   Unexpect aCatch(SALOME_SalomeException);
402   int status;
403   try {
404     status = _impl->MEDToMesh( theFileName, theMeshName );
405   }
406   catch( SALOME_Exception& S_ex ) {
407     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
408   }
409   catch ( ... ) {
410     THROW_SALOME_CORBA_EXCEPTION("ImportMEDFile(): unknown exception", SALOME::BAD_PARAM);
411   }
412
413   CreateGroupServants();
414
415   int major, minor, release;
416   major = minor = release = 0;
417   MED::GetMEDVersion(theFileName, major, minor, release);
418   _medFileInfo           = new SMESH::MedFileInfo();
419   _medFileInfo->fileName = theFileName;
420   _medFileInfo->fileSize = 0;
421   _medFileInfo->major    = major;
422   _medFileInfo->minor    = minor;
423   _medFileInfo->release  = release;
424   _medFileInfo->fileSize = SMESH_File( theFileName ).size();
425
426   return ConvertDriverMEDReadStatus(status);
427 }
428
429 //================================================================================
430 /*!
431  * \brief Import mesh data from the CGNS file
432  */
433 //================================================================================
434
435 SMESH::DriverMED_ReadStatus SMESH_Mesh_i::ImportCGNSFile( const char*  theFileName,
436                                                           const int    theMeshIndex,
437                                                           std::string& theMeshName )
438 {
439   Unexpect aCatch(SALOME_SalomeException);
440   int status;
441   try {
442     status = _impl->CGNSToMesh( theFileName, theMeshIndex, theMeshName );
443   }
444   catch( SALOME_Exception& S_ex ) {
445     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
446   }
447   catch ( ... ) {
448     THROW_SALOME_CORBA_EXCEPTION("ImportCGNSFile(): unknown exception", SALOME::BAD_PARAM);
449   }
450
451   CreateGroupServants();
452
453   _medFileInfo           = new SMESH::MedFileInfo();
454   _medFileInfo->fileName = theFileName;
455   _medFileInfo->major    = 0;
456   _medFileInfo->minor    = 0;
457   _medFileInfo->release  = 0;
458   _medFileInfo->fileSize = SMESH_File( theFileName ).size();
459
460   return ConvertDriverMEDReadStatus(status);
461 }
462
463 //================================================================================
464 /*!
465  * \brief Return string representation of a MED file version comprising nbDigits
466  */
467 //================================================================================
468
469 char* SMESH_Mesh_i::GetVersionString(CORBA::Long minor, CORBA::Short nbDigits)
470 {
471   string ver = DriverMED_W_SMESHDS_Mesh::GetVersionString(minor, nbDigits);
472   return CORBA::string_dup( ver.c_str() );
473 }
474
475 //================================================================================
476 /*!
477  *  Return the list of med versions compatibles for write/append,
478  *  encoded in 10*major+minor (for instance, code for med 3.2.1 is 32)
479  */
480 //================================================================================
481
482 SMESH::long_array* SMESH_Mesh_i::GetMEDVersionsCompatibleForAppend()
483 {
484   SMESH::long_array_var aResult = new SMESH::long_array();
485   std::vector<int> mvok = MED::GetMEDVersionsAppendCompatible();
486   long nbver = mvok.size();
487   aResult->length( nbver );
488   for ( int i = 0; i < nbver; i++ )
489     aResult[i] = mvok[i];
490   return aResult._retn();
491 }
492
493 //=============================================================================
494 /*!
495  *  ImportUNVFile
496  *
497  *  Import mesh data from MED file
498  */
499 //=============================================================================
500
501 int SMESH_Mesh_i::ImportUNVFile( const char* theFileName )
502 {
503   SMESH_TRY;
504
505   // Read mesh with name = <theMeshName> into SMESH_Mesh
506   _impl->UNVToMesh( theFileName );
507
508   CreateGroupServants();
509
510   _medFileInfo           = new SMESH::MedFileInfo();
511   _medFileInfo->fileName = theFileName;
512   _medFileInfo->major    = 0;
513   _medFileInfo->minor    = 0;
514   _medFileInfo->release  = 0;
515   _medFileInfo->fileSize = SMESH_File( theFileName ).size();
516
517   SMESH_CATCH( SMESH::throwCorbaException );
518
519   return 1;
520 }
521
522 //=============================================================================
523 /*!
524  *  ImportSTLFile
525  *
526  *  Import mesh data from STL file
527  */
528 //=============================================================================
529
530 int SMESH_Mesh_i::ImportSTLFile( const char* theFileName )
531 {
532   SMESH_TRY;
533
534   // Read mesh with name = <theMeshName> into SMESH_Mesh
535   std::string name = _impl->STLToMesh( theFileName );
536   if ( !name.empty() )
537   {
538     SALOMEDS::SObject_wrap meshSO = _gen_i->ObjectToSObject( _this() );
539     _gen_i->SetName( meshSO, name.c_str() );
540   }
541   _medFileInfo           = new SMESH::MedFileInfo();
542   _medFileInfo->fileName = theFileName;
543   _medFileInfo->major    = 0;
544   _medFileInfo->minor    = 0;
545   _medFileInfo->release  = 0;
546   _medFileInfo->fileSize = SMESH_File( theFileName ).size();
547
548   SMESH_CATCH( SMESH::throwCorbaException );
549
550   return 1;
551 }
552
553 //================================================================================
554 /*!
555  * \brief Function used in SMESH_CATCH by ImportGMFFile()
556  */
557 //================================================================================
558
559 namespace
560 {
561   SMESH_ComputeErrorPtr exceptionToComputeError(const char* excText)
562   {
563     return SMESH_ComputeError::New( Driver_Mesh::DRS_FAIL, excText );
564   }
565 }
566
567 //================================================================================
568 /*!
569  * \brief Import data from a GMF file and return an error description
570  */
571 //================================================================================
572
573 SMESH::ComputeError* SMESH_Mesh_i::ImportGMFFile( const char* theFileName,
574                                                   bool        theMakeRequiredGroups )
575 {
576   SMESH_ComputeErrorPtr error;
577
578 #undef SMESH_CAUGHT
579 #define SMESH_CAUGHT error =
580   SMESH_TRY;
581
582   error = _impl->GMFToMesh( theFileName, theMakeRequiredGroups );
583
584   _medFileInfo           = new SMESH::MedFileInfo();
585   _medFileInfo->fileName = theFileName;
586   _medFileInfo->major    = 0;
587   _medFileInfo->minor    = 0;
588   _medFileInfo->release  = 0;
589   _medFileInfo->fileSize = SMESH_File( theFileName ).size();
590
591   SMESH_CATCH( exceptionToComputeError );
592 #undef SMESH_CAUGHT
593 #define SMESH_CAUGHT
594
595   CreateGroupServants();
596
597   return ConvertComputeError( error );
598 }
599
600 //=============================================================================
601 /*!
602  * \brief Convert SMESH_Hypothesis::Hypothesis_Status into SMESH::Hypothesis_Status
603  */
604 //=============================================================================
605
606 #define RETURNCASE(hyp_stat) case SMESH_Hypothesis::hyp_stat: return SMESH::hyp_stat;
607
608 SMESH::Hypothesis_Status SMESH_Mesh_i::ConvertHypothesisStatus
609                          (SMESH_Hypothesis::Hypothesis_Status theStatus)
610 {
611   switch (theStatus) {
612   RETURNCASE( HYP_OK            );
613   RETURNCASE( HYP_MISSING       );
614   RETURNCASE( HYP_CONCURRENT    );
615   RETURNCASE( HYP_BAD_PARAMETER );
616   RETURNCASE( HYP_HIDDEN_ALGO   );
617   RETURNCASE( HYP_HIDING_ALGO   );
618   RETURNCASE( HYP_UNKNOWN_FATAL );
619   RETURNCASE( HYP_INCOMPATIBLE  );
620   RETURNCASE( HYP_NOTCONFORM    );
621   RETURNCASE( HYP_ALREADY_EXIST );
622   RETURNCASE( HYP_BAD_DIM       );
623   RETURNCASE( HYP_BAD_SUBSHAPE  );
624   RETURNCASE( HYP_BAD_GEOMETRY  );
625   RETURNCASE( HYP_NEED_SHAPE    );
626   RETURNCASE( HYP_INCOMPAT_HYPS );
627   default:;
628   }
629   return SMESH::HYP_UNKNOWN_FATAL;
630 }
631
632 //=============================================================================
633 /*!
634  *  AddHypothesis
635  *
636  *  Call internal addHypothesis() and then add a reference to <anHyp> under
637  *  the SObject actually having a reference to <aSubShape>.
638  *  NB: For this method to work, it is necessary to add a reference to sub-shape first.
639  */
640 //=============================================================================
641
642 SMESH::Hypothesis_Status
643 SMESH_Mesh_i::AddHypothesis(GEOM::GEOM_Object_ptr       aSubShape,
644                             SMESH::SMESH_Hypothesis_ptr anHyp,
645                             CORBA::String_out           anErrorText)
646 {
647   Unexpect aCatch(SALOME_SalomeException);
648
649   const smIdType prevNbMeshEnt = NbNodes() + NbElements();
650
651   if ( _preMeshInfo )
652     _preMeshInfo->ForgetOrLoad();
653
654   std::string error;
655   SMESH_Hypothesis::Hypothesis_Status status = addHypothesis( aSubShape, anHyp, &error );
656   anErrorText = error.c_str();
657
658   SMESH::SMESH_Mesh_var mesh( _this() );
659   if ( !SMESH_Hypothesis::IsStatusFatal(status) )
660   {
661     _gen_i->AddHypothesisToShape( mesh, aSubShape, anHyp );
662
663     //int newNbMeshEnt = _impl->NbNodes() + _impl->GetMeshDS()->NbElements();
664     if ( prevNbMeshEnt > 0 /*newNbMeshEnt != prevNbMeshEnt*/ )
665       _gen_i->UpdateIcons( mesh );
666   }
667   if(MYDEBUG) MESSAGE( " AddHypothesis(): status = " << status );
668
669   // Update Python script
670   TPythonDump() << "status = " << mesh << ".AddHypothesis( "
671                 << aSubShape << ", " << anHyp << " )";
672
673   return ConvertHypothesisStatus(status);
674 }
675
676 //================================================================================
677 /*!
678  * \brief Create  a sub-mesh and add a hypothesis to it
679  */
680 //================================================================================
681
682 SMESH_Hypothesis::Hypothesis_Status
683 SMESH_Mesh_i::addHypothesis(GEOM::GEOM_Object_ptr       aSubShape,
684                             SMESH::SMESH_Hypothesis_ptr anHyp,
685                             std::string*                anErrorText)
686 {
687   if(MYDEBUG) MESSAGE("addHypothesis");
688
689   if (CORBA::is_nil( aSubShape ) && HasShapeToMesh())
690     THROW_SALOME_CORBA_EXCEPTION("bad Sub-shape reference",SALOME::BAD_PARAM);
691
692   if (CORBA::is_nil( anHyp ))
693     THROW_SALOME_CORBA_EXCEPTION("bad hypothesis reference",SALOME::BAD_PARAM);
694
695   SMESH_Hypothesis::Hypothesis_Status status = SMESH_Hypothesis::HYP_OK;
696   try
697   {
698     TopoDS_Shape myLocSubShape;
699     //use PseudoShape in case if mesh has no shape
700     if(HasShapeToMesh())
701       myLocSubShape = _gen_i->GeomObjectToShape( aSubShape);
702     else
703       myLocSubShape = _impl->GetShapeToMesh();
704
705     const int hypId = anHyp->GetId();
706     std::string error;
707     status = _impl->AddHypothesis( myLocSubShape, hypId, &error );
708     if ( !SMESH_Hypothesis::IsStatusFatal(status) )
709     {
710       _mapHypo[hypId] = SMESH::SMESH_Hypothesis::_duplicate( anHyp );
711       anHyp->Register();
712       // assure there is a corresponding submesh
713       if ( !_impl->IsMainShape( myLocSubShape )) {
714         int shapeId = _impl->GetMeshDS()->ShapeToIndex( myLocSubShape );
715         if ( _mapSubMesh_i.find( shapeId ) == _mapSubMesh_i.end() )
716           SMESH::SMESH_subMesh_var( createSubMesh( aSubShape ));
717       }
718     }
719     else if ( anErrorText )
720     {
721       *anErrorText = error;
722     }
723   }
724   catch(SALOME_Exception & S_ex)
725   {
726     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
727   }
728   return status;
729 }
730
731 //================================================================================
732 /*!
733  * \brief Un-assign a hypothesis from a sub-mesh dedicate to the given sub-shape
734  */
735 //================================================================================
736
737 SMESH::Hypothesis_Status SMESH_Mesh_i::RemoveHypothesis(GEOM::GEOM_Object_ptr       aSubShape,
738                                                         SMESH::SMESH_Hypothesis_ptr anHyp)
739 {
740   Unexpect aCatch(SALOME_SalomeException);
741   if ( _preMeshInfo )
742     _preMeshInfo->ForgetOrLoad();
743
744   SMESH_Hypothesis::Hypothesis_Status status = removeHypothesis( aSubShape, anHyp );
745   SMESH::SMESH_Mesh_var mesh = _this();
746
747   if ( !SMESH_Hypothesis::IsStatusFatal(status) )
748   {
749     _gen_i->RemoveHypothesisFromShape( mesh, aSubShape, anHyp );
750     _gen_i->UpdateIcons( mesh );
751   }
752   // Update Python script
753   if(_impl->HasShapeToMesh())
754     TPythonDump() << "status = " << mesh << ".RemoveHypothesis( "
755                   << aSubShape << ", " << anHyp << " )";
756   else
757     TPythonDump() << "status = " << mesh << ".RemoveHypothesis( "
758                   << anHyp << " )";
759
760   return ConvertHypothesisStatus(status);
761 }
762
763 //=============================================================================
764 /*!
765  * \brief Un-assign a hypothesis from a sub-mesh dedicate to the given sub-shape
766  */
767 //=============================================================================
768
769 SMESH_Hypothesis::Hypothesis_Status
770 SMESH_Mesh_i::removeHypothesis(GEOM::GEOM_Object_ptr       aSubShape,
771                                SMESH::SMESH_Hypothesis_ptr anHyp)
772 {
773   if(MYDEBUG) MESSAGE("removeHypothesis()");
774
775   if (CORBA::is_nil( aSubShape ) && HasShapeToMesh())
776     THROW_SALOME_CORBA_EXCEPTION("bad Sub-shape reference", SALOME::BAD_PARAM);
777
778   if (CORBA::is_nil( anHyp ))
779     THROW_SALOME_CORBA_EXCEPTION("bad hypothesis reference", SALOME::BAD_PARAM);
780
781   if ( _preMeshInfo )
782     _preMeshInfo->ForgetOrLoad();
783
784   SMESH_Hypothesis::Hypothesis_Status status = SMESH_Hypothesis::HYP_OK;
785   try
786   {
787     TopoDS_Shape myLocSubShape;
788     //use PseudoShape in case if mesh has no shape
789     if( _impl->HasShapeToMesh() )
790       myLocSubShape = _gen_i->GeomObjectToShape( aSubShape );
791     else
792       myLocSubShape = _impl->GetShapeToMesh();
793
794     const int hypId = anHyp->GetId();
795     status = _impl->RemoveHypothesis(myLocSubShape, hypId);
796     if ( !SMESH_Hypothesis::IsStatusFatal(status) )
797     {
798       // _mapHypo.erase( hypId ); EAP: hyp can be used on many sub-shapes
799       anHyp->UnRegister();
800     }
801   }
802   catch(SALOME_Exception & S_ex)
803   {
804     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
805   }
806   return status;
807 }
808
809 //================================================================================
810 /*!
811  * \brief Return hypotheses assigned to a given sub-shape
812  */
813 //================================================================================
814
815 SMESH::ListOfHypothesis *
816 SMESH_Mesh_i::GetHypothesisList(GEOM::GEOM_Object_ptr aSubShape)
817 {
818   Unexpect aCatch(SALOME_SalomeException);
819   if (MYDEBUG) MESSAGE("GetHypothesisList");
820   if (_impl->HasShapeToMesh() && CORBA::is_nil(aSubShape))
821     THROW_SALOME_CORBA_EXCEPTION("bad Sub-shape reference", SALOME::BAD_PARAM);
822
823   SMESH::ListOfHypothesis_var aList = new SMESH::ListOfHypothesis();
824
825   try {
826     TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(aSubShape);
827     if ( myLocSubShape.IsNull() && !_impl->HasShapeToMesh() )
828       myLocSubShape = _impl->GetShapeToMesh();
829     const list<const SMESHDS_Hypothesis*>& aLocalList = _impl->GetHypothesisList( myLocSubShape );
830     int i = 0, n = aLocalList.size();
831     aList->length( n );
832
833     list<const SMESHDS_Hypothesis*>::const_iterator aHyp = aLocalList.begin();
834     std::map<int, SMESH::SMESH_Hypothesis_ptr>::iterator id_hypptr;
835     for ( ; i < n && aHyp != aLocalList.end(); aHyp++ )
836     {
837       id_hypptr = _mapHypo.find( (*aHyp)->GetID() );
838       if ( id_hypptr != _mapHypo.end() )
839         aList[i++] = SMESH::SMESH_Hypothesis::_narrow( id_hypptr->second );
840     }
841     aList->length( i );
842   }
843   catch(SALOME_Exception & S_ex) {
844     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
845   }
846
847   return aList._retn();
848 }
849
850 //================================================================================
851 /*!
852  * \brief Return sub-meshes
853  */
854 //================================================================================
855
856 SMESH::submesh_array* SMESH_Mesh_i::GetSubMeshes()
857 {
858   Unexpect aCatch(SALOME_SalomeException);
859   if (MYDEBUG) MESSAGE("GetSubMeshes");
860
861   SMESH::submesh_array_var aList = new SMESH::submesh_array();
862
863   // Python Dump
864   TPythonDump aPythonDump;
865   if ( !_mapSubMeshIor.empty() )
866     aPythonDump << "[ ";
867
868   try {
869     aList->length( _mapSubMeshIor.size() );
870     int i = 0;
871     map<int, SMESH::SMESH_subMesh_ptr>::iterator it = _mapSubMeshIor.begin();
872     for ( ; it != _mapSubMeshIor.end(); it++ ) {
873       if ( CORBA::is_nil( it->second )) continue;
874       aList[i++] = SMESH::SMESH_subMesh::_duplicate( it->second );
875       // Python Dump
876       if (i > 1) aPythonDump << ", ";
877       aPythonDump << it->second;
878     }
879     aList->length( i );
880   }
881   catch(SALOME_Exception & S_ex) {
882     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
883   }
884
885   // Update Python script
886   if ( !_mapSubMeshIor.empty() )
887     aPythonDump << " ] = " << SMESH::SMESH_Mesh_var( _this() ) << ".GetSubMeshes()";
888
889   return aList._retn();
890 }
891
892 //================================================================================
893 /*!
894  * \brief Create and return a sub-mesh on the given sub-shape
895  */
896 //================================================================================
897
898 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::GetSubMesh(GEOM::GEOM_Object_ptr aSubShape,
899                                                   const char*           theName )
900 {
901   Unexpect aCatch(SALOME_SalomeException);
902   if (CORBA::is_nil(aSubShape))
903     THROW_SALOME_CORBA_EXCEPTION("bad Sub-shape reference", SALOME::BAD_PARAM);
904
905   SMESH::SMESH_subMesh_var subMesh;
906   SMESH::SMESH_Mesh_var    aMesh = _this();
907   try {
908     TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(aSubShape);
909
910     //Get or Create the SMESH_subMesh object implementation
911
912     TopoDS_Iterator it( myLocSubShape );
913     int   subMeshId = _impl->GetMeshDS()->ShapeToIndex( myLocSubShape );
914     bool isValidSub = ( subMeshId || _impl->GetMeshDS()->IsGroupOfSubShapes( myLocSubShape ));
915     if ( isValidSub && myLocSubShape.ShapeType() == TopAbs_COMPOUND )
916       isValidSub = !it.Value().IsSame( _impl->GetShapeToMesh() );
917     if ( !isValidSub )
918     {
919       if ( it.More() )
920         THROW_SALOME_CORBA_EXCEPTION("Not a sub-shape of the main shape", SALOME::BAD_PARAM);
921     }
922     subMesh = getSubMesh( subMeshId );
923
924     // create a new subMesh object servant if there is none for the shape
925     if ( subMesh->_is_nil() )
926       subMesh = createSubMesh( aSubShape );
927     if ( _gen_i->CanPublishInStudy( subMesh ))
928     {
929       SALOMEDS::SObject_wrap aSO =
930         _gen_i->PublishSubMesh( aMesh, subMesh, aSubShape, theName );
931       if ( !aSO->_is_nil()) {
932         // Update Python script
933         TPythonDump() << aSO << " = " << aMesh << ".GetSubMesh( "
934                       << aSubShape << ", '" << theName << "' )";
935       }
936     }
937   }
938   catch(SALOME_Exception & S_ex) {
939     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
940   }
941   return subMesh._retn();
942 }
943
944 //================================================================================
945 /*!
946  * \brief Remove a sub-mesh
947  */
948 //================================================================================
949
950 void SMESH_Mesh_i::RemoveSubMesh( SMESH::SMESH_subMesh_ptr theSubMesh )
951 {
952   SMESH_TRY;
953
954   if ( theSubMesh->_is_nil() )
955     return;
956
957   GEOM::GEOM_Object_var aSubShape;
958   // Remove submesh's SObject
959   SALOMEDS::SObject_wrap anSO = _gen_i->ObjectToSObject( theSubMesh );
960   if ( !anSO->_is_nil() ) {
961     long aTag = SMESH_Gen_i::GetRefOnShapeTag();
962     SALOMEDS::SObject_wrap anObj, aRef;
963     if ( anSO->FindSubObject( aTag, anObj.inout() ) &&
964          anObj->ReferencedObject( aRef.inout() ))
965     {
966       CORBA::Object_var obj = aRef->GetObject();
967       aSubShape = GEOM::GEOM_Object::_narrow( obj );
968     }
969     // if ( aSubShape->_is_nil() ) // not published shape (IPAL13617)
970     //   aSubShape = theSubMesh->GetSubShape();
971
972     SALOMEDS::StudyBuilder_var builder = _gen_i->getStudyServant()->NewBuilder();
973     builder->RemoveObjectWithChildren( anSO );
974
975     // Update Python script
976     TPythonDump() << SMESH::SMESH_Mesh_var( _this() ) << ".RemoveSubMesh( " << anSO << " )";
977   }
978
979   if ( removeSubMesh( theSubMesh, aSubShape.in() ))
980     if ( _preMeshInfo )
981       _preMeshInfo->ForgetOrLoad();
982
983   SMESH_CATCH( SMESH::throwCorbaException );
984 }
985
986 //================================================================================
987 /*!
988  * \brief Create a standalone group
989  */
990 //================================================================================
991
992 SMESH::SMESH_Group_ptr SMESH_Mesh_i::CreateGroup( SMESH::ElementType theElemType,
993                                                   const char*        theName )
994 {
995   Unexpect aCatch(SALOME_SalomeException);
996   if ( _preMeshInfo )
997     _preMeshInfo->FullLoadFromFile();
998
999   SMESH::SMESH_Group_var aNewGroup =
1000     SMESH::SMESH_Group::_narrow( createGroup( theElemType, theName ));
1001
1002   if ( _gen_i->CanPublishInStudy( aNewGroup ) )
1003   {
1004     SMESH::SMESH_Mesh_var mesh = _this();
1005     SALOMEDS::SObject_wrap aSO =
1006       _gen_i->PublishGroup( mesh, aNewGroup, GEOM::GEOM_Object::_nil(), theName);
1007     if ( !aSO->_is_nil())
1008       // Update Python script
1009       TPythonDump() << aSO << " = " << mesh << ".CreateGroup( "
1010                     << theElemType << ", '" << theName << "' )";
1011   }
1012   return aNewGroup._retn();
1013 }
1014
1015 //================================================================================
1016 /*!
1017  * \brief Create a group based on the given geometry
1018  */
1019 //================================================================================
1020
1021 SMESH::SMESH_GroupOnGeom_ptr
1022 SMESH_Mesh_i::CreateGroupFromGEOM (SMESH::ElementType    theElemType,
1023                                    const char*           theName,
1024                                    GEOM::GEOM_Object_ptr theGeomObj)
1025 {
1026   Unexpect aCatch(SALOME_SalomeException);
1027   if ( _preMeshInfo )
1028     _preMeshInfo->FullLoadFromFile();
1029
1030   SMESH::SMESH_GroupOnGeom_var aNewGroup;
1031
1032   TopoDS_Shape aShape = _gen_i->GeomObjectToShape( theGeomObj );
1033   if ( !aShape.IsNull() )
1034   {
1035     aNewGroup =
1036       SMESH::SMESH_GroupOnGeom::_narrow( createGroup( theElemType, theName, /*id=*/-1, aShape ));
1037
1038     if ( _gen_i->CanPublishInStudy( aNewGroup ) )
1039     {
1040       SMESH::SMESH_Mesh_var mesh = _this();
1041       SALOMEDS::SObject_wrap aSO =
1042         _gen_i->PublishGroup( mesh, aNewGroup, theGeomObj, theName );
1043       if ( !aSO->_is_nil())
1044         TPythonDump() << aSO << " = " << mesh << ".CreateGroupFromGEOM( "
1045                       << theElemType << ", '" << theName << "', " << theGeomObj << " )";
1046     }
1047   }
1048
1049   return aNewGroup._retn();
1050 }
1051
1052 //================================================================================
1053 /*!
1054  * \brief Creates a group whose contents is defined by filter
1055  *  \param theElemType - group type
1056  *  \param theName - group name
1057  *  \param theFilter - the filter
1058  *  \retval SMESH::SMESH_GroupOnFilter_ptr - group defined by filter
1059  */
1060 //================================================================================
1061
1062 SMESH::SMESH_GroupOnFilter_ptr
1063 SMESH_Mesh_i::CreateGroupFromFilter(SMESH::ElementType theElemType,
1064                                     const char*        theName,
1065                                     SMESH::Filter_ptr  theFilter )
1066 {
1067   Unexpect aCatch(SALOME_SalomeException);
1068   if ( _preMeshInfo )
1069     _preMeshInfo->FullLoadFromFile();
1070
1071   if ( CORBA::is_nil( theFilter ))
1072     THROW_SALOME_CORBA_EXCEPTION("NULL filter", SALOME::BAD_PARAM);
1073
1074   SMESH_PredicatePtr predicate = SMESH_GroupOnFilter_i::GetPredicate( theFilter );
1075   if ( !predicate )
1076     THROW_SALOME_CORBA_EXCEPTION("Invalid filter", SALOME::BAD_PARAM);
1077
1078   SMESH::SMESH_GroupOnFilter_var aNewGroup = SMESH::SMESH_GroupOnFilter::_narrow
1079     ( createGroup( theElemType, theName, /*id=*/-1, TopoDS_Shape(), predicate ));
1080
1081   TPythonDump pd;
1082   if ( !aNewGroup->_is_nil() )
1083     aNewGroup->SetFilter( theFilter );
1084
1085   if ( _gen_i->CanPublishInStudy( aNewGroup ) )
1086   {
1087     SMESH::SMESH_Mesh_var mesh = _this();
1088     SALOMEDS::SObject_wrap aSO =
1089       _gen_i->PublishGroup( mesh, aNewGroup, GEOM::GEOM_Object::_nil(), theName );
1090
1091     if ( !aSO->_is_nil())
1092       pd << aSO << " = " << mesh << ".CreateGroupFromFilter( "
1093          << theElemType << ", '" << theName << "', " << theFilter << " )";
1094   }
1095   return aNewGroup._retn();
1096 }
1097
1098 //================================================================================
1099 /*!
1100  * \brief Remove a group
1101  */
1102 //================================================================================
1103
1104 void SMESH_Mesh_i::RemoveGroup( SMESH::SMESH_GroupBase_ptr theGroup )
1105 {
1106   if ( theGroup->_is_nil() )
1107     return;
1108
1109   SMESH_TRY;
1110
1111   SMESH_GroupBase_i* aGroup = SMESH::DownCast<SMESH_GroupBase_i*>( theGroup );
1112   if ( !aGroup )
1113     return;
1114
1115   if ( aGroup->GetMeshServant() != this )
1116     THROW_SALOME_CORBA_EXCEPTION( "RemoveGroup(): group does not belong to this mesh",
1117                                   SALOME::BAD_PARAM );
1118
1119   SALOMEDS::SObject_wrap aGroupSO = _gen_i->ObjectToSObject( theGroup );
1120   if ( !aGroupSO->_is_nil() )
1121   {
1122     // Update Python script
1123     TPythonDump() << SMESH::SMESH_Mesh_var(_this()) << ".RemoveGroup( " << aGroupSO << " )";
1124
1125     // Remove group's SObject
1126     SALOMEDS::StudyBuilder_var builder = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->NewBuilder();
1127     builder->RemoveObjectWithChildren( aGroupSO );
1128   }
1129   aGroup->Modified(/*removed=*/true); // notify dependent Filter with FT_BelongToMeshGroup criterion
1130
1131   // Remove the group from SMESH data structures
1132   removeGroup( aGroup->GetLocalID() );
1133
1134   SMESH_CATCH( SMESH::throwCorbaException );
1135 }
1136
1137 //=============================================================================
1138 /*!
1139  *  Remove group with its contents
1140  */
1141 //=============================================================================
1142
1143 void SMESH_Mesh_i::RemoveGroupWithContents( SMESH::SMESH_GroupBase_ptr theGroup )
1144 {
1145   SMESH_TRY;
1146   if ( _preMeshInfo )
1147     _preMeshInfo->FullLoadFromFile();
1148
1149   if ( theGroup->_is_nil() )
1150     return;
1151
1152   SMESH_GroupBase_i* groupImpl = SMESH::DownCast< SMESH_GroupBase_i* >( theGroup );
1153   if ( !groupImpl || groupImpl->GetMeshServant() != this )
1154     THROW_SALOME_CORBA_EXCEPTION( "RemoveGroupWithContents(): group does not belong to this mesh",
1155                                   SALOME::BAD_PARAM);
1156
1157   vector<smIdType> nodeIds; // to remove nodes becoming free
1158   bool isNodal = ( theGroup->GetType() == SMESH::NODE );
1159   if ( !isNodal && !theGroup->IsEmpty() )
1160   {
1161     SMESH::smIdType elemID = theGroup->GetID( 1 );
1162     int nbElemNodes = GetElemNbNodes( elemID );
1163     if ( nbElemNodes > 0 )
1164       nodeIds.reserve( theGroup->Size() * nbElemNodes );
1165   }
1166
1167   // Retrieve contents
1168   SMESH::SMESH_IDSource_var idSrc = SMESH::SMESH_IDSource::_narrow( theGroup );
1169   SMDS_ElemIteratorPtr     elemIt = GetElements( idSrc, theGroup->GetType() );
1170   SMDS_StdIterator< const SMDS_MeshElement*, SMDS_ElemIteratorPtr > elemBeg( elemIt ), elemEnd;
1171   std::vector< const SMDS_MeshElement* > elems( theGroup->Size() );
1172   elems.assign( elemBeg, elemEnd );
1173
1174   TPythonDump pyDump; // Suppress dump from RemoveGroup()
1175
1176   // Remove group
1177   RemoveGroup( theGroup );
1178
1179   // Remove contents
1180   for ( size_t i = 0; i < elems.size(); ++i )
1181   {
1182     // if ( !_impl->GetMeshDS()->Contains( elems[i] ))
1183     //   continue;
1184     if ( !isNodal )
1185     {
1186       for ( SMDS_ElemIteratorPtr nIt = elems[i]->nodesIterator(); nIt->more(); )
1187         nodeIds.push_back( nIt->next()->GetID() );
1188
1189       _impl->GetMeshDS()->RemoveFreeElement( elems[i], /*sm=*/0 );
1190     }
1191     else
1192     {
1193       _impl->GetMeshDS()->RemoveElement( elems[i] );
1194     }
1195   }
1196
1197   // Remove free nodes
1198   for ( size_t i = 0 ; i < nodeIds.size(); ++i )
1199     if ( const SMDS_MeshNode* n = _impl->GetMeshDS()->FindNode( nodeIds[i] ))
1200       if ( n->NbInverseElements() == 0 )
1201         _impl->GetMeshDS()->RemoveFreeNode( n, /*sm=*/0 );
1202
1203   _impl->GetMeshDS()->Modified();
1204   _impl->SetIsModified( true );
1205
1206   // Update Python script (theGroup must be alive for this)
1207   pyDump << SMESH::SMESH_Mesh_var(_this())
1208          << ".RemoveGroupWithContents( " << theGroup << " )";
1209
1210   SMESH_CATCH( SMESH::throwCorbaException );
1211 }
1212
1213 //================================================================================
1214 /*!
1215  * \brief Get the list of groups existing in the mesh
1216  *  \retval SMESH::ListOfGroups * - list of groups
1217  */
1218 //================================================================================
1219
1220 SMESH::ListOfGroups * SMESH_Mesh_i::GetGroups()
1221 {
1222   Unexpect aCatch(SALOME_SalomeException);
1223   if (MYDEBUG) MESSAGE("GetGroups");
1224
1225   SMESH::ListOfGroups_var aList = new SMESH::ListOfGroups();
1226
1227   // Python Dump
1228   TPythonDump aPythonDump;
1229   if ( !_mapGroups.empty() )
1230   {
1231     aPythonDump << "[ ";
1232     try {
1233       aList->length( _mapGroups.size() );
1234       int i = 0;
1235       map<int, SMESH::SMESH_GroupBase_ptr>::iterator it = _mapGroups.begin();
1236       for ( ; it != _mapGroups.end(); it++ ) {
1237         if ( CORBA::is_nil( it->second )) continue;
1238         aList[i++] = SMESH::SMESH_GroupBase::_duplicate( it->second );
1239         // Python Dump
1240         if (i > 1) aPythonDump << ", ";
1241         aPythonDump << it->second;
1242       }
1243       aList->length( i );
1244     }
1245     catch(SALOME_Exception & S_ex) {
1246       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1247     }
1248     aPythonDump << " ] = " << SMESH::SMESH_Mesh_var(_this()) << ".GetGroups()";
1249   }
1250   return aList._retn();
1251 }
1252
1253 //=============================================================================
1254 /*!
1255  *  Get number of groups existing in the mesh
1256  */
1257 //=============================================================================
1258
1259 CORBA::Long SMESH_Mesh_i::NbGroups()
1260 {
1261   Unexpect aCatch(SALOME_SalomeException);
1262   return _mapGroups.size();
1263 }
1264
1265 //=============================================================================
1266 /*!
1267  * New group including all mesh elements present in initial groups is created.
1268  */
1269 //=============================================================================
1270
1271 SMESH::SMESH_Group_ptr SMESH_Mesh_i::UnionGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
1272                                                   SMESH::SMESH_GroupBase_ptr theGroup2,
1273                                                   const char*                theName )
1274 {
1275   SMESH::SMESH_Group_var aResGrp;
1276
1277   SMESH_TRY;
1278   if ( _preMeshInfo )
1279     _preMeshInfo->FullLoadFromFile();
1280
1281   if ( theGroup1->_is_nil() || theGroup2->_is_nil() )
1282     THROW_SALOME_CORBA_EXCEPTION("UnionGroups(): NULL Group",
1283                                  SALOME::BAD_PARAM);
1284   if ( theGroup1->GetType() != theGroup2->GetType() )
1285     THROW_SALOME_CORBA_EXCEPTION("UnionGroups(): different group types",
1286                                  SALOME::BAD_PARAM);
1287   TPythonDump pyDump;
1288
1289   // Create Union
1290   aResGrp = CreateGroup( theGroup1->GetType(), theName );
1291   if ( aResGrp->_is_nil() )
1292     return SMESH::SMESH_Group::_nil();
1293
1294   aResGrp->AddFrom( theGroup1 );
1295   aResGrp->AddFrom( theGroup2 );
1296
1297   // Update Python script
1298   pyDump << aResGrp << " = " << SMESH::SMESH_Mesh_var(_this())
1299          << ".UnionGroups( " << theGroup1 << ", " << theGroup2 << ", '" << theName << "' )";
1300
1301   SMESH_CATCH( SMESH::throwCorbaException );
1302
1303   return aResGrp._retn();
1304 }
1305
1306 //=============================================================================
1307 /*!
1308  * \brief New group including all mesh elements present in initial groups is created.
1309  *  \param theGroups list of groups
1310  *  \param theName name of group to be created
1311  *  \return pointer to the new group
1312  */
1313 //=============================================================================
1314
1315 SMESH::SMESH_Group_ptr SMESH_Mesh_i::UnionListOfGroups(const SMESH::ListOfGroups& theGroups,
1316                                                        const char*                theName )
1317 {
1318   SMESH::SMESH_Group_var aResGrp;
1319
1320   if ( _preMeshInfo )
1321     _preMeshInfo->FullLoadFromFile();
1322
1323   if ( !theName )
1324     return SMESH::SMESH_Group::_nil();
1325
1326   SMESH_TRY;
1327
1328   // check types
1329   SMESH::ElementType aType = SMESH::ALL;
1330   for ( int g = 0, n = theGroups.length(); g < n; g++ )
1331   {
1332     SMESH::SMESH_GroupBase_var aGrp = theGroups[ g ];
1333     if ( CORBA::is_nil( aGrp ) )
1334       continue;
1335     if ( aType == SMESH::ALL )
1336       aType = aGrp->GetType();
1337     else if ( aType != aGrp->GetType() )
1338       THROW_SALOME_CORBA_EXCEPTION("UnionListOfGroups(): different group types",
1339                                    SALOME::BAD_PARAM);
1340   }
1341   if ( aType == SMESH::ALL )
1342     return SMESH::SMESH_Group::_nil();
1343
1344   TPythonDump pyDump;
1345
1346   // Create Union
1347   aResGrp = CreateGroup( aType, theName );
1348   if ( aResGrp->_is_nil() )
1349     return SMESH::SMESH_Group::_nil();
1350
1351   pyDump << aResGrp << " = " << SMESH::SMESH_Mesh_var(_this()) << ".UnionListOfGroups([ ";
1352   for ( int g = 0, n = theGroups.length(); g < n; g++ )
1353   {
1354     SMESH::SMESH_GroupBase_var aGrp = theGroups[ g ];
1355     if ( !CORBA::is_nil( aGrp ) )
1356     {
1357       aResGrp->AddFrom( aGrp );
1358       if ( g > 0 ) pyDump << ", ";
1359       pyDump << aGrp;
1360     }
1361   }
1362   pyDump << " ], '" << theName << "' )";
1363
1364   SMESH_CATCH( SMESH::throwCorbaException );
1365
1366   return aResGrp._retn();
1367 }
1368
1369 //=============================================================================
1370 /*!
1371  *  New group is created. All mesh elements that are
1372  *  present in both initial groups are added to the new one.
1373  */
1374 //=============================================================================
1375
1376 SMESH::SMESH_Group_ptr SMESH_Mesh_i::IntersectGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
1377                                                       SMESH::SMESH_GroupBase_ptr theGroup2,
1378                                                       const char*                theName )
1379 {
1380   SMESH::SMESH_Group_var aResGrp;
1381
1382   SMESH_TRY;
1383
1384   if ( _preMeshInfo )
1385     _preMeshInfo->FullLoadFromFile();
1386
1387   if ( theGroup1->_is_nil() || theGroup2->_is_nil() )
1388     THROW_SALOME_CORBA_EXCEPTION("IntersectGroups(): NULL Group",
1389                                  SALOME::BAD_PARAM);
1390   if ( theGroup1->GetType() != theGroup2->GetType() )
1391     THROW_SALOME_CORBA_EXCEPTION("IntersectGroups(): different group types",
1392                                  SALOME::BAD_PARAM);
1393   TPythonDump pyDump;
1394
1395   // Create Intersection
1396   aResGrp = CreateGroup( theGroup1->GetType(), theName );
1397   if ( aResGrp->_is_nil() )
1398     return aResGrp._retn();
1399
1400   SMESHDS_GroupBase* groupDS1 = 0;
1401   if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( theGroup1 ))
1402     groupDS1 = grp_i->GetGroupDS();
1403
1404   SMESHDS_GroupBase* groupDS2 = 0;
1405   if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( theGroup2 ))
1406     groupDS2 = grp_i->GetGroupDS();
1407
1408   SMESHDS_Group* resGroupDS = 0;
1409   if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( aResGrp ))
1410     resGroupDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() );
1411
1412   if ( groupDS1 && groupDS2 && resGroupDS && !groupDS2->IsEmpty() )
1413   {
1414     SMDS_ElemIteratorPtr elemIt1 = groupDS1->GetElements();
1415     while ( elemIt1->more() )
1416     {
1417       const SMDS_MeshElement* e = elemIt1->next();
1418       if ( groupDS2->Contains( e ))
1419         resGroupDS->SMDSGroup().Add( e );
1420     }
1421   }
1422   // Update Python script
1423   pyDump << aResGrp << " = " << SMESH::SMESH_Mesh_var(_this()) << ".IntersectGroups( "
1424          << theGroup1 << ", " << theGroup2 << ", '" << theName << "')";
1425
1426   SMESH_CATCH( SMESH::throwCorbaException );
1427
1428   return aResGrp._retn();
1429 }
1430
1431 //=============================================================================
1432 /*!
1433   \brief Intersect list of groups. New group is created. All mesh elements that
1434   are present in all initial groups simultaneously are added to the new one.
1435   \param theGroups list of groups
1436   \param theName name of group to be created
1437   \return pointer on the group
1438 */
1439 //=============================================================================
1440
1441 SMESH::SMESH_Group_ptr
1442 SMESH_Mesh_i::IntersectListOfGroups(const SMESH::ListOfGroups& theGroups,
1443                                     const char*                theName )
1444 {
1445   SMESH::SMESH_Group_var aResGrp;
1446
1447   SMESH_TRY;
1448
1449   if ( _preMeshInfo )
1450     _preMeshInfo->FullLoadFromFile();
1451
1452   if ( !theName )
1453     return SMESH::SMESH_Group::_nil();
1454
1455   // check types and get SMESHDS_GroupBase's
1456   SMESH::ElementType aType = SMESH::ALL;
1457   vector< SMESHDS_GroupBase* > groupVec;
1458   for ( int g = 0, n = theGroups.length(); g < n; g++ )
1459   {
1460     SMESH::SMESH_GroupBase_var aGrp = theGroups[ g ];
1461     if ( CORBA::is_nil( aGrp ) )
1462       continue;
1463     if ( aType == SMESH::ALL )
1464       aType = aGrp->GetType();
1465     else if ( aType != aGrp->GetType() )
1466       THROW_SALOME_CORBA_EXCEPTION("IntersectListOfGroups(): different group types",
1467                                    SALOME::BAD_PARAM);
1468
1469     if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( aGrp ))
1470       if ( SMESHDS_GroupBase* grpDS = grp_i->GetGroupDS() )
1471       {
1472         if ( grpDS->IsEmpty() )
1473         {
1474           groupVec.clear();
1475           break;
1476         }
1477         groupVec.push_back( grpDS );
1478       }
1479   }
1480   if ( aType == SMESH::ALL ) // all groups are nil
1481     return SMESH::SMESH_Group::_nil();
1482
1483   TPythonDump pyDump;
1484
1485   // Create a group
1486   aResGrp = CreateGroup( aType, theName );
1487
1488   SMESHDS_Group* resGroupDS = 0;
1489   if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( aResGrp ))
1490     resGroupDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() );
1491   if ( !resGroupDS || groupVec.empty() )
1492     return aResGrp._retn();
1493
1494   // Fill the group
1495   size_t i, nb = groupVec.size();
1496   SMDS_ElemIteratorPtr elemIt1 = groupVec[0]->GetElements();
1497   while ( elemIt1->more() )
1498   {
1499     const SMDS_MeshElement* e = elemIt1->next();
1500     bool inAll = true;
1501     for ( i = 1; ( i < nb && inAll ); ++i )
1502       inAll = groupVec[i]->Contains( e );
1503
1504     if ( inAll )
1505       resGroupDS->SMDSGroup().Add( e );
1506   }
1507
1508   // Update Python script
1509   pyDump << aResGrp << " = " << SMESH::SMESH_Mesh_var( _this() )
1510          << ".IntersectListOfGroups( " << theGroups << ", '" << theName << "' )";
1511
1512   SMESH_CATCH( SMESH::throwCorbaException );
1513
1514   return aResGrp._retn();
1515 }
1516
1517 //=============================================================================
1518 /*!
1519  *  New group is created. All mesh elements that are present in
1520  *  a main group but is not present in a tool group are added to the new one
1521  */
1522 //=============================================================================
1523
1524 SMESH::SMESH_Group_ptr SMESH_Mesh_i::CutGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
1525                                                 SMESH::SMESH_GroupBase_ptr theGroup2,
1526                                                 const char*                theName )
1527 {
1528   SMESH::SMESH_Group_var aResGrp;
1529
1530   SMESH_TRY;
1531
1532   if ( _preMeshInfo )
1533     _preMeshInfo->FullLoadFromFile();
1534
1535   if ( theGroup1->_is_nil() || theGroup2->_is_nil() )
1536     THROW_SALOME_CORBA_EXCEPTION("CutGroups(): NULL Group",
1537                                  SALOME::BAD_PARAM);
1538   if ( theGroup1->GetType() != theGroup2->GetType() )
1539     THROW_SALOME_CORBA_EXCEPTION("CutGroups(): different group types",
1540                                  SALOME::BAD_PARAM);
1541   TPythonDump pyDump;
1542
1543   aResGrp = CreateGroup( theGroup1->GetType(), theName );
1544   if ( aResGrp->_is_nil() )
1545     return aResGrp._retn();
1546
1547   SMESHDS_GroupBase* groupDS1 = 0;
1548   if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( theGroup1 ))
1549     groupDS1 = grp_i->GetGroupDS();
1550
1551   SMESHDS_GroupBase* groupDS2 = 0;
1552   if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( theGroup2 ))
1553     groupDS2 = grp_i->GetGroupDS();
1554
1555   SMESHDS_Group* resGroupDS = 0;
1556   if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( aResGrp ))
1557     resGroupDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() );
1558
1559   if ( groupDS1 && groupDS2 && resGroupDS )
1560   {
1561     SMDS_ElemIteratorPtr elemIt1 = groupDS1->GetElements();
1562     while ( elemIt1->more() )
1563     {
1564       const SMDS_MeshElement* e = elemIt1->next();
1565       if ( !groupDS2->Contains( e ))
1566         resGroupDS->SMDSGroup().Add( e );
1567     }
1568   }
1569   // Update Python script
1570   pyDump << aResGrp << " = " << SMESH::SMESH_Mesh_var(_this()) << ".CutGroups( "
1571          << theGroup1 << ", " << theGroup2 << ", '" << theName << "')";
1572
1573   SMESH_CATCH( SMESH::throwCorbaException );
1574
1575   return aResGrp._retn();
1576 }
1577
1578 //=============================================================================
1579 /*!
1580   \brief Cut lists of groups. New group is created. All mesh elements that are
1581   present in main groups but do not present in tool groups are added to the new one
1582   \param theMainGroups list of main groups
1583   \param theToolGroups list of tool groups
1584   \param theName name of group to be created
1585   \return pointer on the group
1586 */
1587 //=============================================================================
1588
1589 SMESH::SMESH_Group_ptr
1590 SMESH_Mesh_i::CutListOfGroups(const SMESH::ListOfGroups& theMainGroups,
1591                               const SMESH::ListOfGroups& theToolGroups,
1592                               const char*                theName )
1593 {
1594   SMESH::SMESH_Group_var aResGrp;
1595
1596   SMESH_TRY;
1597
1598   if ( _preMeshInfo )
1599     _preMeshInfo->FullLoadFromFile();
1600
1601   if ( !theName )
1602     return SMESH::SMESH_Group::_nil();
1603
1604   // check types and get SMESHDS_GroupBase's
1605   SMESH::ElementType aType = SMESH::ALL;
1606   vector< SMESHDS_GroupBase* >   toolGroupVec;
1607   vector< SMDS_ElemIteratorPtr > mainIterVec;
1608
1609   for ( int g = 0, n = theMainGroups.length(); g < n; g++ )
1610   {
1611     SMESH::SMESH_GroupBase_var aGrp = theMainGroups[ g ];
1612     if ( CORBA::is_nil( aGrp ) )
1613       continue;
1614     if ( aType == SMESH::ALL )
1615       aType = aGrp->GetType();
1616     else if ( aType != aGrp->GetType() )
1617       THROW_SALOME_CORBA_EXCEPTION("CutListOfGroups(): different group types",
1618                                    SALOME::BAD_PARAM);
1619     if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( aGrp ))
1620       if ( SMESHDS_GroupBase* grpDS = grp_i->GetGroupDS() )
1621         if ( !grpDS->IsEmpty() )
1622           mainIterVec.push_back( grpDS->GetElements() );
1623   }
1624   if ( aType == SMESH::ALL ) // all main groups are nil
1625     return SMESH::SMESH_Group::_nil();
1626   if ( mainIterVec.empty() ) // all main groups are empty
1627     return aResGrp._retn();
1628
1629   for ( int g = 0, n = theToolGroups.length(); g < n; g++ )
1630   {
1631     SMESH::SMESH_GroupBase_var aGrp = theToolGroups[ g ];
1632     if ( CORBA::is_nil( aGrp ) )
1633       continue;
1634     if ( aType != aGrp->GetType() )
1635       THROW_SALOME_CORBA_EXCEPTION("CutListOfGroups(): different group types",
1636                                    SALOME::BAD_PARAM);
1637     if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( aGrp ))
1638       if ( SMESHDS_GroupBase* grpDS = grp_i->GetGroupDS() )
1639         toolGroupVec.push_back( grpDS );
1640   }
1641
1642   TPythonDump pyDump;
1643
1644   // Create a group
1645   aResGrp = CreateGroup( aType, theName );
1646
1647   SMESHDS_Group* resGroupDS = 0;
1648   if ( SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( aResGrp ))
1649     resGroupDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() );
1650   if ( !resGroupDS )
1651     return aResGrp._retn();
1652
1653   // Fill the group
1654   size_t i, nb = toolGroupVec.size();
1655   SMDS_ElemIteratorPtr mainElemIt
1656     ( new SMDS_IteratorOnIterators
1657       < const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > >( mainIterVec ));
1658   while ( mainElemIt->more() )
1659   {
1660     const SMDS_MeshElement* e = mainElemIt->next();
1661     bool isIn = false;
1662     for ( i = 0; ( i < nb && !isIn ); ++i )
1663       isIn = toolGroupVec[i]->Contains( e );
1664
1665     if ( !isIn )
1666       resGroupDS->SMDSGroup().Add( e );
1667   }
1668
1669   // Update Python script
1670   pyDump << aResGrp << " = " << SMESH::SMESH_Mesh_var( _this() )
1671          << ".CutListOfGroups( " << theMainGroups << ", "
1672          << theToolGroups << ", '" << theName << "' )";
1673
1674   SMESH_CATCH( SMESH::throwCorbaException );
1675
1676   return aResGrp._retn();
1677 }
1678
1679 namespace // functions making checks according to SMESH::NB_COMMON_NODES_ENUM
1680 {
1681   bool isAllNodesCommon(int nbChecked, int nbCommon, int nbNodes, int /*nbCorners*/,
1682                         bool & toStopChecking )
1683   {
1684     toStopChecking = ( nbCommon < nbChecked );
1685     return nbCommon == nbNodes;
1686   }
1687   bool isMainNodesCommon(int nbChecked, int nbCommon, int /*nbNodes*/, int nbCorners,
1688                          bool & toStopChecking )
1689   {
1690     toStopChecking = ( nbCommon < nbChecked || nbChecked >= nbCorners );
1691     return nbCommon == nbCorners;
1692   }
1693   bool isAtLeastOneNodeCommon(int /*nbChecked*/, int nbCommon, int /*nbNodes*/, int /*nbCorners*/,
1694                               bool & /*toStopChecking*/ )
1695   {
1696     return nbCommon > 0;
1697   }
1698   bool isMajorityOfNodesCommon(int /*nbChecked*/, int nbCommon, int nbNodes, int /*nbCorners*/,
1699                                bool & /*toStopChecking*/ )
1700   {
1701     return nbCommon >= (nbNodes+1) / 2;
1702   }
1703 }
1704
1705 //=============================================================================
1706 /*!
1707  * Create a group of entities basing on nodes of other groups.
1708  *  \param [in] theGroups - list of either groups, sub-meshes or filters.
1709  *  \param [in] anElemType - a type of elements to include to the new group.
1710  *  \param [in] theName - a name of the new group.
1711  *  \param [in] theNbCommonNodes - criterion of inclusion of an element to the new group.
1712  *  \param [in] theUnderlyingOnly - if \c True, an element is included to the
1713  *         new group provided that it is based on nodes of an element of \a aListOfGroups
1714  *  \return SMESH_Group - the created group
1715 */
1716 // IMP 19939, bug 22010, IMP 22635
1717 //=============================================================================
1718
1719 SMESH::SMESH_Group_ptr
1720 SMESH_Mesh_i::CreateDimGroup(const SMESH::ListOfIDSources& theGroups,
1721                              SMESH::ElementType            theElemType,
1722                              const char*                   theName,
1723                              SMESH::NB_COMMON_NODES_ENUM   theNbCommonNodes,
1724                              CORBA::Boolean                theUnderlyingOnly)
1725 {
1726   SMESH::SMESH_Group_var aResGrp;
1727
1728   SMESH_TRY;
1729   if ( _preMeshInfo )
1730     _preMeshInfo->FullLoadFromFile();
1731
1732   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
1733
1734   if ( !theName || !aMeshDS )
1735     return SMESH::SMESH_Group::_nil();
1736
1737   SMDSAbs_ElementType anElemType = (SMDSAbs_ElementType)theElemType;
1738
1739   bool (*isToInclude)(int nbChecked, int nbCommon, int nbNodes, int nbCorners, bool & toStop);
1740   SMESH_Comment nbCoNoStr( "SMESH.");
1741   switch ( theNbCommonNodes ) {
1742   case SMESH::ALL_NODES   : isToInclude = isAllNodesCommon;        nbCoNoStr<<"ALL_NODES"   ;break;
1743   case SMESH::MAIN        : isToInclude = isMainNodesCommon;       nbCoNoStr<<"MAIN"        ;break;
1744   case SMESH::AT_LEAST_ONE: isToInclude = isAtLeastOneNodeCommon;  nbCoNoStr<<"AT_LEAST_ONE";break;
1745   case SMESH::MAJORITY    : isToInclude = isMajorityOfNodesCommon; nbCoNoStr<<"MAJORITY"    ;break;
1746   default: return aResGrp._retn();
1747   }
1748   int nbChecked, nbCommon, nbNodes, nbCorners;
1749
1750   // Create a group
1751
1752   TPythonDump pyDump;
1753
1754   aResGrp = CreateGroup( theElemType, theName );
1755   if ( aResGrp->_is_nil() )
1756     return SMESH::SMESH_Group::_nil();
1757
1758   SMESHDS_GroupBase* groupBaseDS =
1759     SMESH::DownCast<SMESH_GroupBase_i*>( aResGrp )->GetGroupDS();
1760   SMDS_MeshGroup& resGroupCore = static_cast< SMESHDS_Group* >( groupBaseDS )->SMDSGroup();
1761
1762   vector<bool> isNodeInGroups;
1763
1764   for ( int g = 0, n = theGroups.length(); g < n; g++ ) // loop on theGroups
1765   {
1766     SMESH::SMESH_IDSource_var aGrp = theGroups[ g ];
1767     if ( CORBA::is_nil( aGrp ) )
1768       continue;
1769     SMESH::SMESH_Mesh_var mesh = aGrp->GetMesh();
1770     if ( mesh->_is_nil() || mesh->GetId() != this->GetId() )
1771       continue;
1772
1773     SMDS_ElemIteratorPtr elIt = GetElements( aGrp, SMESH::ALL );
1774     if ( !elIt ) continue;
1775
1776     if ( theElemType == SMESH::NODE ) // get all nodes of elements
1777     {
1778       while ( elIt->more() ) {
1779         const SMDS_MeshElement* el = elIt->next();
1780         SMDS_ElemIteratorPtr nIt = el->nodesIterator();
1781         while ( nIt->more() )
1782           resGroupCore.Add( nIt->next() );
1783       }
1784     }
1785     // get elements of theElemType based on nodes of every element of group
1786     else if ( theUnderlyingOnly )
1787     {
1788       while ( elIt->more() )
1789       {
1790         const SMDS_MeshElement* el = elIt->next(); // an element of ref group
1791         TIDSortedElemSet elNodes( el->begin_nodes(), el->end_nodes() );
1792         TIDSortedElemSet checkedElems;
1793         SMDS_NodeIteratorPtr nIt = el->nodeIterator();
1794         while ( nIt->more() )
1795         {
1796           const SMDS_MeshNode* n = nIt->next();
1797           SMDS_ElemIteratorPtr elOfTypeIt = n->GetInverseElementIterator( anElemType );
1798           // check nodes of elements of theElemType around el
1799           while ( elOfTypeIt->more() )
1800           {
1801             const SMDS_MeshElement* elOfType = elOfTypeIt->next();
1802             if ( !checkedElems.insert( elOfType ).second ) continue;
1803             nbNodes   = elOfType->NbNodes();
1804             nbCorners = elOfType->NbCornerNodes();
1805             nbCommon  = 0;
1806             bool toStopChecking = false;
1807             SMDS_ElemIteratorPtr nIt2 = elOfType->nodesIterator();
1808             for ( nbChecked = 1; nIt2->more() && !toStopChecking; ++nbChecked )
1809               if ( elNodes.count( nIt2->next() ) &&
1810                    isToInclude( nbChecked, ++nbCommon, nbNodes, nbCorners, toStopChecking ))
1811               {
1812                 resGroupCore.Add( elOfType );
1813                 break;
1814               }
1815           }
1816         }
1817       }
1818     }
1819     // get all nodes of elements of groups
1820     else
1821     {
1822       while ( elIt->more() )
1823       {
1824         const SMDS_MeshElement* el = elIt->next(); // an element of group
1825         SMDS_NodeIteratorPtr nIt = el->nodeIterator();
1826         while ( nIt->more() )
1827         {
1828           const SMDS_MeshNode* n = nIt->next();
1829           if ( n->GetID() >= (int) isNodeInGroups.size() )
1830             isNodeInGroups.resize( n->GetID() + 1, false );
1831           isNodeInGroups[ n->GetID() ] = true;
1832         }
1833       }
1834     }
1835   }
1836
1837   // Get elements of theElemType based on a certain number of nodes of elements of groups
1838   if ( !theUnderlyingOnly && !isNodeInGroups.empty() )
1839   {
1840     const SMDS_MeshNode* n;
1841     vector<bool> isElemChecked( aMeshDS->MaxElementID() + 1 );
1842     const int isNodeInGroupsSize = isNodeInGroups.size();
1843     for ( int iN = 0; iN < isNodeInGroupsSize; ++iN )
1844     {
1845       if ( !isNodeInGroups[ iN ] ||
1846            !( n = aMeshDS->FindNode( iN )))
1847         continue;
1848
1849       // check nodes of elements of theElemType around n
1850       SMDS_ElemIteratorPtr elOfTypeIt = n->GetInverseElementIterator( anElemType );
1851       while ( elOfTypeIt->more() )
1852       {
1853         const SMDS_MeshElement*  elOfType = elOfTypeIt->next();
1854         vector<bool>::reference isChecked = isElemChecked[ elOfType->GetID() ];
1855         if ( isChecked )
1856           continue;
1857         isChecked = true;
1858
1859         nbNodes   = elOfType->NbNodes();
1860         nbCorners = elOfType->NbCornerNodes();
1861         nbCommon  = 0;
1862         bool toStopChecking = false;
1863         SMDS_ElemIteratorPtr nIt = elOfType->nodesIterator();
1864         for ( nbChecked = 1; nIt->more() && !toStopChecking; ++nbChecked )
1865         {
1866           const smIdType nID = nIt->next()->GetID();
1867           if ( nID < isNodeInGroupsSize && isNodeInGroups[ nID ] &&
1868                isToInclude( nbChecked, ++nbCommon, nbNodes, nbCorners, toStopChecking ))
1869           {
1870             resGroupCore.Add( elOfType );
1871             break;
1872           }
1873         }
1874       }
1875     }
1876   }
1877
1878   // Update Python script
1879   pyDump << aResGrp << " = " << SMESH::SMESH_Mesh_var( _this())
1880          << ".CreateDimGroup( "
1881          << theGroups << ", " << theElemType << ", '" << theName << "', "
1882          << nbCoNoStr << ", " << theUnderlyingOnly << ")";
1883
1884   SMESH_CATCH( SMESH::throwCorbaException );
1885
1886   return aResGrp._retn();
1887 }
1888
1889 //================================================================================
1890 /*!
1891  * \brief Distribute all faces of the mesh between groups using sharp edges and optionally
1892  *        existing 1D elements as group boundaries.
1893  *  \param [in] theSharpAngle - edge is considered sharp if an angle between normals of
1894  *              adjacent faces is more than \a sharpAngle in degrees.
1895  *  \param [in] theCreateEdges - to create 1D elements for detected sharp edges.
1896  *  \param [in] theUseExistingEdges - to use existing edges as group boundaries
1897  *  \return ListOfGroups - the created groups
1898  */
1899 //================================================================================
1900
1901 SMESH::ListOfGroups*
1902 SMESH_Mesh_i::FaceGroupsSeparatedByEdges( CORBA::Double  theSharpAngle,
1903                                           CORBA::Boolean theCreateEdges,
1904                                           CORBA::Boolean theUseExistingEdges )
1905 {
1906   if ( theSharpAngle < 0 || theSharpAngle > 180 )
1907     THROW_SALOME_CORBA_EXCEPTION("Invalid sharp angle, it must be between 0 and 180 degrees",
1908                                  SALOME::BAD_PARAM);
1909
1910   SMESH::ListOfGroups_var resultGroups = new SMESH::ListOfGroups;
1911
1912   TPythonDump pyDump;
1913
1914   SMESH_TRY;
1915   if ( _preMeshInfo )
1916     _preMeshInfo->FullLoadFromFile();
1917
1918   SMESHDS_Mesh* meshDS = _impl->GetMeshDS();
1919
1920   std::vector< SMESH_MeshAlgos::Edge > edges =
1921     SMESH_MeshAlgos::FindSharpEdges( meshDS, theSharpAngle, theUseExistingEdges );
1922
1923   if ( theCreateEdges )
1924   {
1925     std::vector<const SMDS_MeshNode *> nodes(2);
1926     for ( size_t i = 0; i < edges.size(); ++i )
1927     {
1928       nodes[0] = edges[i]._node1;
1929       nodes[1] = edges[i]._node2;
1930       if ( meshDS->FindElement( nodes, SMDSAbs_Edge ))
1931         continue;
1932       if ( edges[i]._medium )
1933         meshDS->AddEdge( edges[i]._node1, edges[i]._node2, edges[i]._medium );
1934       else
1935         meshDS->AddEdge( edges[i]._node1, edges[i]._node2 );
1936     }
1937   }
1938
1939   std::vector< std::vector< const SMDS_MeshElement* > > faceGroups =
1940     SMESH_MeshAlgos::SeparateFacesByEdges( meshDS, edges );
1941
1942   SMESH::SMESH_MeshEditor_var editor = GetMeshEditor(); // create _editor
1943
1944   resultGroups->length( faceGroups.size() );
1945   for ( size_t iG = 0; iG < faceGroups.size(); ++iG )
1946   {
1947     SMESH::SMESH_Group_var group = CreateGroup( SMESH::FACE,
1948                                                 _editor->GenerateGroupName("Group").c_str());
1949     resultGroups[iG] = SMESH::SMESH_Group::_duplicate( group );
1950
1951     SMESHDS_GroupBase* groupBaseDS =
1952       SMESH::DownCast<SMESH_GroupBase_i*>( group )->GetGroupDS();
1953     SMDS_MeshGroup& groupCore = static_cast< SMESHDS_Group* >( groupBaseDS )->SMDSGroup();
1954
1955     std::vector< const SMDS_MeshElement* >& faces = faceGroups[ iG ];
1956     for ( size_t i = 0; i < faces.size(); ++i )
1957       groupCore.Add( faces[i] );
1958   }
1959
1960   pyDump << resultGroups << " = " << SMESH::SMESH_Mesh_var(_this())
1961          << ".FaceGroupsSeparatedByEdges( "
1962          << TVar( theSharpAngle ) << ", "
1963          << theCreateEdges << ", "
1964          << theUseExistingEdges << " )";
1965
1966   SMESH_CATCH( SMESH::throwCorbaException );
1967   return resultGroups._retn();
1968
1969 }
1970
1971 //================================================================================
1972 /*!
1973  * \brief Remember GEOM group data
1974  */
1975 //================================================================================
1976
1977 void SMESH_Mesh_i::addGeomGroupData(GEOM::GEOM_Object_ptr theGeomObj,
1978                                     CORBA::Object_ptr     theSmeshObj)
1979 {
1980   if ( CORBA::is_nil( theGeomObj ) || theGeomObj->GetType() != GEOM_GROUP )
1981     return;
1982   // group SO
1983   SALOMEDS::SObject_wrap groupSO = _gen_i->ObjectToSObject( theGeomObj );
1984   if ( groupSO->_is_nil() )
1985     return;
1986   // group indices
1987   GEOM::GEOM_Gen_var               geomGen = _gen_i->GetGeomEngine( theGeomObj );
1988   GEOM::GEOM_IGroupOperations_wrap groupOp = geomGen->GetIGroupOperations();
1989   GEOM::ListOfLong_var                 ids = groupOp->GetObjects( theGeomObj );
1990
1991   // store data
1992   _geomGroupData.push_back( TGeomGroupData() );
1993   TGeomGroupData & groupData = _geomGroupData.back();
1994   // entry
1995   CORBA::String_var entry = groupSO->GetID();
1996   groupData._groupEntry = entry.in();
1997   // indices
1998   for ( CORBA::ULong i = 0; i < ids->length(); ++i )
1999     groupData._indices.insert( ids[i] );
2000   // SMESH object
2001   groupData._smeshObject = CORBA::Object::_duplicate( theSmeshObj );
2002   // shape index in SMESHDS
2003   // TopoDS_Shape shape = _gen_i->GeomObjectToShape( theGeomObj );
2004   // groupData._dsID = shape.IsNull() ? 0 : _impl->GetSubMesh( shape )->GetId();
2005 }
2006
2007 //================================================================================
2008 /*!
2009  * Remove GEOM group data relating to removed smesh object
2010  */
2011 //================================================================================
2012
2013 void SMESH_Mesh_i::removeGeomGroupData(CORBA::Object_ptr theSmeshObj)
2014 {
2015   list<TGeomGroupData>::iterator
2016     data = _geomGroupData.begin(), dataEnd = _geomGroupData.end();
2017   for ( ; data != dataEnd; ++data ) {
2018     if ( theSmeshObj->_is_equivalent( data->_smeshObject )) {
2019       _geomGroupData.erase( data );
2020       return;
2021     }
2022   }
2023 }
2024
2025 //================================================================================
2026 /*!
2027 * \brief Replace a shape in the mesh upon Break Link
2028 */
2029 //================================================================================
2030
2031 void SMESH_Mesh_i::ReplaceShape(GEOM::GEOM_Object_ptr theNewGeom)
2032 {
2033   // check if geometry changed
2034   bool geomChanged = true;
2035   GEOM::GEOM_Object_var oldGeom = GetShapeToMesh();
2036   if ( !theNewGeom->_is_nil() && !oldGeom->_is_nil() )
2037     geomChanged = ( oldGeom->GetTick() != theNewGeom->GetTick() );
2038
2039   TopoDS_Shape S = _impl->GetShapeToMesh();
2040   GEOM_Client* geomClient = _gen_i->GetShapeReader();
2041   TCollection_AsciiString aIOR;
2042   if ( geomClient->Find( S, aIOR ))
2043     geomClient->RemoveShapeFromBuffer( aIOR );
2044
2045   // clear buffer also for sub-groups
2046   SMESHDS_Mesh* meshDS = _impl->GetMeshDS();
2047   const std::set<SMESHDS_GroupBase*>& groups = meshDS->GetGroups();
2048   std::set<SMESHDS_GroupBase*>::const_iterator g = groups.begin();
2049   for (; g != groups.end(); ++g)
2050     if (const SMESHDS_GroupOnGeom* group = dynamic_cast<SMESHDS_GroupOnGeom*>(*g))
2051     {
2052       const TopoDS_Shape& s = group->GetShape();
2053       if ( geomClient->Find( s, aIOR ))
2054         geomClient->RemoveShapeFromBuffer( aIOR );
2055     }
2056
2057   // clear buffer also for sub-meshes
2058   std::map<int, SMESH_subMesh_i*>::const_iterator aSubMeshIter = _mapSubMesh_i.cbegin();
2059   for(; aSubMeshIter != _mapSubMesh_i.cend(); aSubMeshIter++) {
2060     int aShapeID = aSubMeshIter->first;
2061     const TopoDS_Shape& aSubShape = meshDS->IndexToShape(aShapeID);
2062     TCollection_AsciiString aShapeIOR;
2063     if ( geomClient->Find( aSubShape, aShapeIOR ))
2064       geomClient->RemoveShapeFromBuffer( aShapeIOR );
2065   }
2066
2067   typedef struct {
2068     int shapeID; smIdType fromID, toID; // indices of elements of a sub-mesh
2069   } TRange;
2070   std::vector< TRange > elemRanges, nodeRanges; // elements of sub-meshes
2071   std::vector< SMDS_PositionPtr > positions; // node positions
2072   if ( !geomChanged )
2073   {
2074     // store positions of elements on geometry
2075     Load();
2076     if ( meshDS->MaxNodeID()    > meshDS->NbNodes() ||
2077          meshDS->MaxElementID() > meshDS->NbElements() )
2078     {
2079       meshDS->Modified();
2080       meshDS->CompactMesh();
2081     }
2082     positions.resize( meshDS->NbNodes() + 1 );
2083     for ( SMDS_NodeIteratorPtr nodeIt = meshDS->nodesIterator(); nodeIt->more(); )
2084     {
2085       const SMDS_MeshNode* n = nodeIt->next();
2086       positions[ n->GetID() ] = n->GetPosition();
2087     }
2088
2089     // remove elements from sub-meshes to avoid their removal at hypotheses addition
2090     for ( int isNode = 0; isNode < 2; ++isNode )
2091     {
2092       std::vector< TRange > & ranges = isNode ? nodeRanges : elemRanges;
2093       ranges.reserve( meshDS->MaxShapeIndex() + 10 );
2094       ranges.push_back( TRange{ 0,0,0 });
2095       SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
2096       while ( elemIt->more() )
2097       {
2098         const SMDS_MeshElement* e = elemIt->next();
2099         const smIdType     elemID = e->GetID();
2100         const int         shapeID = e->GetShapeID();
2101         TRange &        lastRange = ranges.back();
2102         if ( lastRange.shapeID != shapeID ||
2103              lastRange.toID    != elemID )
2104           ranges.push_back( TRange{ shapeID, elemID, elemID + 1 });
2105         else
2106           lastRange.toID = elemID + 1;
2107
2108         if ( SMESHDS_SubMesh* sm = meshDS->MeshElements( shapeID ))
2109         {
2110           if ( isNode ) sm->RemoveNode( static_cast< const SMDS_MeshNode *>( e ));
2111           else          sm->RemoveElement( e );
2112         }
2113       }
2114     }
2115   }
2116
2117
2118   // update the reference to theNewGeom (needed for correct execution of a dumped python script)
2119   SMESH::SMESH_Mesh_var   me = _this();
2120   SALOMEDS::SObject_wrap aSO = _gen_i->ObjectToSObject( me );
2121   CORBA::String_var    entry = theNewGeom->GetStudyEntry();
2122   if ( !aSO->_is_nil() )
2123   {
2124     SALOMEDS::SObject_wrap aShapeRefSO;
2125     if ( aSO->FindSubObject( _gen_i->GetRefOnShapeTag(), aShapeRefSO.inout() ))
2126     {
2127       SALOMEDS::SObject_wrap    aShapeSO = _gen_i->getStudyServant()->FindObjectID( entry );
2128       SALOMEDS::StudyBuilder_var builder = _gen_i->getStudyServant()->NewBuilder();
2129       builder->Addreference( aShapeRefSO, aShapeSO );
2130     }
2131   }
2132
2133   // re-assign global hypotheses to the new shape
2134   _mainShapeTick = geomChanged ? -1 : theNewGeom->GetTick();
2135   CheckGeomModif( true );
2136
2137   if ( !geomChanged )
2138   {
2139     // restore positions of elements on geometry
2140     for ( int isNode = 0; isNode < 2; ++isNode )
2141     {
2142       std::vector< TRange > & ranges = isNode ? nodeRanges : elemRanges;
2143       for ( size_t i = 1; i < ranges.size(); ++i )
2144       {
2145         int elemID = ranges[ i ].fromID;
2146         int   toID = ranges[ i ].toID;
2147         SMESHDS_SubMesh * smDS = meshDS->NewSubMesh( ranges[ i ].shapeID );
2148         if ( isNode )
2149           for ( ; elemID < toID; ++elemID )
2150             smDS->AddNode( meshDS->FindNode( elemID ));
2151         else
2152           for ( ; elemID < toID; ++elemID )
2153             smDS->AddElement( meshDS->FindElement( elemID ));
2154
2155         if ( SMESH_subMesh* sm = _impl->GetSubMeshContaining( ranges[ i ].shapeID ))
2156           sm->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2157       }
2158     }
2159     for ( unsigned int nodeID = 1; nodeID < positions.size(); ++nodeID )
2160       if ( positions[ nodeID ])
2161         if ( SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( meshDS->FindNode( nodeID )))
2162           n->SetPosition( positions[ nodeID ], n->GetShapeID() );
2163
2164     // restore icons
2165     _gen_i->UpdateIcons( SMESH::SMESH_Mesh_var( _this() ));
2166   }
2167
2168   TPythonDump() << "SHAPERSTUDY.breakLinkForSubElements(salome.ObjectToSObject("
2169                 << me <<".GetMesh()), " << entry.in() << ")";
2170
2171   TPythonDump() <<  me << ".ReplaceShape( " << entry.in() << " )";
2172
2173 }
2174
2175 //================================================================================
2176 /*!
2177  * \brief Return new group contents if it has been changed and update group data
2178  */
2179 //================================================================================
2180
2181 enum { ONLY_IF_CHANGED, IS_BREAK_LINK, MAIN_TRANSFORMED };
2182
2183 TopoDS_Shape SMESH_Mesh_i::newGroupShape( TGeomGroupData & groupData, int how )
2184 {
2185   TopoDS_Shape newShape;
2186   SALOMEDS::SObject_wrap groupSO;
2187
2188   if ( how == IS_BREAK_LINK )
2189   {
2190     SALOMEDS::SObject_wrap meshSO = _gen_i->ObjectToSObject( groupData._smeshObject );
2191     SALOMEDS::SObject_wrap geomRefSO;
2192     if ( !meshSO->_is_nil() &&
2193          meshSO->FindSubObject( SMESH::Tag_RefOnShape, geomRefSO.inout() ))
2194     {
2195       geomRefSO->ReferencedObject( groupSO.inout() );
2196     }
2197   }
2198   else
2199   {
2200     // get geom group
2201     groupSO = _gen_i->getStudyServant()->FindObjectID( groupData._groupEntry.c_str() );
2202   }
2203
2204   if ( groupSO->_is_nil() )
2205     return newShape;
2206
2207   CORBA::Object_var      groupObj = _gen_i->SObjectToObject( groupSO );
2208   GEOM::GEOM_Object_var geomGroup = GEOM::GEOM_Object::_narrow( groupObj );
2209   if ( geomGroup->_is_nil() )
2210     return newShape;
2211
2212   // get indices of group items
2213   set<int> curIndices;
2214   GEOM::GEOM_Gen_var               geomGen = _gen_i->GetGeomEngine( geomGroup );
2215   GEOM::GEOM_IGroupOperations_wrap groupOp = geomGen->GetIGroupOperations();
2216   GEOM::ListOfLong_var                 ids = groupOp->GetObjects( geomGroup );
2217   for ( CORBA::ULong i = 0; i < ids->length(); ++i )
2218     curIndices.insert( ids[i] );
2219
2220   bool sameIndices = ( groupData._indices == curIndices );
2221   if ( how == ONLY_IF_CHANGED && sameIndices )
2222     return newShape; // group not changed
2223
2224   // update data
2225   CORBA::String_var entry = geomGroup->GetStudyEntry();
2226   groupData._groupEntry = entry.in();
2227   groupData._indices = curIndices;
2228
2229   newShape = _gen_i->GeomObjectToShape( geomGroup );
2230
2231   // check if newShape is up-to-date
2232   if ( !newShape.IsNull() && ids->length() > 0 )
2233   {
2234     bool toUpdate = ! _impl->GetMeshDS()->IsGroupOfSubShapes( newShape );
2235     if ( !toUpdate )
2236     {
2237       TopExp_Explorer exp( newShape, (TopAbs_ShapeEnum)( groupOp->GetType( geomGroup )));
2238       for ( ; exp.More() && !toUpdate; exp.Next() )
2239       {
2240         int ind = _impl->GetMeshDS()->ShapeToIndex( exp.Current() );
2241         toUpdate = ( curIndices.erase( ind ) == 0 );
2242       }
2243       if ( !curIndices.empty() )
2244         toUpdate = true;
2245     }
2246     if ( toUpdate )
2247     {
2248       GEOM_Client*    geomClient = _gen_i->GetShapeReader();
2249       CORBA::String_var groupIOR = geomGen->GetStringFromIOR( geomGroup );
2250       geomClient->RemoveShapeFromBuffer( groupIOR.in() );
2251       newShape = _gen_i->GeomObjectToShape( geomGroup );
2252     }
2253   }
2254   else
2255   {
2256     // geom group becomes empty - return empty compound
2257     TopoDS_Compound compound;
2258     BRep_Builder().MakeCompound(compound);
2259     newShape = compound;
2260   }
2261
2262   return newShape;
2263 }
2264
2265 namespace
2266 {
2267   //-----------------------------------------------------------------------------
2268   /*!
2269    * \brief Storage of shape and index used in CheckGeomGroupModif()
2270    */
2271   struct TIndexedShape
2272   {
2273     int          _index;
2274     TopoDS_Shape _shape;
2275     TIndexedShape( int i, const TopoDS_Shape& s ):_index(i), _shape(s) {}
2276   };
2277   //-----------------------------------------------------------------------------
2278   /*!
2279    * \brief Data to re-create a group on geometry
2280    */
2281   struct TGroupOnGeomData
2282   {
2283     int                 _oldID;
2284     TopoDS_Shape        _shape;
2285     SMDSAbs_ElementType _type;
2286     std::string         _name;
2287     Quantity_Color      _color;
2288
2289     TGroupOnGeomData( const SMESHDS_GroupOnGeom* group )
2290     {
2291       _oldID = group->GetID();
2292       _type  = group->GetType();
2293       _name  = group->GetStoreName();
2294       _color = group->GetColor();
2295     }
2296   };
2297
2298   //-----------------------------------------------------------------------------
2299   /*!
2300    * \brief Check if a filter is still valid after geometry removal
2301    */
2302   bool isValidGeomFilter( SMESH::Filter_var theFilter )
2303   {
2304     if ( theFilter->_is_nil() )
2305       return false;
2306     SMESH::Filter::Criteria_var criteria;
2307     theFilter->GetCriteria( criteria.out() );
2308
2309     for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
2310     {
2311       const char* thresholdID = criteria[ iCr ].ThresholdID.in();
2312       std::string entry;
2313       switch ( criteria[ iCr ].Type )
2314       {
2315       case SMESH::FT_BelongToGeom:
2316       case SMESH::FT_BelongToPlane:
2317       case SMESH::FT_BelongToCylinder:
2318       case SMESH::FT_BelongToGenSurface:
2319       case SMESH::FT_LyingOnGeom:
2320         entry = thresholdID;
2321         break;
2322       case SMESH::FT_ConnectedElements:
2323         if ( thresholdID )
2324         {
2325           entry = thresholdID;
2326           break;
2327         }
2328       default:
2329         continue;
2330       }
2331       SMESH_Gen_i*           gen = SMESH_Gen_i::GetSMESHGen();
2332       SALOMEDS::SObject_wrap  so = gen->getStudyServant()->FindObjectID( entry.c_str() );
2333       if ( so->_is_nil() )
2334         return false;
2335       CORBA::Object_var      obj = so->GetObject();
2336       GEOM::GEOM_Object_var geom = GEOM::GEOM_Object::_narrow( obj );
2337       if ( gen->GeomObjectToShape( geom ).IsNull() )
2338         return false;
2339
2340     } // loop on criteria
2341
2342     return true;
2343   }
2344 }
2345
2346 //=============================================================================
2347 /*!
2348  * \brief Update data if geometry changes
2349  *
2350  * Issue 0022501
2351  */
2352 //=============================================================================
2353
2354 void SMESH_Mesh_i::CheckGeomModif( bool theIsBreakLink )
2355 {
2356   SMESH::SMESH_Mesh_var me = _this();
2357   GEOM::GEOM_Object_var mainGO = GetShapeToMesh();
2358
2359   TPythonDump dumpNothing; // prevent any dump
2360
2361   //bool removedFromClient = false;
2362
2363   if ( mainGO->_is_nil() ) // GEOM_Client cleared or geometry removed? (IPAL52735, PAL23636)
2364   {
2365     //removedFromClient = _impl->HasShapeToMesh();
2366
2367     // try to find geometry by study reference
2368     SALOMEDS::SObject_wrap meshSO = _gen_i->ObjectToSObject( me );
2369     SALOMEDS::SObject_wrap geomRefSO, geomSO;
2370     if ( !meshSO->_is_nil() &&
2371          meshSO->FindSubObject( SMESH::Tag_RefOnShape, geomRefSO.inout() ) &&
2372          geomRefSO->ReferencedObject( geomSO.inout() ))
2373     {
2374       CORBA::Object_var geomObj = _gen_i->SObjectToObject( geomSO );
2375       mainGO = GEOM::GEOM_Object::_narrow( geomObj );
2376     }
2377
2378     if ( mainGO->_is_nil() &&    // geometry removed ==>
2379          !geomRefSO->_is_nil() ) // remove geom dependent data: sub-meshes etc.
2380     {
2381       // convert geom dependent groups into standalone ones
2382       CheckGeomGroupModif();
2383
2384       _impl->ShapeToMesh( TopoDS_Shape() );
2385
2386       // remove sub-meshes
2387       std::map<int, SMESH::SMESH_subMesh_ptr>::iterator i_sm = _mapSubMeshIor.begin();
2388       while ( i_sm != _mapSubMeshIor.end() )
2389       {
2390         SMESH::SMESH_subMesh_ptr sm = i_sm->second;
2391         ++i_sm;
2392         RemoveSubMesh( sm );
2393       }
2394       // remove all children except groups in the study
2395       SALOMEDS::StudyBuilder_var builder = _gen_i->getStudyServant()->NewBuilder();
2396       SALOMEDS::SObject_wrap so;
2397       for ( CORBA::Long tag = SMESH::Tag_RefOnShape; tag <= SMESH::Tag_LastSubMesh; ++tag )
2398         if ( meshSO->FindSubObject( tag, so.inout() ))
2399           builder->RemoveObjectWithChildren( so );
2400
2401       _gen_i->SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED" );
2402
2403       return;
2404     }
2405   }
2406
2407   if ( !_impl->HasShapeToMesh() ) return;
2408
2409
2410   // Update after group modification
2411
2412   const bool geomChanged = ( mainGO->GetTick() != _mainShapeTick );
2413   if ( !theIsBreakLink )
2414     if ( mainGO->GetType() == GEOM_GROUP || !geomChanged )  // is group or not modified
2415     {
2416       smIdType nb = NbNodes() + NbElements();
2417       CheckGeomGroupModif();
2418       if ( nb != NbNodes() + NbElements() ) // something removed due to hypotheses change
2419         _gen_i->UpdateIcons( me );
2420       return;
2421     }
2422
2423   // Update after shape modification or breakLink w/o geometry change
2424
2425   GEOM_Client* geomClient = _gen_i->GetShapeReader();
2426   if ( !geomClient ) return;
2427   GEOM::GEOM_Gen_var geomGen = _gen_i->GetGeomEngine( mainGO );
2428   if ( geomGen->_is_nil() ) return;
2429   CORBA::String_var geomComponentType = geomGen->ComponentDataType();
2430   bool isShaper = ( strcmp( geomComponentType.in(), "SHAPERSTUDY" ) == 0 );
2431
2432   SMESHDS_Mesh * meshDS = _impl->GetMeshDS();
2433
2434   TopoDS_Shape newShape = _gen_i->GeomObjectToShape( mainGO );
2435   if ( meshDS->ShapeToIndex( newShape ) == 1 ) // not yet updated
2436   {
2437     CORBA::String_var ior = geomGen->GetStringFromIOR( mainGO );
2438     geomClient->RemoveShapeFromBuffer( ior.in() );
2439     newShape = _gen_i->GeomObjectToShape( mainGO );
2440   }
2441
2442   // Update data taking into account that if topology doesn't change
2443   // all sub-shapes change but IDs of sub-shapes remain (except for geom groups)
2444
2445   if ( _preMeshInfo )
2446     _preMeshInfo->ForgetAllData();
2447
2448   if ( geomChanged || !isShaper )
2449     _impl->Clear();
2450   if ( newShape.IsNull() )
2451     return;
2452
2453   _mainShapeTick = mainGO->GetTick();
2454
2455   // store data of groups on geometry including new TopoDS_Shape's
2456   std::vector< TGroupOnGeomData > groupsData;
2457   const std::set<SMESHDS_GroupBase*>& groups = meshDS->GetGroups();
2458   groupsData.reserve( groups.size() );
2459   TopTools_DataMapOfShapeShape old2newShapeMap;
2460   std::set<SMESHDS_GroupBase*>::const_iterator g = groups.begin();
2461   for ( ; g != groups.end(); ++g )
2462   {
2463     if ( const SMESHDS_GroupOnGeom* group = dynamic_cast< SMESHDS_GroupOnGeom* >( *g ))
2464     {
2465       groupsData.push_back( TGroupOnGeomData( group ));
2466
2467       // get a new shape
2468       SMESH::SMESH_GroupOnGeom_var gog;
2469       std::map<int, SMESH::SMESH_GroupBase_ptr>::iterator i_grp = _mapGroups.find( group->GetID() );
2470       if ( i_grp != _mapGroups.end() )
2471         gog = SMESH::SMESH_GroupOnGeom::_narrow( i_grp->second );
2472
2473       GEOM::GEOM_Object_var geom;
2474       if ( !gog->_is_nil() )
2475       {
2476         if ( !theIsBreakLink )
2477           geom = gog->GetShape();
2478
2479         if ( theIsBreakLink || geom->_is_nil() )
2480         {
2481           SALOMEDS::SObject_wrap grpSO = _gen_i->ObjectToSObject( gog );
2482           SALOMEDS::SObject_wrap geomRefSO, geomSO;
2483           if ( !grpSO->_is_nil() &&
2484                grpSO->FindSubObject( SMESH::Tag_RefOnShape, geomRefSO.inout() ) &&
2485                geomRefSO->ReferencedObject( geomSO.inout() ))
2486           {
2487             CORBA::Object_var geomObj = _gen_i->SObjectToObject( geomSO );
2488             geom = GEOM::GEOM_Object::_narrow( geomObj );
2489           }
2490         }
2491       }
2492       if ( old2newShapeMap.IsBound( group->GetShape() ))
2493       {
2494         groupsData.back()._shape = old2newShapeMap( group->GetShape() );
2495       }
2496       else if ( !geom->_is_nil() )
2497       {
2498         groupsData.back()._shape = _gen_i->GeomObjectToShape( geom );
2499         if ( meshDS->IsGroupOfSubShapes( groupsData.back()._shape ))
2500         {
2501           CORBA::String_var ior = geomGen->GetStringFromIOR( geom );
2502           geomClient->RemoveShapeFromBuffer( ior.in() );
2503           groupsData.back()._shape = _gen_i->GeomObjectToShape( geom );
2504         }
2505         old2newShapeMap.Bind( group->GetShape(), groupsData.back()._shape );
2506       }
2507       
2508     }
2509   }
2510   // store assigned hypotheses
2511   std::vector< pair< int, THypList > > ids2Hyps;
2512   const ShapeToHypothesis & hyps = meshDS->GetHypotheses();
2513   for ( ShapeToHypothesis::Iterator s2hyps( hyps ); s2hyps.More(); s2hyps.Next() )
2514   {
2515     const TopoDS_Shape& s = s2hyps.Key();
2516     const THypList&  hyps = s2hyps.ChangeValue();
2517     ids2Hyps.push_back( make_pair( meshDS->ShapeToIndex( s ), hyps ));
2518   }
2519
2520   std::multimap< std::set<int>, int > ii2iMap; // group sub-ids to group id in SMESHDS
2521
2522   // count shapes excluding compounds corresponding to geom groups
2523   int oldNbSubShapes = meshDS->MaxShapeIndex();
2524   for ( ; oldNbSubShapes > 0; --oldNbSubShapes )
2525   {
2526     const TopoDS_Shape& s = meshDS->IndexToShape( oldNbSubShapes );
2527     if ( s.IsNull() || s.ShapeType() != TopAbs_COMPOUND )
2528       break;
2529     // fill ii2iMap
2530     std::set<int> subIds;
2531     for ( TopoDS_Iterator it( s ); it.More(); it.Next() )
2532       subIds.insert( meshDS->ShapeToIndex( it.Value() ));
2533     ii2iMap.insert( std::make_pair( subIds, oldNbSubShapes ));
2534   }
2535
2536   // check if shape topology changes - save shape type per shape ID
2537   std::vector< TopAbs_ShapeEnum > shapeTypes( Max( oldNbSubShapes + 1, 1 ));
2538   for ( int shapeID = oldNbSubShapes; shapeID > 0; --shapeID )
2539     shapeTypes[ shapeID ] = meshDS->IndexToShape( shapeID ).ShapeType();
2540
2541   // change shape to mesh
2542   _impl->ShapeToMesh( TopoDS_Shape() );
2543   _impl->ShapeToMesh( newShape );
2544
2545   // check if shape topology changes - check new shape types
2546   bool sameTopology = ( oldNbSubShapes == meshDS->MaxShapeIndex() );
2547   for ( int shapeID = oldNbSubShapes; shapeID > 0 &&  sameTopology; --shapeID )
2548   {
2549     const TopoDS_Shape& s = meshDS->IndexToShape( shapeID );
2550     sameTopology = ( !s.IsNull() && s.ShapeType() == shapeTypes[ shapeID ]);
2551   }
2552
2553   // re-add shapes (compounds) of geom groups
2554   typedef std::map< std::vector< int >, TGeomGroupData* > TIndices2GroupData;
2555   TIndices2GroupData ii2grData;
2556   std::vector< int > ii;
2557   std::map< int, int > old2newIDs; // group IDs
2558   std::list<TGeomGroupData>::iterator dataIt = _geomGroupData.begin();
2559   for ( ; dataIt != _geomGroupData.end(); ++dataIt )
2560   {
2561     TGeomGroupData* data = &(*dataIt);
2562     ii.reserve( data->_indices.size() );
2563     ii.assign( data->_indices.begin(), data->_indices.end() );
2564     TIndices2GroupData::iterator ii2gd = ii2grData.insert( std::make_pair( ii, data )).first;
2565     if ( ii2gd->second != data )
2566     {
2567       data->_groupEntry = ii2gd->second->_groupEntry;
2568       data->_indices    = ii2gd->second->_indices;
2569       continue;
2570     }
2571     const int  oldNbSub = data->_indices.size();
2572     const int soleOldID = oldNbSub == 1 ? *data->_indices.begin() : 0;
2573     int oldID = 0;
2574     std::multimap< std::set<int>, int >::iterator ii2i = ii2iMap.find( data->_indices );
2575     if ( ii2i != ii2iMap.end() )
2576     {
2577       oldID = ii2i->second;
2578       ii2iMap.erase( ii2i );
2579     }
2580     if ( !oldID && oldNbSub == 1 )
2581       oldID = soleOldID;
2582     if ( old2newIDs.count( oldID ))
2583       continue;
2584
2585     int how = ( theIsBreakLink || !sameTopology ) ? IS_BREAK_LINK : MAIN_TRANSFORMED;
2586     newShape = newGroupShape( *data, how );
2587
2588     if ( !newShape.IsNull() )
2589     {
2590       if ( oldNbSub > 1 && meshDS->ShapeToIndex( newShape ) > 0 ) // group reduced to one sub-shape
2591       {
2592         TopoDS_Compound compound;
2593         BRep_Builder().MakeCompound( compound );
2594         BRep_Builder().Add( compound, newShape );
2595         newShape = compound;
2596       }
2597       int newID = _impl->GetSubMesh( newShape )->GetId();
2598       if ( oldID /*&& oldID != newID*/ )
2599         old2newIDs.insert( std::make_pair( oldID, newID ));
2600       if ( oldNbSub == 1 )
2601         old2newIDs.insert( std::make_pair( soleOldID, newID ));
2602     }
2603   }
2604
2605   // re-assign hypotheses
2606   for ( size_t i = 0; i < ids2Hyps.size(); ++i )
2607   {
2608     int sID = ids2Hyps[i].first;
2609     if ( sID != 1 )
2610     {
2611       std::map< int, int >::iterator o2n = old2newIDs.find( sID );
2612       if ( o2n != old2newIDs.end() )
2613         sID = o2n->second;
2614       else if ( !sameTopology )
2615         continue;
2616     }
2617     const TopoDS_Shape& s = meshDS->IndexToShape( sID );
2618     if ( s.IsNull() )
2619       continue;
2620     const THypList& hyps = ids2Hyps[i].second;
2621     THypList::const_iterator h = hyps.begin();
2622     for ( ; h != hyps.end(); ++h )
2623       _impl->AddHypothesis( s, (*h)->GetID() );
2624   }
2625
2626   {
2627     // restore groups on geometry
2628     for ( size_t i = 0; i < groupsData.size(); ++i )
2629     {
2630       const TGroupOnGeomData& data = groupsData[i];
2631       if ( data._shape.IsNull() )
2632         continue;
2633
2634       std::map<int, SMESH::SMESH_GroupBase_ptr>::iterator i2g = _mapGroups.find( data._oldID );
2635       if ( i2g == _mapGroups.end() ) continue;
2636
2637       SMESH_GroupBase_i* gr_i = SMESH::DownCast<SMESH_GroupBase_i*>( i2g->second );
2638       if ( !gr_i ) continue;
2639
2640       SMESH_Group* g = _impl->AddGroup( data._type, data._name.c_str(), data._oldID, data._shape );
2641       if ( !g )
2642         _mapGroups.erase( i2g );
2643       else
2644         g->GetGroupDS()->SetColor( data._color );
2645     }
2646
2647     if ( !sameTopology )
2648     {
2649       std::map< int, int >::iterator o2n = old2newIDs.begin();
2650       for ( ; o2n != old2newIDs.end(); ++o2n )
2651       {
2652         int newID = o2n->second, oldID = o2n->first;
2653         if ( newID == oldID || !_mapSubMesh.count( oldID ))
2654           continue;
2655         if ( newID > 0 )
2656         {
2657           _mapSubMesh   [ newID ] = _impl->GetSubMeshContaining( newID );
2658           _mapSubMesh_i [ newID ] = _mapSubMesh_i [ oldID ];
2659           _mapSubMeshIor[ newID ] = _mapSubMeshIor[ oldID ];
2660         }
2661         _mapSubMesh.   erase(oldID);
2662         _mapSubMesh_i. erase(oldID);
2663         _mapSubMeshIor.erase(oldID);
2664         if ( newID > 0 )
2665           _mapSubMesh_i [ newID ]->changeLocalId( newID );
2666       }
2667     }
2668
2669     // update _mapSubMesh
2670     std::map<int, ::SMESH_subMesh*>::iterator i_sm = _mapSubMesh.begin();
2671     for ( ; i_sm != _mapSubMesh.end(); ++i_sm )
2672       i_sm->second = _impl->GetSubMesh( meshDS->IndexToShape( i_sm->first ));
2673   }
2674
2675   if ( !sameTopology )
2676   {
2677     // remove invalid study sub-objects
2678     CheckGeomGroupModif();
2679   }
2680
2681   _gen_i->UpdateIcons( me );
2682
2683   if ( !theIsBreakLink && isShaper )
2684   {
2685     SALOMEDS::SObject_wrap meshSO = _gen_i->ObjectToSObject( me );
2686     if ( !meshSO->_is_nil() )
2687       _gen_i->SetPixMap(meshSO, "ICON_SMESH_TREE_GEOM_MODIF");
2688   }
2689 }
2690
2691 //=============================================================================
2692 /*!
2693  * \brief Update objects depending on changed geom groups
2694  *
2695  * NPAL16168: geometrical group edition from a submesh don't modify mesh computation
2696  * issue 0020210: Update of a smesh group after modification of the associated geom group
2697  */
2698 //=============================================================================
2699
2700 void SMESH_Mesh_i::CheckGeomGroupModif()
2701 {
2702   // remove sub-meshes referring a removed sub-shapes (if main shape still exists)
2703   SALOMEDS::StudyBuilder_var builder = _gen_i->getStudyServant()->NewBuilder();
2704   GEOM::GEOM_Object_var  mainGO = GetShapeToMesh();
2705   SALOMEDS::SObject_wrap meshSO = _gen_i->ObjectToSObject( SMESH::SMESH_Mesh_var( _this() ));
2706   if ( !mainGO->_is_nil() && !meshSO->_is_nil() )
2707   {
2708     SALOMEDS::SObject_wrap rootSO, geomRefSO, geomSO;
2709     for ( CORBA::Long tag = SMESH::Tag_FirstSubMesh; tag <= SMESH::Tag_LastSubMesh; ++tag )
2710       if ( meshSO->FindSubObject( tag, rootSO.inout() ))
2711       {
2712         int nbValid = 0, nbRemoved = 0;
2713         SALOMEDS::ChildIterator_wrap chItr = _gen_i->getStudyServant()->NewChildIterator( rootSO );
2714         for ( ; chItr->More(); chItr->Next() )
2715         {
2716           SALOMEDS::SObject_wrap smSO = chItr->Value(); // sub-mesh SO
2717           if ( !smSO->_is_nil() &&
2718                smSO->FindSubObject( SMESH::Tag_RefOnShape, geomRefSO.inout() ) &&
2719                geomRefSO->ReferencedObject( geomSO.inout() )) // find geometry by reference
2720           {
2721             CORBA::Object_var  geomObj = _gen_i->SObjectToObject( geomSO );
2722             GEOM::GEOM_Object_var geom = GEOM::GEOM_Object::_narrow( geomObj );
2723             if ( !geom->_non_existent() )
2724             {
2725               ++nbValid;
2726               continue; // keep the sub-mesh
2727             }
2728           }
2729           CORBA::Object_var     smObj = _gen_i->SObjectToObject( smSO );
2730           SMESH::SMESH_subMesh_var sm = SMESH::SMESH_subMesh::_narrow( smObj );
2731           if ( !sm->_is_nil() && !sm->_non_existent() )
2732           {
2733             GEOM::GEOM_Object_var smGeom = sm->GetSubShape();
2734             if ( smGeom->_is_nil() )
2735             {
2736               RemoveSubMesh( sm );
2737               ++nbRemoved;
2738             }
2739           }
2740           else
2741           {
2742             if ( _preMeshInfo )
2743               _preMeshInfo->ForgetAllData(); // unknown hypothesis modified
2744             builder->RemoveObjectWithChildren( smSO ); // sub-shape removed before loading SMESH
2745             ++nbRemoved;
2746           }
2747         }
2748         if ( /*nbRemoved > 0 &&*/ nbValid == 0 )
2749           builder->RemoveObjectWithChildren( rootSO );
2750       }
2751   }
2752
2753   // check for removed sub-shapes and convert geom dependent groups into standalone ones
2754   std::map<int, SMESH::SMESH_GroupBase_ptr>::iterator i_gr = _mapGroups.begin();
2755   while ( i_gr != _mapGroups.end())
2756   {
2757     SMESH::SMESH_GroupBase_ptr group = i_gr->second;
2758     ++i_gr;
2759     SALOMEDS::SObject_wrap        groupSO = _gen_i->ObjectToSObject( group ), refSO, geomSO;
2760     SMESH::SMESH_GroupOnGeom_var   onGeom = SMESH::SMESH_GroupOnGeom::_narrow  ( group );
2761     SMESH::SMESH_GroupOnFilter_var onFilt = SMESH::SMESH_GroupOnFilter::_narrow( group );
2762     bool isValidGeom = false;
2763     if ( !onGeom->_is_nil() )
2764     {
2765       isValidGeom = ( ! GEOM::GEOM_Object_var( onGeom->GetShape() )->_is_nil() ); // check TopoDS
2766       if ( !isValidGeom ) // check reference
2767       {
2768         isValidGeom = ( ! groupSO->_is_nil() &&
2769                         groupSO->FindSubObject( SMESH::Tag_RefOnShape, refSO.inout() ) &&
2770                         refSO->ReferencedObject( geomSO.inout() ) &&
2771                         ! geomSO->_is_nil() &&
2772                         !CORBA::is_nil( CORBA::Object_var( geomSO->GetObject() )));
2773       }
2774     }
2775     else if ( !onFilt->_is_nil() )
2776     {
2777       isValidGeom = isValidGeomFilter( onFilt->GetFilter() );
2778     }
2779     else // standalone
2780     {
2781       isValidGeom = ( !groupSO->_is_nil() &&
2782                       !groupSO->FindSubObject( SMESH::Tag_RefOnShape, refSO.inout() ));
2783     }
2784     if ( !isValidGeom )
2785     {
2786       if ( !IsLoaded() || group->IsEmpty() )
2787       {
2788         RemoveGroup( group );
2789       }
2790       else if ( !onGeom->_is_nil() || !onFilt->_is_nil() )
2791       {
2792         SMESH::SMESH_Group_var ( ConvertToStandalone( group ));
2793       }
2794       else // is it possible?
2795       {
2796         builder->RemoveObjectWithChildren( refSO );
2797       }
2798     }
2799   }
2800
2801
2802   if ( !_impl->HasShapeToMesh() ) return;
2803
2804   SMESH::smIdType nbEntities = NbNodes() + NbElements();
2805
2806   // Check if group contents changed
2807
2808   typedef map< string, TopoDS_Shape > TEntry2Geom;
2809   TEntry2Geom newGroupContents;
2810
2811   list<TGeomGroupData>::iterator
2812     data = _geomGroupData.begin(), dataEnd = _geomGroupData.end();
2813   for ( ; data != dataEnd; ++data )
2814   {
2815     pair< TEntry2Geom::iterator, bool > it_new =
2816       newGroupContents.insert( make_pair( data->_groupEntry, TopoDS_Shape() ));
2817     bool processedGroup    = !it_new.second;
2818     TopoDS_Shape& newShape = it_new.first->second;
2819     if ( !processedGroup )
2820       newShape = newGroupShape( *data, ONLY_IF_CHANGED );
2821     if ( newShape.IsNull() )
2822       continue; // no changes
2823
2824     if ( _preMeshInfo )
2825       _preMeshInfo->ForgetOrLoad();
2826
2827     if ( processedGroup ) { // update group indices
2828       list<TGeomGroupData>::iterator data2 = data;
2829       for ( --data2; data2->_groupEntry != data->_groupEntry; --data2) {}
2830       data->_indices = data2->_indices;
2831     }
2832
2833     // Update SMESH objects according to new GEOM group contents
2834
2835     SMESH::SMESH_subMesh_var submesh = SMESH::SMESH_subMesh::_narrow( data->_smeshObject );
2836     if ( !submesh->_is_nil() ) // -------------- Sub mesh ---------------------
2837     {
2838       int oldID = submesh->GetId();
2839       if ( !_mapSubMeshIor.count( oldID ))
2840         continue;
2841       TopoDS_Shape oldShape = _mapSubMesh[oldID]->GetSubShape();
2842
2843       // update hypotheses
2844       list <const SMESHDS_Hypothesis * > hyps = _impl->GetHypothesisList(oldShape);
2845       list <const SMESHDS_Hypothesis * >::iterator hypIt;
2846       for ( hypIt = hyps.begin(); hypIt != hyps.end(); ++hypIt )
2847       {
2848         _impl->RemoveHypothesis( oldShape, (*hypIt)->GetID());
2849         _impl->AddHypothesis   ( newShape, (*hypIt)->GetID());
2850       }
2851       // care of submeshes
2852       SMESH_subMesh* newSubmesh = _impl->GetSubMesh( newShape );
2853       int newID = newSubmesh->GetId();
2854       if ( newID != oldID ) {
2855         _mapSubMesh   [ newID ] = newSubmesh;
2856         _mapSubMesh_i [ newID ] = _mapSubMesh_i [ oldID ];
2857         _mapSubMeshIor[ newID ] = _mapSubMeshIor[ oldID ];
2858         _mapSubMesh.   erase(oldID);
2859         _mapSubMesh_i. erase(oldID);
2860         _mapSubMeshIor.erase(oldID);
2861         _mapSubMesh_i [ newID ]->changeLocalId( newID );
2862       }
2863       continue;
2864     }
2865
2866     SMESH::SMESH_GroupOnGeom_var smeshGroup =
2867       SMESH::SMESH_GroupOnGeom::_narrow( data->_smeshObject );
2868     if ( !smeshGroup->_is_nil() ) // ------------ GROUP -----------------------
2869     {
2870       SMESH_GroupOnGeom_i* group_i = SMESH::DownCast<SMESH_GroupOnGeom_i*>( smeshGroup );
2871       if ( group_i ) {
2872         ::SMESH_Group* group = _impl->GetGroup( group_i->GetLocalID() );
2873         SMESHDS_GroupOnGeom* ds = static_cast<SMESHDS_GroupOnGeom*>( group->GetGroupDS() );
2874         ds->SetShape( newShape );
2875       }
2876       continue;
2877     }
2878
2879     SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( data->_smeshObject );
2880     if ( !mesh->_is_nil() ) // -------------- MESH ----------------------------
2881     {
2882       // Remove groups and submeshes basing on removed sub-shapes
2883
2884       TopTools_MapOfShape newShapeMap;
2885       TopoDS_Iterator shapeIt( newShape );
2886       for ( ; shapeIt.More(); shapeIt.Next() )
2887         newShapeMap.Add( shapeIt.Value() );
2888
2889       SMESHDS_Mesh* meshDS = _impl->GetMeshDS();
2890       for ( shapeIt.Initialize( meshDS->ShapeToMesh() ); shapeIt.More(); shapeIt.Next() )
2891       {
2892         if ( newShapeMap.Contains( shapeIt.Value() ))
2893           continue;
2894         TopTools_IndexedMapOfShape oldShapeMap;
2895         TopExp::MapShapes( shapeIt.Value(), oldShapeMap );
2896         for ( int i = 1; i <= oldShapeMap.Extent(); ++i )
2897         {
2898           const TopoDS_Shape& oldShape = oldShapeMap(i);
2899           int oldInd = meshDS->ShapeToIndex( oldShape );
2900           // -- submeshes --
2901           map<int, SMESH::SMESH_subMesh_ptr>::iterator i_smIor = _mapSubMeshIor.find( oldInd );
2902           if ( i_smIor != _mapSubMeshIor.end() ) {
2903             RemoveSubMesh( i_smIor->second ); // one submesh per shape index
2904           }
2905           // --- groups ---
2906           map<int, SMESH::SMESH_GroupBase_ptr>::iterator i_grp = _mapGroups.begin();
2907           for ( ; i_grp != _mapGroups.end(); ++i_grp )
2908           {
2909             // check if a group bases on oldInd shape
2910             SMESHDS_GroupOnGeom* grpOnGeom = 0;
2911             if ( ::SMESH_Group* g = _impl->GetGroup( i_grp->first ))
2912               grpOnGeom = dynamic_cast<SMESHDS_GroupOnGeom*>( g->GetGroupDS() );
2913             if ( grpOnGeom && oldShape.IsSame( grpOnGeom->GetShape() ))
2914             { // remove
2915               RemoveGroup( i_grp->second ); // several groups can base on same shape
2916               i_grp = _mapGroups.begin(); // _mapGroups changed - restart iteration
2917             }
2918           }
2919         }
2920       }
2921       // Reassign hypotheses and update groups after setting the new shape to mesh
2922
2923       // collect anassigned hypotheses
2924       typedef list< pair< TIndexedShape, list<const SMESHDS_Hypothesis*> > > TShapeHypList;
2925       list <const SMESHDS_Hypothesis * >::const_iterator hypIt;
2926       TShapeHypList assignedHyps;
2927       for ( int i = 1; i <= meshDS->MaxShapeIndex(); ++i )
2928       {
2929         const TopoDS_Shape& oldShape = meshDS->IndexToShape(i);
2930         list<const SMESHDS_Hypothesis*> hyps = meshDS->GetHypothesis( oldShape );// copy
2931         if ( !hyps.empty() ) {
2932           assignedHyps.push_back( make_pair( TIndexedShape(i,oldShape), hyps ));
2933           for ( hypIt = hyps.begin(); hypIt != hyps.end(); ++hypIt )
2934             _impl->RemoveHypothesis( oldShape, (*hypIt)->GetID());
2935         }
2936       }
2937       // collect shapes supporting groups
2938       typedef list < pair< TIndexedShape, SMDSAbs_ElementType > > TShapeTypeList;
2939       TShapeTypeList groupData;
2940       const set<SMESHDS_GroupBase*>& groups = meshDS->GetGroups();
2941       set<SMESHDS_GroupBase*>::const_iterator grIt = groups.begin();
2942       for ( ; grIt != groups.end(); ++grIt )
2943       {
2944         if ( SMESHDS_GroupOnGeom* gog = dynamic_cast<SMESHDS_GroupOnGeom*>( *grIt ))
2945           groupData.push_back
2946             ( make_pair( TIndexedShape( gog->GetID(),gog->GetShape()), gog->GetType()));
2947       }
2948       // set new shape to mesh -> DS of sub-meshes and geom groups is deleted
2949       _impl->Clear();
2950       _impl->ShapeToMesh( TopoDS_Shape() ); // IPAL52730
2951       _impl->ShapeToMesh( newShape );
2952
2953       // reassign hypotheses
2954       TShapeHypList::iterator indS_hyps = assignedHyps.begin();
2955       for ( ; indS_hyps != assignedHyps.end(); ++indS_hyps )
2956       {
2957         TIndexedShape&                   geom = indS_hyps->first;
2958         list<const SMESHDS_Hypothesis*>& hyps = indS_hyps->second;
2959         int oldID = geom._index;
2960         int newID = meshDS->ShapeToIndex( geom._shape );
2961         if ( oldID == 1 ) { // main shape
2962           newID = 1;
2963           geom._shape = newShape;
2964         }
2965         if ( !newID )
2966           continue;
2967         for ( hypIt = hyps.begin(); hypIt != hyps.end(); ++hypIt )
2968           _impl->AddHypothesis( geom._shape, (*hypIt)->GetID());
2969         // care of sub-meshes
2970         SMESH_subMesh* newSubmesh = _impl->GetSubMesh( geom._shape );
2971         if ( newID != oldID ) {
2972           _mapSubMesh   [ newID ] = newSubmesh;
2973           _mapSubMesh_i [ newID ] = _mapSubMesh_i [ oldID ];
2974           _mapSubMeshIor[ newID ] = _mapSubMeshIor[ oldID ];
2975           _mapSubMesh.   erase(oldID);
2976           _mapSubMesh_i. erase(oldID);
2977           _mapSubMeshIor.erase(oldID);
2978           _mapSubMesh_i [ newID ]->changeLocalId( newID );
2979         }
2980       }
2981       // recreate groups
2982       TShapeTypeList::iterator geomType = groupData.begin();
2983       for ( ; geomType != groupData.end(); ++geomType )
2984       {
2985         const TIndexedShape& geom = geomType->first;
2986         int oldID = geom._index;
2987         if ( _mapGroups.find( oldID ) == _mapGroups.end() )
2988           continue;
2989         // get group name
2990         SALOMEDS::SObject_wrap groupSO = _gen_i->ObjectToSObject( _mapGroups[oldID] );
2991         CORBA::String_var      name    = groupSO->GetName();
2992         // update
2993         if ( SMESH_GroupBase_i* group_i = SMESH::DownCast<SMESH_GroupBase_i*>(_mapGroups[oldID]))
2994           if ( SMESH_Group* group = _impl->AddGroup( geomType->second, name.in(),
2995                                                      /*id=*/-1, geom._shape ))
2996             group_i->changeLocalId( group->GetID() );
2997       }
2998
2999       break; // everything has been updated
3000
3001     } // update mesh
3002   } // loop on group data
3003
3004   // Update icons
3005
3006   SMESH::smIdType newNbEntities = NbNodes() + NbElements();
3007   list< SALOMEDS::SObject_wrap > soToUpdateIcons;
3008   if ( newNbEntities != nbEntities )
3009   {
3010     // Add all SObjects with icons to soToUpdateIcons
3011     soToUpdateIcons.push_back( _gen_i->ObjectToSObject( _this() )); // mesh
3012
3013     for (map<int, SMESH::SMESH_subMesh_ptr>::iterator i_sm = _mapSubMeshIor.begin();
3014          i_sm != _mapSubMeshIor.end(); ++i_sm ) // submeshes
3015       soToUpdateIcons.push_back( _gen_i->ObjectToSObject( i_sm->second ));
3016
3017     for ( map<int, SMESH::SMESH_GroupBase_ptr>::iterator i_gr = _mapGroups.begin();
3018           i_gr != _mapGroups.end(); ++i_gr ) // groups
3019       soToUpdateIcons.push_back( _gen_i->ObjectToSObject( i_gr->second ));
3020   }
3021
3022   list< SALOMEDS::SObject_wrap >::iterator so = soToUpdateIcons.begin();
3023   for ( ; so != soToUpdateIcons.end(); ++so )
3024     _gen_i->SetPixMap( *so, "ICON_SMESH_TREE_MESH_WARN" );
3025 }
3026
3027 //=============================================================================
3028 /*!
3029  * \brief Create standalone group from a group on geometry or filter
3030  */
3031 //=============================================================================
3032
3033 SMESH::SMESH_Group_ptr SMESH_Mesh_i::ConvertToStandalone( SMESH::SMESH_GroupBase_ptr theGroup )
3034 {
3035   SMESH::SMESH_Group_var aGroup;
3036
3037   SMESH_TRY;
3038
3039   if ( _preMeshInfo )
3040     _preMeshInfo->FullLoadFromFile();
3041
3042   if ( theGroup->_is_nil() )
3043     return aGroup._retn();
3044
3045   SMESH_GroupBase_i* aGroupToRem = SMESH::DownCast<SMESH_GroupBase_i*>( theGroup );
3046   if ( !aGroupToRem )
3047     return aGroup._retn();
3048
3049   const bool isOnFilter = ( SMESH::DownCast< SMESH_GroupOnFilter_i* > ( theGroup ));
3050
3051   const int anId = aGroupToRem->GetLocalID();
3052   if ( !_impl->ConvertToStandalone( anId ) )
3053     return aGroup._retn();
3054   removeGeomGroupData( theGroup );
3055
3056   SMESH_GroupBase_i* aGroupImpl = new SMESH_Group_i( SMESH_Gen_i::GetPOA(), this, anId );
3057
3058   // remove old instance of group from own map
3059   { SMESH::SMESH_GroupBase_var var( _mapGroups[anId] ); } // decref CORBA object
3060   _mapGroups.erase( anId );
3061
3062   SALOMEDS::StudyBuilder_var builder;
3063   SALOMEDS::SObject_wrap     aGroupSO;
3064   SALOMEDS::Study_var        aStudy = SMESH_Gen_i::GetSMESHGen()->getStudyServant();
3065   if ( !aStudy->_is_nil() ) {
3066     builder  = aStudy->NewBuilder();
3067     aGroupSO = _gen_i->ObjectToSObject( theGroup );
3068     if ( !aGroupSO->_is_nil() )
3069     {
3070       // remove reference to geometry
3071       SALOMEDS::ChildIterator_wrap chItr = aStudy->NewChildIterator(aGroupSO);
3072       for ( ; chItr->More(); chItr->Next() )
3073       {
3074         // Remove group's child SObject
3075         SALOMEDS::SObject_wrap so = chItr->Value();
3076         builder->RemoveObject( so );
3077       }
3078       // Update Python script
3079       TPythonDump() << aGroupSO << " = " << SMESH::SMESH_Mesh_var(_this())
3080                     << ".ConvertToStandalone( " << aGroupSO << " )";
3081
3082       // change icon of Group on Filter
3083       if ( isOnFilter )
3084       {
3085         // SMESH::array_of_ElementType_var elemTypes = aGroupImpl->GetTypes();
3086         // const int isEmpty = ( elemTypes->length() == 0 );
3087         // if ( !isEmpty )
3088         {
3089           SALOMEDS::GenericAttribute_wrap anAttr =
3090             builder->FindOrCreateAttribute( aGroupSO, "AttributePixMap" );
3091           SALOMEDS::AttributePixMap_wrap pm = anAttr;
3092           pm->SetPixMap( "ICON_SMESH_TREE_GROUP" );
3093         }
3094       }
3095     }
3096   }
3097
3098   // remember new group in own map
3099   aGroup = SMESH::SMESH_Group::_narrow( aGroupImpl->_this() );
3100   _mapGroups[anId] = SMESH::SMESH_GroupBase::_duplicate( aGroup );
3101
3102   // register CORBA object for persistence
3103   _gen_i->RegisterObject( aGroup );
3104
3105   CORBA::String_var ior = _gen_i->GetORB()->object_to_string( aGroup );
3106   builder->SetIOR( aGroupSO, ior.in() ); //  == aGroup->Register();
3107   //aGroup->Register();
3108   aGroupToRem->UnRegister();
3109
3110   SMESH_CATCH( SMESH::throwCorbaException );
3111
3112   return aGroup._retn();
3113 }
3114
3115 //================================================================================
3116 /*!
3117  * \brief Create a sub-mesh on a given sub-shape
3118  */
3119 //================================================================================
3120
3121 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::createSubMesh( GEOM::GEOM_Object_ptr theSubShapeObject )
3122 {
3123   if(MYDEBUG) MESSAGE( "createSubMesh" );
3124   TopoDS_Shape  myLocSubShape = _gen_i->GeomObjectToShape(theSubShapeObject);
3125   ::SMESH_subMesh * mySubMesh = _impl->GetSubMesh(myLocSubShape);
3126   int               subMeshId = 0;
3127
3128   SMESH_subMesh_i * subMeshServant;
3129   if ( mySubMesh )
3130   {
3131     subMeshId = mySubMesh->GetId();
3132     subMeshServant = new SMESH_subMesh_i(myPOA, _gen_i, this, subMeshId);
3133   }
3134   else // "invalid sub-mesh"
3135   {
3136     // The invalid sub-mesh is created for the case where a valid sub-shape not found
3137     // by SMESH_Gen_i::CopyMeshWithGeom(). The invalid sub-mesh has GetId() < 0.
3138     if ( _mapSubMesh.empty() )
3139       subMeshId = -1;
3140     else
3141       subMeshId = _mapSubMesh.begin()->first - 1;
3142     subMeshServant = new SMESH_Invalid_subMesh_i(myPOA, _gen_i, this, subMeshId, theSubShapeObject);
3143   }
3144
3145   SMESH::SMESH_subMesh_var subMesh = subMeshServant->_this();
3146
3147   _mapSubMesh   [subMeshId] = mySubMesh;
3148   _mapSubMesh_i [subMeshId] = subMeshServant;
3149   _mapSubMeshIor[subMeshId] = SMESH::SMESH_subMesh::_duplicate( subMesh );
3150
3151   subMeshServant->Register();
3152
3153   // register CORBA object for persistence
3154   int nextId = _gen_i->RegisterObject( subMesh );
3155   if(MYDEBUG) { MESSAGE( "Add submesh to map with id = "<< nextId); }
3156   else        { (void)nextId; } // avoid "unused variable" warning
3157
3158   // to track changes of GEOM groups
3159   if ( subMeshId > 0 )
3160     addGeomGroupData( theSubShapeObject, subMesh );
3161
3162   return subMesh._retn();
3163 }
3164
3165 //================================================================================
3166 /*!
3167  * \brief Return an existing sub-mesh based on a sub-shape with the given ID
3168  */
3169 //================================================================================
3170
3171 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::getSubMesh(int shapeID)
3172 {
3173   map<int, SMESH::SMESH_subMesh_ptr>::iterator it = _mapSubMeshIor.find( shapeID );
3174   if ( it == _mapSubMeshIor.end() )
3175     return SMESH::SMESH_subMesh::_nil();
3176
3177   return SMESH::SMESH_subMesh::_duplicate( (*it).second );
3178 }
3179
3180 //================================================================================
3181 /*!
3182  * \brief Remove a sub-mesh based on the given sub-shape
3183  */
3184 //================================================================================
3185
3186 bool SMESH_Mesh_i::removeSubMesh (SMESH::SMESH_subMesh_ptr theSubMesh,
3187                                   GEOM::GEOM_Object_ptr    theSubShapeObject )
3188 {
3189   bool isHypChanged = false;
3190   if ( theSubMesh->_is_nil() /*|| theSubShapeObject->_is_nil()*/ )
3191     return isHypChanged;
3192
3193   const int subMeshId = theSubMesh->GetId();
3194
3195   if ( theSubShapeObject->_is_nil() )  // not published shape (IPAL13617)
3196   {
3197     SMESH_subMesh* sm;
3198     if (( _mapSubMesh.count( subMeshId )) &&
3199         ( sm = _impl->GetSubMeshContaining( subMeshId )))
3200     {
3201       TopoDS_Shape S = sm->GetSubShape();
3202       if ( !S.IsNull() )
3203       {
3204         list<const SMESHDS_Hypothesis*> hyps = _impl->GetHypothesisList( S );
3205         isHypChanged = !hyps.empty();
3206         if ( isHypChanged && _preMeshInfo )
3207           _preMeshInfo->ForgetOrLoad();
3208         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hyps.begin();
3209         for ( ; hyp != hyps.end(); ++hyp )
3210           _impl->RemoveHypothesis(S, (*hyp)->GetID());
3211       }
3212     }
3213   }
3214   else
3215   {
3216     try {
3217       SMESH::ListOfHypothesis_var aHypList = GetHypothesisList( theSubShapeObject );
3218       isHypChanged = ( aHypList->length() > 0 );
3219       for ( int i = 0, n = aHypList->length(); i < n; i++ ) {
3220         removeHypothesis( theSubShapeObject, aHypList[i] );
3221       }
3222     }
3223     catch( const SALOME::SALOME_Exception& ) {
3224       INFOS("SMESH_Mesh_i::removeSubMesh(): exception caught!");
3225     }
3226     removeGeomGroupData( theSubShapeObject );
3227   }
3228
3229   // remove a servant
3230   std::map<int, SMESH_subMesh_i*>::iterator id_smi = _mapSubMesh_i.find( subMeshId );
3231   if ( id_smi != _mapSubMesh_i.end() )
3232     id_smi->second->UnRegister();
3233
3234   // remove a CORBA object
3235   std::map<int, SMESH::SMESH_subMesh_ptr>::iterator id_smptr = _mapSubMeshIor.find( subMeshId );
3236   if ( id_smptr != _mapSubMeshIor.end() )
3237     SMESH::SMESH_subMesh_var( id_smptr->second );
3238
3239   _mapSubMesh.erase(subMeshId);
3240   _mapSubMesh_i.erase(subMeshId);
3241   _mapSubMeshIor.erase(subMeshId);
3242
3243   return isHypChanged;
3244 }
3245
3246 //================================================================================
3247 /*!
3248  * \brief Create a group. Group type depends on given arguments
3249  */
3250 //================================================================================
3251
3252 SMESH::SMESH_GroupBase_ptr SMESH_Mesh_i::createGroup (SMESH::ElementType        theElemType,
3253                                                       const char*               theName,
3254                                                       const int                 theID,
3255                                                       const TopoDS_Shape&       theShape,
3256                                                       const SMESH_PredicatePtr& thePredicate )
3257 {
3258   std::string newName;
3259   if ( !theName || !theName[0] )
3260   {
3261     std::set< std::string > presentNames;
3262     std::map<int, SMESH::SMESH_GroupBase_ptr>::const_iterator i_gr = _mapGroups.begin();
3263     for ( ; i_gr != _mapGroups.end(); ++i_gr )
3264     {
3265       CORBA::String_var name = i_gr->second->GetName();
3266       presentNames.insert( name.in() );
3267     }
3268     do {
3269       newName = "noname_Group_" + SMESH_Comment( presentNames.size() + 1 );
3270     } while ( !presentNames.insert( newName ).second );
3271     theName = newName.c_str();
3272   }
3273   SMESH::SMESH_GroupBase_var aGroup;
3274   if ( SMESH_Group* g = _impl->AddGroup( (SMDSAbs_ElementType)theElemType, theName,
3275                                          theID, theShape, thePredicate ))
3276   {
3277     int anId = g->GetID();
3278     SMESH_GroupBase_i* aGroupImpl;
3279     if ( !theShape.IsNull() )
3280       aGroupImpl = new SMESH_GroupOnGeom_i( SMESH_Gen_i::GetPOA(), this, anId );
3281     else if ( thePredicate )
3282       aGroupImpl = new SMESH_GroupOnFilter_i( SMESH_Gen_i::GetPOA(), this, anId );
3283     else
3284       aGroupImpl = new SMESH_Group_i( SMESH_Gen_i::GetPOA(), this, anId );
3285
3286     aGroup = aGroupImpl->_this();
3287     _mapGroups[anId] = SMESH::SMESH_GroupBase::_duplicate( aGroup );
3288     aGroupImpl->Register();
3289
3290     // register CORBA object for persistence
3291     int nextId = _gen_i->RegisterObject( aGroup );
3292     if(MYDEBUG) { MESSAGE( "Add group to map with id = "<< nextId); }
3293     else        { nextId = ( nextId > 0 ); } // avoid "unused variable" warning in release mode
3294
3295     // to track changes of GEOM groups
3296     if ( !theShape.IsNull() ) {
3297       GEOM::GEOM_Object_var geom = _gen_i->ShapeToGeomObject( theShape );
3298       addGeomGroupData( geom, aGroup );
3299     }
3300   }
3301   return aGroup._retn();
3302 }
3303
3304 //=============================================================================
3305 /*!
3306  * SMESH_Mesh_i::removeGroup
3307  *
3308  * Should be called by ~SMESH_Group_i()
3309  */
3310 //=============================================================================
3311
3312 void SMESH_Mesh_i::removeGroup( const int theId )
3313 {
3314   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::removeGroup()" );
3315   if ( _mapGroups.find( theId ) != _mapGroups.end() ) {
3316     SMESH::SMESH_GroupBase_var group = _mapGroups[theId];
3317     _mapGroups.erase( theId );
3318     removeGeomGroupData( group );
3319     if ( !_impl->RemoveGroup( theId ))
3320     {
3321       // it seems to be a call up from _impl caused by hyp modification (issue 0020918)
3322       RemoveGroup( group );
3323     }
3324     group->UnRegister();
3325   }
3326 }
3327
3328 //================================================================================
3329 /*!
3330  * \brief Return a log that can be used to move another mesh to the same state as this one
3331  */
3332 //================================================================================
3333
3334 SMESH::log_array * SMESH_Mesh_i::GetLog(CORBA::Boolean clearAfterGet)
3335 {
3336   SMESH::log_array_var aLog;
3337
3338   SMESH_TRY;
3339   if ( _preMeshInfo )
3340     _preMeshInfo->FullLoadFromFile();
3341
3342   list < SMESHDS_Command * >logDS = _impl->GetLog();
3343   aLog = new SMESH::log_array;
3344   int indexLog = 0;
3345   int lg = logDS.size();
3346   aLog->length(lg);
3347   list < SMESHDS_Command * >::iterator its = logDS.begin();
3348   while(its != logDS.end()){
3349     SMESHDS_Command *com = *its;
3350     int comType = com->GetType();
3351     smIdType lgcom = com->GetNumber();
3352     const list < smIdType >&intList = com->GetIndexes();
3353     int inum = intList.size();
3354     list < smIdType >::const_iterator ii = intList.begin();
3355     const list < double >&coordList = com->GetCoords();
3356     int rnum = coordList.size();
3357     list < double >::const_iterator ir = coordList.begin();
3358     aLog[indexLog].commandType = comType;
3359     aLog[indexLog].number = lgcom;
3360     aLog[indexLog].coords.length(rnum);
3361     aLog[indexLog].indexes.length(inum);
3362     for(int i = 0; i < rnum; i++){
3363       aLog[indexLog].coords[i] = *ir;
3364       ir++;
3365     }
3366     for(int i = 0; i < inum; i++){
3367       aLog[indexLog].indexes[i] = *ii;
3368       ii++;
3369     }
3370     indexLog++;
3371     its++;
3372   }
3373   if(clearAfterGet)
3374     _impl->ClearLog();
3375
3376   SMESH_CATCH( SMESH::throwCorbaException );
3377
3378   return aLog._retn();
3379 }
3380
3381 //================================================================================
3382 /*!
3383  * \brief Remove the log of commands
3384  */
3385 //================================================================================
3386
3387 void SMESH_Mesh_i::ClearLog()
3388 {
3389   SMESH_TRY;
3390   _impl->ClearLog();
3391   SMESH_CATCH( SMESH::throwCorbaException );
3392 }
3393
3394 //================================================================================
3395 /*!
3396  * \brief Return a mesh ID
3397  */
3398 //================================================================================
3399
3400 CORBA::Long SMESH_Mesh_i::GetId()
3401 {
3402   return _id;
3403 }
3404
3405 //=============================================================================
3406 namespace
3407 {
3408   //!< implementation of struct used to call methods of SMESH_Mesh_i from SMESH_Mesh
3409   // issue 0020918: groups removal is caused by hyp modification
3410   // issue 0021208: to forget not loaded mesh data at hyp modification
3411   struct TCallUp_i : public SMESH_Mesh::TCallUp
3412   {
3413     SMESH_Mesh_i* _mesh;
3414     TCallUp_i(SMESH_Mesh_i* mesh):_mesh(mesh) {}
3415     void RemoveGroup (const int theGroupID) override { _mesh->removeGroup( theGroupID ); }
3416     void HypothesisModified( int hypID,
3417                              bool updIcons) override { _mesh->onHypothesisModified( hypID,
3418                                                                                     updIcons ); }
3419     void Load ()                            override { _mesh->Load(); }
3420     bool IsLoaded()                         override { return _mesh->IsLoaded(); }
3421     TopoDS_Shape GetShapeByEntry(const std::string& entry) override
3422     {
3423       GEOM::GEOM_Object_var go = SMESH_Gen_i::GetGeomObjectByEntry( entry );
3424       return SMESH_Gen_i::GeomObjectToShape( go );
3425     }
3426   };
3427 }
3428
3429 //================================================================================
3430 /*!
3431  * \brief callback from _impl to
3432  *     1) forget not loaded mesh data (issue 0021208)
3433  *     2) mark hypothesis as valid
3434  */
3435 //================================================================================
3436
3437 void SMESH_Mesh_i::onHypothesisModified(int theHypID, bool theUpdateIcons)
3438 {
3439   if ( _preMeshInfo )
3440     _preMeshInfo->ForgetOrLoad();
3441
3442   if ( theUpdateIcons )
3443   {
3444     SMESH::SMESH_Mesh_var mesh = _this();
3445     _gen_i->UpdateIcons( mesh );
3446   }
3447
3448   if ( _nbInvalidHypos != 0 )
3449   {
3450     // mark a hypothesis as valid after edition
3451     int nbInvalid = 0;
3452     SALOMEDS::SComponent_wrap smeshComp = _gen_i->PublishComponent();
3453     SALOMEDS::SObject_wrap hypRoot;
3454     if ( !smeshComp->_is_nil() &&
3455          smeshComp->FindSubObject( _gen_i->GetHypothesisRootTag(), hypRoot.inout() ))
3456     {
3457       SALOMEDS::ChildIterator_wrap anIter = _gen_i->getStudyServant()->NewChildIterator( hypRoot );
3458       for ( ; anIter->More(); anIter->Next() )
3459       {
3460         SALOMEDS::SObject_wrap    hypSO = anIter->Value();
3461         CORBA::Object_var           obj = _gen_i->SObjectToObject( hypSO );
3462         SMESH::SMESH_Hypothesis_var hyp = SMESH::SMESH_Hypothesis::_narrow( obj );
3463         if ( !hyp->_is_nil() && hyp->GetId() == theHypID )
3464           _gen_i->HighLightInvalid( hyp, false );
3465         else
3466           nbInvalid += _gen_i->IsInvalid( hypSO );
3467       }
3468     }
3469     _nbInvalidHypos = nbInvalid;
3470   }
3471 }
3472
3473 //================================================================================
3474 /*!
3475  * \brief Set mesh implementation
3476  */
3477 //================================================================================
3478
3479 void SMESH_Mesh_i::SetImpl(::SMESH_Mesh * impl)
3480 {
3481   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::SetImpl");
3482   _impl = impl;
3483   if ( _impl )
3484     _impl->SetCallUp( new TCallUp_i(this));
3485 }
3486
3487 //=============================================================================
3488 /*!
3489  * Return a mesh implementation
3490  */
3491 //=============================================================================
3492
3493 ::SMESH_Mesh & SMESH_Mesh_i::GetImpl()
3494 {
3495   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::GetImpl()");
3496   return *_impl;
3497 }
3498
3499 //=============================================================================
3500 /*!
3501  * Return mesh editor
3502  */
3503 //=============================================================================
3504
3505 SMESH::SMESH_MeshEditor_ptr SMESH_Mesh_i::GetMeshEditor()
3506 {
3507   SMESH::SMESH_MeshEditor_var aMeshEdVar;
3508
3509   SMESH_TRY;
3510   if ( _preMeshInfo )
3511     _preMeshInfo->FullLoadFromFile();
3512
3513   // Create MeshEditor
3514   if ( !_editor )
3515     _editor = new SMESH_MeshEditor_i( this, false );
3516   aMeshEdVar = _editor->_this();
3517
3518   // Update Python script
3519   TPythonDump() << _editor << " = "
3520                 << SMESH::SMESH_Mesh_var(_this()) << ".GetMeshEditor()";
3521
3522   SMESH_CATCH( SMESH::throwCorbaException );
3523
3524   return aMeshEdVar._retn();
3525 }
3526
3527 //=============================================================================
3528 /*!
3529  * Return mesh edition previewer
3530  */
3531 //=============================================================================
3532
3533 SMESH::SMESH_MeshEditor_ptr SMESH_Mesh_i::GetMeshEditPreviewer()
3534 {
3535   SMESH::SMESH_MeshEditor_var aMeshEdVar;
3536
3537   SMESH_TRY;
3538   if ( _preMeshInfo )
3539     _preMeshInfo->FullLoadFromFile();
3540
3541   if ( !_previewEditor )
3542     _previewEditor = new SMESH_MeshEditor_i( this, true );
3543   aMeshEdVar = _previewEditor->_this();
3544
3545   SMESH_CATCH( SMESH::throwCorbaException );
3546
3547   return aMeshEdVar._retn();
3548 }
3549
3550 //================================================================================
3551 /*!
3552  * \brief Return true if the mesh has been edited since a last total re-compute
3553  *        and those modifications may prevent successful partial re-compute
3554  */
3555 //================================================================================
3556
3557 CORBA::Boolean SMESH_Mesh_i::HasModificationsToDiscard()
3558 {
3559   Unexpect aCatch(SALOME_SalomeException);
3560   return _impl->HasModificationsToDiscard();
3561 }
3562
3563 //================================================================================
3564 /*!
3565  * \brief Return a random unique color
3566  */
3567 //================================================================================
3568
3569 static SALOMEDS::Color getUniqueColor( const std::list<SALOMEDS::Color>& theReservedColors )
3570 {
3571   const int MAX_ATTEMPTS = 100;
3572   int cnt = 0;
3573   double tolerance = 0.5;
3574   SALOMEDS::Color col;
3575
3576   bool ok = false;
3577   while ( !ok ) {
3578     // generate random color
3579     double red    = (double)rand() / RAND_MAX;
3580     double green  = (double)rand() / RAND_MAX;
3581     double blue   = (double)rand() / RAND_MAX;
3582     // check existence in the list of the existing colors
3583     bool matched = false;
3584     std::list<SALOMEDS::Color>::const_iterator it;
3585     for ( it = theReservedColors.begin(); it != theReservedColors.end() && !matched; ++it ) {
3586       SALOMEDS::Color color = *it;
3587       double tol = fabs( color.R - red ) + fabs( color.G - green ) + fabs( color.B  - blue  );
3588       matched = tol < tolerance;
3589     }
3590     if ( (cnt+1) % 20 == 0 ) tolerance = tolerance/2;
3591     ok = ( ++cnt == MAX_ATTEMPTS ) || !matched;
3592     col.R = red;
3593     col.G = green;
3594     col.B = blue;
3595   }
3596   return col;
3597 }
3598
3599 //=============================================================================
3600 /*!
3601  * Set auto-color mode. If it is on, groups get unique random colors
3602  */
3603 //=============================================================================
3604
3605 void SMESH_Mesh_i::SetAutoColor(CORBA::Boolean theAutoColor)
3606 {
3607   Unexpect aCatch(SALOME_SalomeException);
3608   _impl->SetAutoColor(theAutoColor);
3609
3610   TPythonDump pyDump; // not to dump group->SetColor() from below code
3611   pyDump << SMESH::SMESH_Mesh_var(_this()) <<".SetAutoColor( "<<theAutoColor<<" )";
3612
3613   std::list<SALOMEDS::Color> aReservedColors;
3614   map<int, SMESH::SMESH_GroupBase_ptr>::iterator it = _mapGroups.begin();
3615   for ( ; it != _mapGroups.end(); it++ ) {
3616     if ( CORBA::is_nil( it->second )) continue;
3617     SALOMEDS::Color aColor = getUniqueColor( aReservedColors );
3618     it->second->SetColor( aColor );
3619     aReservedColors.push_back( aColor );
3620   }
3621 }
3622
3623 //=============================================================================
3624 /*!
3625  * Return true if auto-color mode is on
3626  */
3627 //=============================================================================
3628
3629 CORBA::Boolean SMESH_Mesh_i::GetAutoColor()
3630 {
3631   Unexpect aCatch(SALOME_SalomeException);
3632   return _impl->GetAutoColor();
3633 }
3634
3635 //=============================================================================
3636 /*!
3637  *  Check if there are groups with equal names
3638  */
3639 //=============================================================================
3640
3641 CORBA::Boolean SMESH_Mesh_i::HasDuplicatedGroupNamesMED()
3642 {
3643   return _impl->HasDuplicatedGroupNamesMED();
3644 }
3645
3646 //================================================================================
3647 /*!
3648  * \brief Care of a file before exporting mesh into it
3649  */
3650 //================================================================================
3651
3652 void SMESH_Mesh_i::PrepareForWriting (const char* file, bool overwrite)
3653 {
3654   SMESH_File aFile( file, false );
3655   SMESH_Comment msg;
3656   if ( aFile.exists() ) {
3657     // existing filesystem node
3658     if ( !aFile.isDirectory() ) {
3659       if ( aFile.openForWriting() ) {
3660         if ( overwrite && ! aFile.remove()) {
3661           msg << "Can't replace " << aFile.getName();
3662         }
3663       } else {
3664         msg << "Can't write into " << aFile.getName();
3665       }
3666     } else {
3667       msg << "Location " << aFile.getName() << " is not a file";
3668     }
3669   }
3670   else {
3671     // nonexisting file; check if it can be created
3672     if ( !aFile.openForWriting() ) {
3673       msg << "You cannot create the file "
3674           << aFile.getName()
3675           << ". Check the directory existence and access rights";
3676     }
3677     aFile.remove();
3678   }
3679
3680   if ( !msg.empty() )
3681   {
3682     msg << ".";
3683     THROW_SALOME_CORBA_EXCEPTION(msg.c_str(), SALOME::BAD_PARAM);
3684   }
3685 }
3686
3687 /*!
3688   Return a MeshName
3689  */
3690 std::string SMESH_Mesh_i::generateMeshName()
3691 {
3692   string aMeshName = "Mesh";
3693   SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->getStudyServant();
3694   if ( !aStudy->_is_nil() )
3695   {
3696     SALOMEDS::SObject_wrap aMeshSO = _gen_i->ObjectToSObject(  _this() );
3697     if ( !aMeshSO->_is_nil() )
3698     {
3699       CORBA::String_var name = aMeshSO->GetName();
3700       aMeshName = name;
3701     }
3702   }
3703   return aMeshName;
3704 }
3705
3706 //================================================================================
3707 /*!
3708  * \brief Prepare a file for export and pass names of mesh groups from study to mesh DS
3709  *  \param file - file name
3710  *  \param overwrite - to erase the file or not
3711  *  \retval string - mesh name
3712  */
3713 //================================================================================
3714
3715 string SMESH_Mesh_i::prepareMeshNameAndGroups(const char*    file,
3716                                               CORBA::Boolean overwrite)
3717 {
3718   // Perform Export
3719   PrepareForWriting(file, overwrite);
3720   string aMeshName(this->generateMeshName());
3721   SALOMEDS::Study_var aStudy = SMESH_Gen_i::GetSMESHGen()->getStudyServant();
3722   if ( !aStudy->_is_nil() ) {
3723     SALOMEDS::SObject_wrap aMeshSO = _gen_i->ObjectToSObject(  _this() );
3724     if ( !aMeshSO->_is_nil() ) {
3725       // asv : 27.10.04 : fix of 6903: check for StudyLocked before adding attributes
3726       if ( !aStudy->GetProperties()->IsLocked() )
3727       {
3728         SALOMEDS::GenericAttribute_wrap anAttr;
3729         SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
3730         anAttr=aStudyBuilder->FindOrCreateAttribute(aMeshSO, "AttributeExternalFileDef");
3731         SALOMEDS::AttributeExternalFileDef_wrap aFileName = anAttr;
3732         ASSERT(!aFileName->_is_nil());
3733         aFileName->SetValue(file);
3734         anAttr=aStudyBuilder->FindOrCreateAttribute(aMeshSO, "AttributeFileType");
3735         SALOMEDS::AttributeFileType_wrap aFileType = anAttr;
3736         ASSERT(!aFileType->_is_nil());
3737         aFileType->SetValue("FICHIERMED");
3738       }
3739     }
3740   }
3741   // Update Python script
3742   // set name of mesh before export
3743   TPythonDump() << _gen_i << ".SetName("
3744                 << SMESH::SMESH_Mesh_var(_this()) << ", '" << aMeshName.c_str() << "')";
3745
3746   // check names of groups
3747   checkGroupNames();
3748
3749   return aMeshName;
3750 }
3751
3752 //================================================================================
3753 /*!
3754  * \brief Export to MED file
3755  */
3756 //================================================================================
3757
3758 void SMESH_Mesh_i::ExportMED(const char*    file,
3759                              CORBA::Boolean auto_groups,
3760                              CORBA::Long    version,
3761                              CORBA::Boolean overwrite,
3762                              CORBA::Boolean autoDimension)
3763 {
3764   //MESSAGE("MED minor version: "<< minor);
3765   SMESH_TRY;
3766   if ( _preMeshInfo )
3767     _preMeshInfo->FullLoadFromFile();
3768
3769   string aMeshName = prepareMeshNameAndGroups(file, overwrite);
3770   _impl->ExportMED( file, aMeshName.c_str(), auto_groups, version, 0, autoDimension );
3771
3772   TPythonDump() << SMESH::SMESH_Mesh_var(_this()) << ".ExportMED( r'"
3773                 << file << "', "
3774                 << "auto_groups=" <<auto_groups << ", "
3775                 << "version=" << version <<  ", "
3776                 << "overwrite=" << overwrite << ", "
3777                 << "meshPart=None, "
3778                 << "autoDimension=" << autoDimension << " )";
3779
3780   SMESH_CATCH( SMESH::throwCorbaException );
3781 }
3782
3783 CORBA::LongLong SMESH_Mesh_i::ExportMEDCoupling(CORBA::Boolean auto_groups, CORBA::Boolean autoDimension)
3784 {
3785   MEDCoupling::MCAuto<MEDCoupling::DataArrayByte> data;
3786   SMESH_TRY;
3787   // TODO : Fix me ! 2 next lines are required
3788   if( !this->_gen_i->isSSLMode() )
3789     SMESH::throwCorbaException("SMESH_Mesh_i::ExportMEDCoupling : only for embedded mode !");
3790   if ( _preMeshInfo )
3791     _preMeshInfo->FullLoadFromFile();
3792
3793   string aMeshName = this->generateMeshName();
3794   data = _impl->ExportMEDCoupling( aMeshName.c_str(), auto_groups, 0, autoDimension );
3795   SMESH_CATCH( SMESH::throwCorbaException );
3796   MEDCoupling::DataArrayByte *ret(data.retn());
3797   return reinterpret_cast<CORBA::LongLong>(ret);
3798 }
3799
3800 //================================================================================
3801 /*!
3802  * \brief Export a mesh to a SAUV file
3803  */
3804 //================================================================================
3805
3806 void SMESH_Mesh_i::ExportSAUV( const char* file, CORBA::Boolean auto_groups )
3807 {
3808   SMESH_TRY;
3809   if ( _preMeshInfo )
3810     _preMeshInfo->FullLoadFromFile();
3811
3812   string aMeshName = prepareMeshNameAndGroups(file, true);
3813   TPythonDump() << SMESH::SMESH_Mesh_var( _this())
3814                 << ".ExportSAUV( r'" << file << "', " << auto_groups << " )";
3815   _impl->ExportSAUV(file, aMeshName.c_str(), auto_groups);
3816
3817   SMESH_CATCH( SMESH::throwCorbaException );
3818 }
3819
3820
3821 //================================================================================
3822 /*!
3823  * \brief Export a mesh to a DAT file
3824  */
3825 //================================================================================
3826
3827 void SMESH_Mesh_i::ExportDAT (const char *file)
3828 {
3829   SMESH_TRY;
3830   if ( _preMeshInfo )
3831     _preMeshInfo->FullLoadFromFile();
3832
3833   // check names of groups
3834   checkGroupNames();
3835   // Update Python script
3836   TPythonDump() << SMESH::SMESH_Mesh_var(_this()) << ".ExportDAT( r'" << file << "' )";
3837
3838   // Perform Export
3839   PrepareForWriting(file);
3840   _impl->ExportDAT(file);
3841
3842   SMESH_CATCH( SMESH::throwCorbaException );
3843 }
3844
3845 //================================================================================
3846 /*!
3847  * \brief Export a mesh to an UNV file
3848  */
3849 //================================================================================
3850
3851 void SMESH_Mesh_i::ExportUNV (const char *file)
3852 {
3853   SMESH_TRY;
3854   if ( _preMeshInfo )
3855     _preMeshInfo->FullLoadFromFile();
3856
3857   // check names of groups
3858   checkGroupNames();
3859   // Update Python script
3860   TPythonDump() << SMESH::SMESH_Mesh_var(_this()) << ".ExportUNV( r'" << file << "' )";
3861
3862   // Perform Export
3863   PrepareForWriting(file);
3864   _impl->ExportUNV(file);
3865
3866   SMESH_CATCH( SMESH::throwCorbaException );
3867 }
3868
3869 //================================================================================
3870 /*!
3871  * \brief Export a mesh to an STL file
3872  */
3873 //================================================================================
3874
3875 void SMESH_Mesh_i::ExportSTL (const char *file, const bool isascii)
3876 {
3877   SMESH_TRY;
3878   if ( _preMeshInfo )
3879     _preMeshInfo->FullLoadFromFile();
3880
3881   // check names of groups
3882   checkGroupNames();
3883   // Update Python script
3884   TPythonDump() << SMESH::SMESH_Mesh_var(_this())
3885                 << ".ExportSTL( r'" << file << "', " << isascii << " )";
3886
3887   CORBA::String_var name;
3888   SALOMEDS::SObject_wrap so = _gen_i->ObjectToSObject( _this() );
3889   if ( !so->_is_nil() )
3890     name = so->GetName();
3891
3892   // Perform Export
3893   PrepareForWriting( file );
3894   _impl->ExportSTL( file, isascii, name.in() );
3895
3896   SMESH_CATCH( SMESH::throwCorbaException );
3897 }
3898
3899 class MEDFileSpeCls
3900 {
3901 public:
3902   MEDFileSpeCls(const char *file, CORBA::Boolean overwrite, CORBA::Long version):_file(file),_overwrite(overwrite),_version(version) { }
3903   std::string prepareMeshNameAndGroups(SMESH_Mesh_i& self) { return self.prepareMeshNameAndGroups(_file.c_str(),_overwrite); }
3904   void exportTo(SMESH_Mesh *mesh, const std::string& aMeshName, CORBA::Boolean auto_groups,
3905                 SMESH_MeshPartDS* partDS,
3906                 CORBA::Boolean autoDimension, bool have0dField,
3907                 CORBA::Double ZTolerance)
3908   {
3909     mesh->ExportMED( _file.c_str(), aMeshName.c_str(), auto_groups, _version,
3910                     partDS, autoDimension,have0dField,ZTolerance);
3911
3912   }
3913
3914   void exportField(SMESH_Mesh_i& self, const std::string& aMeshName, bool have0dField, SMESHDS_Mesh *meshDS, const GEOM::ListOfFields& fields, const char*geomAssocFields)
3915   {
3916     DriverMED_W_Field fieldWriter;
3917     fieldWriter.SetFile( _file.c_str() );
3918     fieldWriter.SetMeshName( aMeshName );
3919     fieldWriter.AddODOnVertices( have0dField );
3920     self.exportMEDFields( fieldWriter, meshDS, fields, geomAssocFields );
3921   }
3922
3923   void prepareForWriting(SMESH_Mesh_i& self) { self.PrepareForWriting(_file.c_str(), _overwrite); }
3924 private:
3925   std::string _file;
3926   CORBA::Boolean _overwrite;
3927   CORBA::Long  _version;
3928 };
3929
3930
3931 template<class SPECLS>
3932 void SMESH_Mesh_i::ExportPartToMEDCommon(SPECLS& speCls,
3933       SMESH::SMESH_IDSource_ptr meshPart,
3934       CORBA::Boolean            auto_groups,
3935       CORBA::Boolean            autoDimension,
3936       const GEOM::ListOfFields& fields,
3937       const char*               geomAssocFields,
3938       CORBA::Double             ZTolerance)
3939 {
3940   SMESH_TRY;
3941   if ( _preMeshInfo )
3942     _preMeshInfo->FullLoadFromFile();
3943
3944   // check fields
3945   bool have0dField = false;
3946   if ( fields.length() > 0 )
3947   {
3948     GEOM::GEOM_Object_var shapeToMesh = GetShapeToMesh();
3949     if ( shapeToMesh->_is_nil() )
3950       THROW_SALOME_CORBA_EXCEPTION( "No shape to mesh", SALOME::INTERNAL_ERROR );
3951
3952     for ( size_t i = 0; i < fields.length(); ++i )
3953     {
3954       if ( fields[i]->GetDataType() == GEOM::FDT_String )
3955         THROW_SALOME_CORBA_EXCEPTION
3956           ( "Export of string fields is not supported", SALOME::BAD_PARAM);
3957       GEOM::GEOM_Object_var fieldShape = fields[i]->GetShape();
3958       if ( fieldShape->_is_nil() )
3959         THROW_SALOME_CORBA_EXCEPTION( "Null shape under a field", SALOME::INTERNAL_ERROR );
3960       if ( !fieldShape->IsSame( shapeToMesh ) )
3961         THROW_SALOME_CORBA_EXCEPTION
3962           ( "Field defined not on shape", SALOME::BAD_PARAM);
3963       if ( fields[i]->GetDimension() == 0 )
3964         have0dField = true;
3965     }
3966     if ( geomAssocFields )
3967       for ( int i = 0; geomAssocFields[i]; ++i )
3968         switch ( geomAssocFields[i] ) {
3969         case 'v':case 'e':case 'f':case 's': break;
3970         case 'V':case 'E':case 'F':case 'S': break;
3971         default: THROW_SALOME_CORBA_EXCEPTION
3972             ( "geomAssocFields can include only [vefs] characters", SALOME::BAD_PARAM);
3973         }
3974   }
3975
3976   SMESHDS_Mesh* meshDS = _impl->GetMeshDS();
3977
3978   // write mesh
3979
3980   string aMeshName = "Mesh";
3981   SMESHUtils::Deleter< SMESH_MeshPartDS > tmpDSDeleter(0);
3982   if ( CORBA::is_nil( meshPart ) ||
3983        SMESH::DownCast< SMESH_Mesh_i* >( meshPart ))
3984   {
3985     aMeshName = speCls.prepareMeshNameAndGroups(*this);
3986     speCls.exportTo(_impl, aMeshName, auto_groups, nullptr, autoDimension, have0dField, ZTolerance);
3987     meshDS = _impl->GetMeshDS();
3988   }
3989   else
3990   {
3991     if ( _preMeshInfo )
3992       _preMeshInfo->FullLoadFromFile();
3993
3994     speCls.prepareForWriting(*this);
3995
3996     SALOMEDS::SObject_wrap SO = _gen_i->ObjectToSObject( meshPart );
3997     if ( !SO->_is_nil() ) {
3998       CORBA::String_var name = SO->GetName();
3999       aMeshName = name;
4000     }
4001
4002     SMESH_MeshPartDS* partDS = new SMESH_MeshPartDS( meshPart );
4003     speCls.exportTo(_impl, aMeshName, auto_groups, partDS, autoDimension, have0dField, ZTolerance);
4004     meshDS = tmpDSDeleter._obj = partDS;
4005   }
4006
4007   // write fields
4008
4009   if ( _impl->HasShapeToMesh() )
4010   {
4011     speCls.exportField(*this,aMeshName,have0dField,meshDS,fields,geomAssocFields);
4012   }
4013   SMESH_CATCH( SMESH::throwCorbaException );
4014 }
4015
4016 //================================================================================
4017 /*!
4018  * \brief Export a part of mesh to a med file
4019  */
4020 //================================================================================
4021
4022 void SMESH_Mesh_i::ExportPartToMED(SMESH::SMESH_IDSource_ptr meshPart,
4023                                    const char*               file,
4024                                    CORBA::Boolean            auto_groups,
4025                                    CORBA::Long               version,
4026                                    CORBA::Boolean            overwrite,
4027                                    CORBA::Boolean            autoDimension,
4028                                    const GEOM::ListOfFields& fields,
4029                                    const char*               geomAssocFields,
4030                                    CORBA::Double             ZTolerance)
4031 {
4032   MESSAGE("MED version: "<< version);
4033   MEDFileSpeCls spe(file,overwrite,version);
4034   this->ExportPartToMEDCommon<MEDFileSpeCls>(spe,meshPart,auto_groups,autoDimension,fields,geomAssocFields,ZTolerance);
4035   // dump
4036   SMESH_TRY;
4037   GEOM::ListOfGBO_var goList = new GEOM::ListOfGBO;
4038   goList->length( fields.length() );
4039   for ( size_t i = 0; i < fields.length(); ++i )
4040   {
4041     GEOM::GEOM_BaseObject_var gbo = GEOM::GEOM_BaseObject::_narrow( fields[i] );
4042     goList[i] = gbo;
4043   }
4044   TPythonDump() << _this() << ".ExportPartToMED( "
4045                 << meshPart << ", r'"
4046                 << file << "', "
4047                 << auto_groups << ", "
4048                 << version << ", "
4049                 << overwrite << ", "
4050                 << autoDimension << ", "
4051                 << goList << ", '"
4052                 << ( geomAssocFields ? geomAssocFields : "" ) << "',"
4053                 << TVar( ZTolerance )
4054                 << " )";
4055   SMESH_CATCH( SMESH::throwCorbaException );
4056 }
4057
4058 class MEDFileMemSpeCls
4059 {
4060 public:
4061   std::string prepareMeshNameAndGroups(SMESH_Mesh_i& self) { return self.generateMeshName(); }
4062   void exportTo(SMESH_Mesh *mesh, const std::string& aMeshName, CORBA::Boolean auto_groups,
4063                 SMESH_MeshPartDS* partDS,
4064                 CORBA::Boolean autoDimension, bool have0dField,
4065                 CORBA::Double ZTolerance)
4066   {
4067     _res = mesh->ExportMEDCoupling(aMeshName.c_str(),auto_groups,partDS,autoDimension,have0dField,ZTolerance);
4068   }
4069   void prepareForWriting(SMESH_Mesh_i& self) { /* nothing here */ }
4070   void exportField(SMESH_Mesh_i& self, const std::string& aMeshName, bool have0dField, SMESHDS_Mesh *meshDS, const GEOM::ListOfFields& fields, const char*geomAssocFields)
4071   {
4072     DriverMED_W_Field_Mem fieldWriter(_res);
4073     fieldWriter.SetMeshName( aMeshName );
4074     fieldWriter.AddODOnVertices( have0dField );
4075     self.exportMEDFields( fieldWriter, meshDS, fields, geomAssocFields );
4076     _res = fieldWriter.getData();
4077   }
4078 public:
4079   MEDCoupling::MCAuto<MEDCoupling::DataArrayByte> getData() { return _res; }
4080 private:
4081   MEDCoupling::MCAuto<MEDCoupling::DataArrayByte> _res;
4082 };
4083
4084 CORBA::LongLong SMESH_Mesh_i::ExportPartToMEDCoupling(SMESH::SMESH_IDSource_ptr meshPart,
4085                                   CORBA::Boolean            auto_groups,
4086                                   CORBA::Boolean            autoDimension,
4087                                   const GEOM::ListOfFields& fields,
4088                                   const char*               geomAssocFields,
4089                                   CORBA::Double             ZTolerance)
4090 {
4091   MEDCoupling::MCAuto<MEDCoupling::DataArrayByte> data;
4092   SMESH_TRY;
4093   if( !this->_gen_i->isSSLMode() )
4094     SMESH::throwCorbaException("SMESH_Mesh_i::ExportPartToMEDCoupling : only for embedded mode !");
4095   MEDFileMemSpeCls spe;
4096   this->ExportPartToMEDCommon<MEDFileMemSpeCls>(spe,meshPart,auto_groups,autoDimension,fields,geomAssocFields,ZTolerance);
4097   data = spe.getData();
4098   SMESH_CATCH( SMESH::throwCorbaException );
4099   MEDCoupling::DataArrayByte *ret(data.retn());
4100   return reinterpret_cast<CORBA::LongLong>(ret);
4101 }
4102
4103 //================================================================================
4104 /*!
4105  * Write GEOM fields to MED file
4106  */
4107 //================================================================================
4108
4109 void SMESH_Mesh_i::exportMEDFields( DriverMED_W_Field&        fieldWriter,
4110                                     SMESHDS_Mesh*             meshDS,
4111                                     const GEOM::ListOfFields& fields,
4112                                     const char*               geomAssocFields)
4113 {
4114 #define METH "SMESH_Mesh_i::exportMEDFields() "
4115
4116   if (( fields.length() < 1 ) &&
4117       ( !geomAssocFields || !geomAssocFields[0] ))
4118     return;
4119
4120   std::vector< std::vector< double > > dblVals;
4121   std::vector< std::vector< int > >    intVals;
4122   std::vector< int >                   subIdsByDim[ 4 ];
4123   const double noneDblValue = 0.;
4124   const double noneIntValue = 0;
4125
4126   for ( size_t iF = 0; iF < fields.length(); ++iF )
4127   {
4128     // set field data
4129
4130     int dim = fields[ iF ]->GetDimension();
4131     SMDSAbs_ElementType elemType;
4132     TopAbs_ShapeEnum    shapeType;
4133     switch ( dim ) {
4134     case 0: elemType = SMDSAbs_0DElement; shapeType = TopAbs_VERTEX; break;
4135     case 1: elemType = SMDSAbs_Edge;      shapeType = TopAbs_EDGE;   break;
4136     case 2: elemType = SMDSAbs_Face;      shapeType = TopAbs_FACE;   break;
4137     case 3: elemType = SMDSAbs_Volume;    shapeType = TopAbs_SOLID;  break;
4138     default:
4139       continue; // skip fields on whole shape
4140     }
4141     GEOM::field_data_type dataType = fields[ iF ]->GetDataType();
4142     if ( dataType == GEOM::FDT_String )
4143       continue;
4144     GEOM::ListOfLong_var stepIDs = fields[ iF ]->GetSteps();
4145     if ( stepIDs->length() < 1 )
4146       continue;
4147     GEOM::string_array_var comps = fields[ iF ]->GetComponents();
4148     if ( comps->length() < 1 )
4149       continue;
4150     CORBA::String_var       name = fields[ iF ]->GetName();
4151
4152     if ( !fieldWriter.Set( meshDS,
4153                            name.in(),
4154                            elemType,
4155                            comps->length(),
4156                            /*isIntData=*/false ))//( dataType == GEOM::FDT_Int )))
4157       continue;
4158
4159     for ( size_t iC = 0; iC < comps->length(); ++iC )
4160       fieldWriter.SetCompName( iC, comps[ iC ].in() );
4161
4162     dblVals.resize( comps->length() );
4163     intVals.resize( comps->length() );
4164
4165     // find sub-shape IDs
4166
4167     std::vector< int >& subIds = subIdsByDim[ dim ];
4168     if ( subIds.empty() )
4169       for ( int id = 1; id <= meshDS->MaxShapeIndex(); ++id )
4170         if ( meshDS->IndexToShape( id ).ShapeType() == shapeType )
4171           subIds.push_back( id );
4172
4173     // write steps
4174
4175     SMDS_ElemIteratorPtr elemIt = fieldWriter.GetOrderedElems();
4176     if ( !elemIt )
4177       continue;
4178
4179     for ( size_t iS = 0; iS < stepIDs->length(); ++iS )
4180     {
4181       GEOM::GEOM_FieldStep_var step = fields[ iF ]->GetStep( stepIDs[ iS ]);
4182       if ( step->_is_nil() )
4183         continue;
4184
4185       CORBA::Long stamp = step->GetStamp();
4186       CORBA::Long id    = step->GetID();
4187       fieldWriter.SetDtIt( int( stamp ), int( id ));
4188
4189       // fill dblVals or intVals
4190       for ( size_t iC = 0; iC < comps->length(); ++iC )
4191         if ( dataType == GEOM::FDT_Double )
4192         {
4193           dblVals[ iC ].clear();
4194           dblVals[ iC ].resize( meshDS->MaxShapeIndex()+1, 0 );
4195         }
4196         else
4197         {
4198           intVals[ iC ].clear();
4199           intVals[ iC ].resize( meshDS->MaxShapeIndex()+1, 0 );
4200         }
4201       switch ( dataType )
4202       {
4203       case GEOM::FDT_Double:
4204       {
4205         GEOM::GEOM_DoubleFieldStep_var dblStep = GEOM::GEOM_DoubleFieldStep::_narrow( step );
4206         if ( dblStep->_is_nil() ) continue;
4207         GEOM::ListOfDouble_var vv = dblStep->GetValues();
4208         if ( vv->length() != subIds.size() * comps->length() )
4209           THROW_SALOME_CORBA_EXCEPTION( METH "BUG: wrong nb subIds", SALOME::INTERNAL_ERROR );
4210         for ( size_t iS = 0, iV = 0; iS < subIds.size(); ++iS )
4211           for ( size_t iC = 0; iC < comps->length(); ++iC )
4212             dblVals[ iC ][ subIds[ iS ]] = vv[ iV++ ];
4213         break;
4214       }
4215       case GEOM::FDT_Int:
4216       {
4217         GEOM::GEOM_IntFieldStep_var intStep = GEOM::GEOM_IntFieldStep::_narrow( step );
4218         if ( intStep->_is_nil() ) continue;
4219         GEOM::ListOfLong_var vv = intStep->GetValues();
4220         if ( vv->length() != subIds.size() * comps->length() )
4221           THROW_SALOME_CORBA_EXCEPTION( METH "BUG: wrong nb subIds", SALOME::INTERNAL_ERROR );
4222         for ( size_t iS = 0, iV = 0; iS < subIds.size(); ++iS )
4223           for ( size_t iC = 0; iC < comps->length(); ++iC )
4224             intVals[ iC ][ subIds[ iS ]] = (int) vv[ iV++ ];
4225         break;
4226       }
4227       case GEOM::FDT_Bool:
4228       {
4229         GEOM::GEOM_BoolFieldStep_var boolStep = GEOM::GEOM_BoolFieldStep::_narrow( step );
4230         if ( boolStep->_is_nil() ) continue;
4231         GEOM::short_array_var vv = boolStep->GetValues();
4232         if ( vv->length() != subIds.size() * comps->length() )
4233           THROW_SALOME_CORBA_EXCEPTION( METH "BUG: wrong nb subIds", SALOME::INTERNAL_ERROR );
4234         for ( size_t iS = 0, iV = 0; iS < subIds.size(); ++iS )
4235           for ( size_t iC = 0; iC < comps->length(); ++iC )
4236             intVals[ iC ][ subIds[ iS ]] = (int) vv[ iV++ ];
4237         break;
4238       }
4239       default: continue;
4240       }
4241
4242       // pass values to fieldWriter
4243       elemIt = fieldWriter.GetOrderedElems();
4244       if ( dataType == GEOM::FDT_Double )
4245         while ( elemIt->more() )
4246         {
4247           const SMDS_MeshElement* e = elemIt->next();
4248           const int shapeID = e->getshapeId();
4249           if ( shapeID < 1 || shapeID >= (int) dblVals[0].size() )
4250             for ( size_t iC = 0; iC < comps->length(); ++iC )
4251               fieldWriter.AddValue( noneDblValue );
4252           else
4253             for ( size_t iC = 0; iC < comps->length(); ++iC )
4254               fieldWriter.AddValue( dblVals[ iC ][ shapeID ]);
4255         }
4256       else
4257         while ( elemIt->more() )
4258         {
4259           const SMDS_MeshElement* e = elemIt->next();
4260           const int shapeID = e->getshapeId();
4261           if ( shapeID < 1 || shapeID >= (int) intVals[0].size() )
4262             for ( size_t iC = 0; iC < comps->length(); ++iC )
4263               fieldWriter.AddValue( (double) noneIntValue );
4264           else
4265             for ( size_t iC = 0; iC < comps->length(); ++iC )
4266               fieldWriter.AddValue( (double) intVals[ iC ][ shapeID ]);
4267         }
4268
4269       // write a step
4270       fieldWriter.Perform();
4271       SMESH_ComputeErrorPtr res = fieldWriter.GetError();
4272       if ( res && res->IsKO() )
4273       {
4274         if ( res->myComment.empty() )
4275         { THROW_SALOME_CORBA_EXCEPTION( METH "Fatal error", SALOME::INTERNAL_ERROR ); }
4276         else
4277         { THROW_SALOME_CORBA_EXCEPTION( res->myComment.c_str(), SALOME::INTERNAL_ERROR ); }
4278       }
4279
4280     } // loop on steps
4281   } // loop on fields
4282
4283   if ( !geomAssocFields || !geomAssocFields[0] )
4284     return;
4285
4286   // write geomAssocFields
4287
4288   std::vector< int > shapeDim( TopAbs_SHAPE + 1 );
4289   shapeDim[ TopAbs_COMPOUND  ] = 3;
4290   shapeDim[ TopAbs_COMPSOLID ] = 3;
4291   shapeDim[ TopAbs_SOLID     ] = 3;
4292   shapeDim[ TopAbs_SHELL     ] = 2;
4293   shapeDim[ TopAbs_FACE      ] = 2;
4294   shapeDim[ TopAbs_WIRE      ] = 1;
4295   shapeDim[ TopAbs_EDGE      ] = 1;
4296   shapeDim[ TopAbs_VERTEX    ] = 0;
4297   shapeDim[ TopAbs_SHAPE     ] = 3;
4298
4299   for ( int iF = 0; geomAssocFields[ iF ]; ++iF )
4300   {
4301     std::vector< std::string > compNames;
4302     switch ( geomAssocFields[ iF ]) {
4303     case 'v': case 'V':
4304       fieldWriter.Set( meshDS, "_vertices_", SMDSAbs_Node, /*nbComps=*/2, /*isInt=*/false );
4305       compNames.push_back( "dim" );
4306       break;
4307     case 'e': case 'E':
4308       fieldWriter.Set( meshDS, "_edges_", SMDSAbs_Edge, /*nbComps=*/1, /*isInt=*/false );
4309       break;
4310     case 'f': case 'F':
4311       fieldWriter.Set( meshDS, "_faces_", SMDSAbs_Face, /*nbComps=*/1, /*isInt=*/false );
4312       break;
4313     case 's': case 'S':
4314       fieldWriter.Set( meshDS, "_solids_", SMDSAbs_Volume, /*nbComps=*/1, /*isInt=*/false );
4315       break;
4316     default: continue;
4317     }
4318     compNames.push_back( "id" );
4319     for ( size_t iC = 0; iC < compNames.size(); ++iC )
4320       fieldWriter.SetCompName( iC, compNames[ iC ].c_str() );
4321
4322     fieldWriter.SetDtIt( -1, -1 );
4323
4324     SMDS_ElemIteratorPtr elemIt = fieldWriter.GetOrderedElems();
4325     if ( !elemIt )
4326       continue;
4327
4328     if ( compNames.size() == 2 ) // _vertices_
4329       while ( elemIt->more() )
4330       {
4331         const SMDS_MeshElement* e = elemIt->next();
4332         const int shapeID = e->getshapeId();
4333         if ( shapeID < 1 )
4334         {
4335           fieldWriter.AddValue( (double) -1 );
4336           fieldWriter.AddValue( (double) -1 );
4337         }
4338         else
4339         {
4340           const TopoDS_Shape& S = meshDS->IndexToShape( shapeID );
4341           fieldWriter.AddValue( (double) ( S.IsNull() ? -1 : shapeDim[ S.ShapeType() ]));
4342           fieldWriter.AddValue( (double) shapeID );
4343         }
4344       }
4345     else
4346       while ( elemIt->more() )
4347       {
4348         const SMDS_MeshElement* e = elemIt->next();
4349         const int shapeID = e->getshapeId();
4350         if ( shapeID < 1 )
4351           fieldWriter.AddValue( (double) -1 );
4352         else
4353           fieldWriter.AddValue( (double) shapeID );
4354       }
4355
4356     // write a step
4357     fieldWriter.Perform();
4358     SMESH_ComputeErrorPtr res = fieldWriter.GetError();
4359     if ( res && res->IsKO() )
4360     {
4361       if ( res->myComment.empty() )
4362       { THROW_SALOME_CORBA_EXCEPTION( METH "Fatal error", SALOME::INTERNAL_ERROR ); }
4363       else
4364       { THROW_SALOME_CORBA_EXCEPTION( res->myComment.c_str(), SALOME::INTERNAL_ERROR ); }
4365     }
4366
4367   } // loop on geomAssocFields
4368
4369 #undef METH
4370 }
4371
4372 //================================================================================
4373 /*!
4374  * \brief Export a part of mesh to a DAT file
4375  */
4376 //================================================================================
4377
4378 void SMESH_Mesh_i::ExportPartToDAT(::SMESH::SMESH_IDSource_ptr meshPart,
4379                                    const char*                 file)
4380 {
4381   SMESH_TRY;
4382   if ( _preMeshInfo )
4383     _preMeshInfo->FullLoadFromFile();
4384
4385   PrepareForWriting(file);
4386
4387   SMESH_MeshPartDS partDS( meshPart );
4388   _impl->ExportDAT(file,&partDS);
4389
4390   TPythonDump() << SMESH::SMESH_Mesh_var(_this())
4391                 << ".ExportPartToDAT( " << meshPart << ", r'" << file << "' )";
4392
4393   SMESH_CATCH( SMESH::throwCorbaException );
4394 }
4395 //================================================================================
4396 /*!
4397  * \brief Export a part of mesh to an UNV file
4398  */
4399 //================================================================================
4400
4401 void SMESH_Mesh_i::ExportPartToUNV(::SMESH::SMESH_IDSource_ptr meshPart,
4402                                    const char*                 file)
4403 {
4404   SMESH_TRY;
4405   if ( _preMeshInfo )
4406     _preMeshInfo->FullLoadFromFile();
4407
4408   PrepareForWriting(file);
4409
4410   SMESH_MeshPartDS partDS( meshPart );
4411   _impl->ExportUNV(file, &partDS);
4412
4413   TPythonDump() << SMESH::SMESH_Mesh_var(_this())
4414                 << ".ExportPartToUNV( " << meshPart<< ", r'" << file << "' )";
4415
4416   SMESH_CATCH( SMESH::throwCorbaException );
4417 }
4418 //================================================================================
4419 /*!
4420  * \brief Export a part of mesh to an STL file
4421  */
4422 //================================================================================
4423
4424 void SMESH_Mesh_i::ExportPartToSTL(::SMESH::SMESH_IDSource_ptr meshPart,
4425                                    const char*                 file,
4426                                    ::CORBA::Boolean            isascii)
4427 {
4428   SMESH_TRY;
4429   if ( _preMeshInfo )
4430     _preMeshInfo->FullLoadFromFile();
4431
4432   PrepareForWriting(file);
4433
4434   CORBA::String_var name;
4435   SALOMEDS::SObject_wrap so = _gen_i->ObjectToSObject( meshPart );
4436   if ( !so->_is_nil() )
4437     name = so->GetName();
4438
4439   SMESH_MeshPartDS partDS( meshPart );
4440   _impl->ExportSTL( file, isascii, name.in(), &partDS );
4441
4442   TPythonDump() << SMESH::SMESH_Mesh_var(_this()) << ".ExportPartToSTL( "
4443                 << meshPart<< ", r'" << file << "', " << isascii << ")";
4444
4445   SMESH_CATCH( SMESH::throwCorbaException );
4446 }
4447
4448 //================================================================================
4449 /*!
4450  * \brief Export a part of mesh to an STL file
4451  */
4452 //================================================================================
4453
4454 void SMESH_Mesh_i::ExportCGNS(::SMESH::SMESH_IDSource_ptr meshPart,
4455                               const char*                 file,
4456                               CORBA::Boolean              overwrite,
4457                               CORBA::Boolean              groupElemsByType)
4458 {
4459 #ifdef WITH_CGNS
4460   SMESH_TRY;
4461   if ( _preMeshInfo )
4462     _preMeshInfo->FullLoadFromFile();
4463
4464   PrepareForWriting(file,overwrite);
4465
4466   std::string meshName("");
4467   SALOMEDS::SObject_wrap so = _gen_i->ObjectToSObject( meshPart );
4468   if ( !so->_is_nil() )
4469   {
4470     CORBA::String_var name = so->GetName();
4471     meshName = name.in();
4472   }
4473   SMESH_TRY;
4474
4475   SMESH_MeshPartDS partDS( meshPart );
4476   _impl->ExportCGNS(file, &partDS, meshName.c_str(), groupElemsByType );
4477
4478   SMESH_CATCH( SMESH::throwCorbaException );
4479
4480   TPythonDump() << SMESH::SMESH_Mesh_var(_this()) << ".ExportCGNS( "
4481                 << meshPart<< ", r'" << file << "', " << overwrite << ")";
4482
4483   SMESH_CATCH( SMESH::throwCorbaException );
4484
4485 #else
4486   THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
4487 #endif
4488 }
4489
4490 //================================================================================
4491 /*!
4492  * \brief Export a part of mesh to a GMF file
4493  */
4494 //================================================================================
4495
4496 void SMESH_Mesh_i::ExportGMF(::SMESH::SMESH_IDSource_ptr meshPart,
4497                              const char*                 file,
4498                              bool                        withRequiredGroups)
4499 {
4500   SMESH_TRY;
4501   if ( _preMeshInfo )
4502     _preMeshInfo->FullLoadFromFile();
4503
4504   PrepareForWriting(file,/*overwrite=*/true);
4505
4506   SMESH_MeshPartDS partDS( meshPart );
4507   _impl->ExportGMF(file, &partDS, withRequiredGroups);
4508
4509   TPythonDump() << SMESH::SMESH_Mesh_var(_this()) << ".ExportGMF( "
4510                 << meshPart<< ", r'"
4511                 << file << "', "
4512                 << withRequiredGroups << ")";
4513
4514   SMESH_CATCH( SMESH::throwCorbaException );
4515 }
4516
4517 //=============================================================================
4518 /*!
4519  * Return computation progress [0.,1]
4520  */
4521 //=============================================================================
4522
4523 CORBA::Double SMESH_Mesh_i::GetComputeProgress()
4524 {
4525   SMESH_TRY;
4526
4527   return _impl->GetComputeProgress();
4528
4529   SMESH_CATCH( SMESH::doNothing );
4530   return 0.;
4531 }
4532
4533 //================================================================================
4534 /*!
4535  * \brief Return nb of nodes
4536  */
4537 //================================================================================
4538
4539 SMESH::smIdType SMESH_Mesh_i::NbNodes()
4540 {
4541   Unexpect aCatch(SALOME_SalomeException);
4542   if ( _preMeshInfo )
4543     return _preMeshInfo->NbNodes();
4544
4545   return _impl->NbNodes();
4546 }
4547
4548 //================================================================================
4549 /*!
4550  * \brief Return nb of elements
4551  */
4552 //================================================================================
4553
4554 SMESH::smIdType SMESH_Mesh_i::NbElements()
4555 {
4556   Unexpect aCatch(SALOME_SalomeException);
4557   if ( _preMeshInfo )
4558     return _preMeshInfo->NbElements();
4559
4560   return Nb0DElements() + NbEdges() + NbFaces() + NbVolumes() + NbBalls();
4561 }
4562
4563 //================================================================================
4564 /*!
4565  * \brief Return nb of 0D elements
4566  */
4567 //================================================================================
4568
4569 SMESH::smIdType SMESH_Mesh_i::Nb0DElements()
4570 {
4571   Unexpect aCatch(SALOME_SalomeException);
4572   if ( _preMeshInfo )
4573     return _preMeshInfo->Nb0DElements();
4574
4575   return _impl->Nb0DElements();
4576 }
4577
4578 //================================================================================
4579 /*!
4580  * \brief Return nb of BALL elements
4581  */
4582 //================================================================================
4583
4584 SMESH::smIdType SMESH_Mesh_i::NbBalls()
4585 {
4586   Unexpect aCatch(SALOME_SalomeException);
4587   if ( _preMeshInfo )
4588     return _preMeshInfo->NbBalls();
4589
4590   return _impl->NbBalls();
4591 }
4592
4593 //================================================================================
4594 /*!
4595  * \brief Return nb of 1D elements
4596  */
4597 //================================================================================
4598
4599 SMESH::smIdType SMESH_Mesh_i::NbEdges()
4600 {
4601   Unexpect aCatch(SALOME_SalomeException);
4602   if ( _preMeshInfo )
4603     return _preMeshInfo->NbEdges();
4604
4605   return _impl->NbEdges();
4606 }
4607
4608 //================================================================================
4609 /*!
4610  * \brief Return nb of edges
4611  */
4612 //================================================================================
4613
4614 SMESH::smIdType SMESH_Mesh_i::NbEdgesOfOrder(SMESH::ElementOrder order)
4615 {
4616   Unexpect aCatch(SALOME_SalomeException);
4617   if ( _preMeshInfo )
4618     return _preMeshInfo->NbEdges( (SMDSAbs_ElementOrder) order );
4619
4620   return _impl->NbEdges( (SMDSAbs_ElementOrder) order);
4621 }
4622
4623 //================================================================================
4624 /*!
4625  * \brief Return nb of faces
4626  */
4627 //================================================================================
4628
4629 SMESH::smIdType SMESH_Mesh_i::NbFaces()
4630 {
4631   Unexpect aCatch(SALOME_SalomeException);
4632   if ( _preMeshInfo )
4633     return _preMeshInfo->NbFaces();
4634
4635   return _impl->NbFaces();
4636 }
4637
4638 //================================================================================
4639 /*!
4640  * \brief Return nb of tringles
4641  */
4642 //================================================================================
4643
4644 SMESH::smIdType SMESH_Mesh_i::NbTriangles()
4645 {
4646   Unexpect aCatch(SALOME_SalomeException);
4647   if ( _preMeshInfo )
4648     return _preMeshInfo->NbTriangles();
4649
4650   return _impl->NbTriangles();
4651 }
4652
4653 //================================================================================
4654 /*!
4655  * \brief Return nb of bi-quadratic triangles
4656  */
4657 //================================================================================
4658
4659 SMESH::smIdType SMESH_Mesh_i::NbBiQuadTriangles()
4660 {
4661   Unexpect aCatch(SALOME_SalomeException);
4662   if ( _preMeshInfo )
4663     return _preMeshInfo->NbBiQuadTriangles();
4664
4665   return _impl->NbBiQuadTriangles();
4666 }
4667
4668 SMESH::smIdType SMESH_Mesh_i::NbQuadrangles()
4669 {
4670   Unexpect aCatch(SALOME_SalomeException);
4671   if ( _preMeshInfo )
4672     return _preMeshInfo->NbQuadrangles();
4673
4674   return _impl->NbQuadrangles();
4675 }
4676
4677 SMESH::smIdType SMESH_Mesh_i::NbBiQuadQuadrangles()
4678 {
4679   Unexpect aCatch(SALOME_SalomeException);
4680   if ( _preMeshInfo )
4681     return _preMeshInfo->NbBiQuadQuadrangles();
4682
4683   return _impl->NbBiQuadQuadrangles();
4684 }
4685
4686 SMESH::smIdType SMESH_Mesh_i::NbPolygons()
4687 {
4688   Unexpect aCatch(SALOME_SalomeException);
4689   if ( _preMeshInfo )
4690     return _preMeshInfo->NbPolygons();
4691
4692   return _impl->NbPolygons();
4693 }
4694
4695 SMESH::smIdType SMESH_Mesh_i::NbPolygonsOfOrder(SMESH::ElementOrder order)
4696 {
4697   Unexpect aCatch(SALOME_SalomeException);
4698   if ( _preMeshInfo )
4699     return _preMeshInfo->NbPolygons((SMDSAbs_ElementOrder) order);
4700
4701   return _impl->NbPolygons((SMDSAbs_ElementOrder)order);
4702 }
4703
4704 SMESH::smIdType SMESH_Mesh_i::NbFacesOfOrder(SMESH::ElementOrder order)
4705 {
4706   Unexpect aCatch(SALOME_SalomeException);
4707   if ( _preMeshInfo )
4708     return _preMeshInfo->NbFaces( (SMDSAbs_ElementOrder) order );
4709
4710   return _impl->NbFaces( (SMDSAbs_ElementOrder) order);
4711 }
4712
4713 SMESH::smIdType SMESH_Mesh_i::NbTrianglesOfOrder(SMESH::ElementOrder order)
4714 {
4715   Unexpect aCatch(SALOME_SalomeException);
4716   if ( _preMeshInfo )
4717     return _preMeshInfo->NbTriangles( (SMDSAbs_ElementOrder) order );
4718
4719   return _impl->NbTriangles( (SMDSAbs_ElementOrder) order);
4720 }
4721
4722 SMESH::smIdType SMESH_Mesh_i::NbQuadranglesOfOrder(SMESH::ElementOrder order)
4723 {
4724   Unexpect aCatch(SALOME_SalomeException);
4725   if ( _preMeshInfo )
4726     return _preMeshInfo->NbQuadrangles( (SMDSAbs_ElementOrder) order );
4727
4728   return _impl->NbQuadrangles( (SMDSAbs_ElementOrder) order);
4729 }
4730
4731 //=============================================================================
4732
4733 SMESH::smIdType SMESH_Mesh_i::NbVolumes()
4734 {
4735   Unexpect aCatch(SALOME_SalomeException);
4736   if ( _preMeshInfo )
4737     return _preMeshInfo->NbVolumes();
4738
4739   return _impl->NbVolumes();
4740 }
4741
4742 SMESH::smIdType SMESH_Mesh_i::NbTetras()
4743 {
4744   Unexpect aCatch(SALOME_SalomeException);
4745   if ( _preMeshInfo )
4746     return _preMeshInfo->NbTetras();
4747
4748   return _impl->NbTetras();
4749 }
4750
4751 SMESH::smIdType SMESH_Mesh_i::NbHexas()
4752 {
4753   Unexpect aCatch(SALOME_SalomeException);
4754   if ( _preMeshInfo )
4755     return _preMeshInfo->NbHexas();
4756
4757   return _impl->NbHexas();
4758 }
4759
4760 SMESH::smIdType SMESH_Mesh_i::NbTriQuadraticHexas()
4761 {
4762   Unexpect aCatch(SALOME_SalomeException);
4763   if ( _preMeshInfo )
4764     return _preMeshInfo->NbTriQuadHexas();
4765
4766   return _impl->NbTriQuadraticHexas();
4767 }
4768
4769 SMESH::smIdType SMESH_Mesh_i::NbPyramids()
4770 {
4771   Unexpect aCatch(SALOME_SalomeException);
4772   if ( _preMeshInfo )
4773     return _preMeshInfo->NbPyramids();
4774
4775   return _impl->NbPyramids();
4776 }
4777
4778 SMESH::smIdType SMESH_Mesh_i::NbPrisms()
4779 {
4780   Unexpect aCatch(SALOME_SalomeException);
4781   if ( _preMeshInfo )
4782     return _preMeshInfo->NbPrisms();
4783
4784   return _impl->NbPrisms();
4785 }
4786
4787 SMESH::smIdType SMESH_Mesh_i::NbHexagonalPrisms()
4788 {
4789   Unexpect aCatch(SALOME_SalomeException);
4790   if ( _preMeshInfo )
4791     return _preMeshInfo->NbHexPrisms();
4792
4793   return _impl->NbHexagonalPrisms();
4794 }
4795
4796 SMESH::smIdType SMESH_Mesh_i::NbPolyhedrons()
4797 {
4798   Unexpect aCatch(SALOME_SalomeException);
4799   if ( _preMeshInfo )
4800     return _preMeshInfo->NbPolyhedrons();
4801
4802   return _impl->NbPolyhedrons();
4803 }
4804
4805 SMESH::smIdType SMESH_Mesh_i::NbVolumesOfOrder(SMESH::ElementOrder order)
4806 {
4807   Unexpect aCatch(SALOME_SalomeException);
4808   if ( _preMeshInfo )
4809     return _preMeshInfo->NbVolumes( (SMDSAbs_ElementOrder) order );
4810
4811   return _impl->NbVolumes( (SMDSAbs_ElementOrder) order);
4812 }
4813
4814 SMESH::smIdType SMESH_Mesh_i::NbTetrasOfOrder(SMESH::ElementOrder order)
4815 {
4816   Unexpect aCatch(SALOME_SalomeException);
4817   if ( _preMeshInfo )
4818     return _preMeshInfo->NbTetras( (SMDSAbs_ElementOrder) order);
4819
4820   return _impl->NbTetras( (SMDSAbs_ElementOrder) order);
4821 }
4822
4823 SMESH::smIdType SMESH_Mesh_i::NbHexasOfOrder(SMESH::ElementOrder order)
4824 {
4825   Unexpect aCatch(SALOME_SalomeException);
4826   if ( _preMeshInfo )
4827     return _preMeshInfo->NbHexas( (SMDSAbs_ElementOrder) order);
4828
4829   return _impl->NbHexas( (SMDSAbs_ElementOrder) order);
4830 }
4831
4832 SMESH::smIdType SMESH_Mesh_i::NbPyramidsOfOrder(SMESH::ElementOrder order)
4833 {
4834   Unexpect aCatch(SALOME_SalomeException);
4835   if ( _preMeshInfo )
4836     return _preMeshInfo->NbPyramids( (SMDSAbs_ElementOrder) order);
4837
4838   return _impl->NbPyramids( (SMDSAbs_ElementOrder) order);
4839 }
4840
4841 SMESH::smIdType SMESH_Mesh_i::NbPrismsOfOrder(SMESH::ElementOrder order)
4842 {
4843   Unexpect aCatch(SALOME_SalomeException);
4844   if ( _preMeshInfo )
4845     return _preMeshInfo->NbPrisms( (SMDSAbs_ElementOrder) order);
4846
4847   return _impl->NbPrisms( (SMDSAbs_ElementOrder) order);
4848 }
4849
4850 //=============================================================================
4851 /*!
4852  * Return nb of published sub-meshes
4853  */
4854 //=============================================================================
4855
4856 SMESH::smIdType SMESH_Mesh_i::NbSubMesh()
4857 {
4858   Unexpect aCatch(SALOME_SalomeException);
4859   return _mapSubMesh_i.size();
4860 }
4861
4862 //=============================================================================
4863 /*!
4864  * Dumps mesh into a string
4865  */
4866 //=============================================================================
4867
4868 char* SMESH_Mesh_i::Dump()
4869 {
4870   ostringstream os;
4871   _impl->Dump( os );
4872   return CORBA::string_dup( os.str().c_str() );
4873 }
4874
4875 //=============================================================================
4876 /*!
4877  * Method of SMESH_IDSource interface
4878  */
4879 //=============================================================================
4880
4881 SMESH::smIdType_array* SMESH_Mesh_i::GetIDs()
4882 {
4883   return GetElementsId();
4884 }
4885
4886 //=============================================================================
4887 /*!
4888  * Return ids of all elements
4889  */
4890 //=============================================================================
4891
4892 SMESH::smIdType_array* SMESH_Mesh_i::GetElementsId()
4893 {
4894   Unexpect aCatch(SALOME_SalomeException);
4895   if ( _preMeshInfo )
4896     _preMeshInfo->FullLoadFromFile();
4897
4898   SMESH::smIdType_array_var aResult = new SMESH::smIdType_array();
4899   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
4900
4901   if ( aSMESHDS_Mesh == NULL )
4902     return aResult._retn();
4903
4904   smIdType nbElements = NbElements();
4905   aResult->length( nbElements );
4906   SMDS_ElemIteratorPtr anIt = aSMESHDS_Mesh->elementsIterator();
4907   for ( smIdType i = 0, n = nbElements; i < n && anIt->more(); i++ )
4908     aResult[i] = anIt->next()->GetID();
4909
4910   return aResult._retn();
4911 }
4912
4913
4914 //=============================================================================
4915 /*!
4916  * Return ids of all elements of given type
4917  */
4918 //=============================================================================
4919
4920 SMESH::smIdType_array* SMESH_Mesh_i::GetElementsByType( SMESH::ElementType theElemType )
4921 {
4922   Unexpect aCatch(SALOME_SalomeException);
4923   if ( _preMeshInfo )
4924     _preMeshInfo->FullLoadFromFile();
4925
4926   SMESH::smIdType_array_var aResult = new SMESH::smIdType_array();
4927   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
4928
4929   if ( aSMESHDS_Mesh == NULL )
4930     return aResult._retn();
4931
4932   smIdType nbElements = NbElements();
4933
4934   // No sense in returning ids of elements along with ids of nodes:
4935   // when theElemType == SMESH::ALL, return node ids only if
4936   // there are no elements
4937   if ( theElemType == SMESH::NODE || (theElemType == SMESH::ALL && nbElements == 0) )
4938     return GetNodesId();
4939
4940   aResult->length( nbElements );
4941
4942   smIdType i = 0;
4943
4944   SMDS_ElemIteratorPtr anIt = aSMESHDS_Mesh->elementsIterator( (SMDSAbs_ElementType)theElemType );
4945   while ( i < nbElements && anIt->more() )
4946     aResult[i++] = anIt->next()->GetID();
4947
4948   aResult->length( i );
4949
4950   return aResult._retn();
4951 }
4952
4953 //=============================================================================
4954 /*!
4955  * Return ids of all nodes
4956  */
4957 //=============================================================================
4958
4959 SMESH::smIdType_array* SMESH_Mesh_i::GetNodesId()
4960 {
4961   Unexpect aCatch(SALOME_SalomeException);
4962   if ( _preMeshInfo )
4963     _preMeshInfo->FullLoadFromFile();
4964
4965   SMESH::smIdType_array_var aResult = new SMESH::smIdType_array();
4966   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
4967
4968   if ( aMeshDS == NULL )
4969     return aResult._retn();
4970
4971   smIdType nbNodes = NbNodes();
4972   aResult->length( nbNodes );
4973   SMDS_NodeIteratorPtr anIt = aMeshDS->nodesIterator();
4974   for ( smIdType i = 0, n = nbNodes; i < n && anIt->more(); i++ )
4975     aResult[i] = anIt->next()->GetID();
4976
4977   return aResult._retn();
4978 }
4979
4980 //=============================================================================
4981 /*!
4982  * Return type of the given element
4983  */
4984 //=============================================================================
4985
4986 SMESH::ElementType SMESH_Mesh_i::GetElementType( const SMESH::smIdType id, const bool iselem )
4987 {
4988   SMESH::ElementType type = SMESH::ALL;
4989   SMESH_TRY;
4990
4991   if ( _preMeshInfo )
4992     _preMeshInfo->FullLoadFromFile();
4993
4994   type = ( SMESH::ElementType ) _impl->GetElementType( id, iselem );
4995
4996   SMESH_CATCH( SMESH::throwCorbaException );
4997
4998   return type;
4999 }
5000
5001 //=============================================================================
5002 /*!
5003  * Return geometric type of the given element
5004  */
5005 //=============================================================================
5006
5007 SMESH::EntityType SMESH_Mesh_i::GetElementGeomType( const SMESH::smIdType id )
5008 {
5009   if ( _preMeshInfo )
5010     _preMeshInfo->FullLoadFromFile();
5011
5012   const SMDS_MeshElement* e = _impl->GetMeshDS()->FindElement(id);
5013   if ( !e )
5014     THROW_SALOME_CORBA_EXCEPTION( "invalid element id", SALOME::BAD_PARAM );
5015
5016   return ( SMESH::EntityType ) e->GetEntityType();
5017 }
5018
5019 //=============================================================================
5020 /*!
5021  * Return type of the given element
5022  */
5023 //=============================================================================
5024
5025 SMESH::GeometryType SMESH_Mesh_i::GetElementShape( const SMESH::smIdType id )
5026 {
5027   if ( _preMeshInfo )
5028     _preMeshInfo->FullLoadFromFile();
5029
5030   const SMDS_MeshElement* e = _impl->GetMeshDS()->FindElement(id);
5031   if ( !e )
5032     THROW_SALOME_CORBA_EXCEPTION( "invalid element id", SALOME::BAD_PARAM );
5033
5034   return ( SMESH::GeometryType ) e->GetGeomType();
5035 }
5036
5037 //=============================================================================
5038 /*!
5039  * Return ID of elements for given submesh
5040  */
5041 //=============================================================================
5042
5043 SMESH::smIdType_array* SMESH_Mesh_i::GetSubMeshElementsId(const CORBA::Long ShapeID)
5044 {
5045   SMESH::smIdType_array_var aResult = new SMESH::smIdType_array();
5046
5047   SMESH_TRY;
5048   if ( _preMeshInfo )
5049     _preMeshInfo->FullLoadFromFile();
5050
5051   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
5052   if(!SM) return aResult._retn();
5053
5054   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
5055   if(!SDSM) return aResult._retn();
5056
5057   aResult->length(SDSM->NbElements());
5058
5059   SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
5060   smIdType i = 0;
5061   while ( eIt->more() ) {
5062     aResult[i++] = eIt->next()->GetID();
5063   }
5064
5065   SMESH_CATCH( SMESH::throwCorbaException );
5066
5067   return aResult._retn();
5068 }
5069
5070 //=============================================================================
5071 /*!
5072  * Return ID of nodes for given sub-mesh
5073  * If param all==true - return all nodes, else -
5074  * Return only nodes on shapes.
5075  */
5076 //=============================================================================
5077
5078 SMESH::smIdType_array* SMESH_Mesh_i::GetSubMeshNodesId(const CORBA::Long ShapeID,
5079                                                    CORBA::Boolean    all)
5080 {
5081   SMESH::smIdType_array_var aResult = new SMESH::smIdType_array();
5082
5083   SMESH_TRY;
5084   if ( _preMeshInfo )
5085     _preMeshInfo->FullLoadFromFile();
5086
5087   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
5088   if(!SM) return aResult._retn();
5089
5090   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
5091   if(!SDSM) return aResult._retn();
5092
5093   set<smIdType> theElems;
5094   if( !all || (SDSM->NbElements()==0) ) { // internal nodes or vertex submesh
5095     SMDS_NodeIteratorPtr nIt = SDSM->GetNodes();
5096     while ( nIt->more() ) {
5097       const SMDS_MeshNode* elem = nIt->next();
5098       theElems.insert( elem->GetID() );
5099     }
5100   }
5101   else { // all nodes of submesh elements
5102     SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
5103     while ( eIt->more() ) {
5104       const SMDS_MeshElement* anElem = eIt->next();
5105       SMDS_ElemIteratorPtr nIt = anElem->nodesIterator();
5106       while ( nIt->more() ) {
5107         const SMDS_MeshElement* elem = nIt->next();
5108         theElems.insert( elem->GetID() );
5109       }
5110     }
5111   }
5112
5113   aResult->length(theElems.size());
5114   set<smIdType>::iterator itElem;
5115   smIdType i = 0;
5116   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
5117     aResult[i++] = *itElem;
5118
5119   SMESH_CATCH( SMESH::throwCorbaException );
5120
5121   return aResult._retn();
5122 }
5123
5124 //=============================================================================
5125 /*!
5126  * Return type of elements for given sub-mesh
5127  */
5128 //=============================================================================
5129
5130 SMESH::ElementType SMESH_Mesh_i::GetSubMeshElementType(const CORBA::Long ShapeID)
5131 {
5132   SMESH::ElementType type = SMESH::ALL;
5133
5134   SMESH_TRY;
5135   if ( _preMeshInfo )
5136     _preMeshInfo->FullLoadFromFile();
5137
5138   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
5139   if(!SM) return SMESH::ALL;
5140
5141   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
5142   if(!SDSM) return SMESH::ALL;
5143
5144   if(SDSM->NbElements()==0)
5145     return (SM->GetSubShape().ShapeType() == TopAbs_VERTEX) ? SMESH::NODE : SMESH::ALL;
5146
5147   SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
5148   const SMDS_MeshElement* anElem = eIt->next();
5149
5150   type = ( SMESH::ElementType ) anElem->GetType();
5151
5152   SMESH_CATCH( SMESH::throwCorbaException );
5153
5154   return type;
5155 }
5156
5157
5158 //=============================================================================
5159 /*!
5160  * Return pointer to _impl as an integer value. Is called from constructor of SMESH_Client
5161  */
5162 //=============================================================================
5163
5164 CORBA::LongLong SMESH_Mesh_i::GetMeshPtr()
5165 {
5166   if ( _preMeshInfo )
5167     _preMeshInfo->FullLoadFromFile();
5168
5169   CORBA::LongLong pointeur = CORBA::LongLong(_impl);
5170   if ( MYDEBUG ) MESSAGE("CORBA::LongLong SMESH_Mesh_i::GetMeshPtr() "<<pointeur);
5171   return pointeur;
5172 }
5173
5174
5175 //=============================================================================
5176 /*!
5177  * Get XYZ coordinates of node as list of double
5178  * If there is not node for given ID - return empty list
5179  */
5180 //=============================================================================
5181
5182 SMESH::double_array* SMESH_Mesh_i::GetNodeXYZ(const SMESH::smIdType id)
5183 {
5184   if ( _preMeshInfo )
5185     _preMeshInfo->FullLoadFromFile();
5186
5187   SMESH::double_array_var aResult = new SMESH::double_array();
5188   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5189   if ( aMeshDS == NULL )
5190     return aResult._retn();
5191
5192   // find node
5193   const SMDS_MeshNode* aNode = aMeshDS->FindNode(id);
5194   if(!aNode)
5195     return aResult._retn();
5196
5197   // add coordinates
5198   aResult->length(3);
5199   aResult[0] = aNode->X();
5200   aResult[1] = aNode->Y();
5201   aResult[2] = aNode->Z();
5202   return aResult._retn();
5203 }
5204
5205
5206 //=============================================================================
5207 /*!
5208  * For given node return list of IDs of inverse elements
5209  * If there is not node for given ID - return empty list
5210  */
5211 //=============================================================================
5212
5213 SMESH::smIdType_array* SMESH_Mesh_i::GetNodeInverseElements(const SMESH::smIdType  id,
5214                                                             SMESH::ElementType elemType)
5215 {
5216   if ( _preMeshInfo )
5217     _preMeshInfo->FullLoadFromFile();
5218
5219   SMESH::smIdType_array_var aResult = new SMESH::smIdType_array();
5220   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5221   if ( aMeshDS == NULL )
5222     return aResult._retn();
5223
5224   // find node
5225   const SMDS_MeshNode* aNode = aMeshDS->FindNode( id );
5226   if ( !aNode )
5227     return aResult._retn();
5228
5229   // find inverse elements
5230   SMDSAbs_ElementType type = SMDSAbs_ElementType( elemType );
5231   SMDS_ElemIteratorPtr eIt = aNode->GetInverseElementIterator( type );
5232   aResult->length( aNode->NbInverseElements( type ));
5233   for( smIdType i = 0; eIt->more(); ++i )
5234   {
5235     const SMDS_MeshElement* elem = eIt->next();
5236     aResult[ i ] = elem->GetID();
5237   }
5238   return aResult._retn();
5239 }
5240
5241 //=============================================================================
5242 /*!
5243  * \brief Return position of a node on shape
5244  */
5245 //=============================================================================
5246
5247 SMESH::NodePosition* SMESH_Mesh_i::GetNodePosition(SMESH::smIdType NodeID)
5248 {
5249   if ( _preMeshInfo )
5250     _preMeshInfo->FullLoadFromFile();
5251
5252   SMESH::NodePosition* aNodePosition = new SMESH::NodePosition();
5253   aNodePosition->shapeID = 0;
5254   aNodePosition->shapeType = GEOM::SHAPE;
5255
5256   SMESHDS_Mesh* mesh = _impl->GetMeshDS();
5257   if ( !mesh ) return aNodePosition;
5258
5259   if ( const SMDS_MeshNode* aNode = mesh->FindNode(NodeID) )
5260   {
5261     if ( SMDS_PositionPtr pos = aNode->GetPosition() )
5262     {
5263       aNodePosition->shapeID = aNode->getshapeId();
5264       switch ( pos->GetTypeOfPosition() ) {
5265       case SMDS_TOP_EDGE:
5266         aNodePosition->shapeType = GEOM::EDGE;
5267         aNodePosition->params.length(1);
5268         aNodePosition->params[0] = SMDS_EdgePositionPtr( pos )->GetUParameter();
5269         break;
5270       case SMDS_TOP_FACE: {
5271         SMDS_FacePositionPtr fPos = pos;
5272         aNodePosition->shapeType = GEOM::FACE;
5273         aNodePosition->params.length(2);
5274         aNodePosition->params[0] = fPos->GetUParameter();
5275         aNodePosition->params[1] = fPos->GetVParameter();
5276         break;
5277       }
5278       case SMDS_TOP_VERTEX:
5279         aNodePosition->shapeType = GEOM::VERTEX;
5280         break;
5281       case SMDS_TOP_3DSPACE:
5282         if ( TopExp_Explorer(_impl->GetShapeToMesh(), TopAbs_SOLID).More() )
5283           aNodePosition->shapeType = GEOM::SOLID;
5284         else if ( TopExp_Explorer(_impl->GetShapeToMesh(), TopAbs_SHELL).More() )
5285           aNodePosition->shapeType = GEOM::SHELL;
5286         break;
5287       default:;
5288       }
5289     }
5290   }
5291   return aNodePosition;
5292 }
5293
5294 //=============================================================================
5295 /*!
5296  * \brief Return position of an element on shape
5297  */
5298 //=============================================================================
5299
5300 SMESH::ElementPosition SMESH_Mesh_i::GetElementPosition(SMESH::smIdType ElemID)
5301 {
5302   if ( _preMeshInfo )
5303     _preMeshInfo->FullLoadFromFile();
5304
5305   SMESH::ElementPosition anElementPosition;
5306   anElementPosition.shapeID = 0;
5307   anElementPosition.shapeType = GEOM::SHAPE;
5308
5309   SMESHDS_Mesh* mesh = _impl->GetMeshDS();
5310   if ( !mesh ) return anElementPosition;
5311
5312   if ( const SMDS_MeshElement* anElem = mesh->FindElement( ElemID ) )
5313   {
5314     anElementPosition.shapeID = anElem->getshapeId();
5315     const TopoDS_Shape& aSp = mesh->IndexToShape( anElem->getshapeId() );
5316     if ( !aSp.IsNull() ) {
5317       switch ( aSp.ShapeType() ) {
5318       case TopAbs_EDGE:
5319         anElementPosition.shapeType = GEOM::EDGE;
5320         break;
5321       case TopAbs_FACE:
5322         anElementPosition.shapeType = GEOM::FACE;
5323         break;
5324       case TopAbs_VERTEX:
5325         anElementPosition.shapeType = GEOM::VERTEX;
5326         break;
5327       case TopAbs_SOLID:
5328         anElementPosition.shapeType = GEOM::SOLID;
5329         break;
5330       case TopAbs_SHELL:
5331         anElementPosition.shapeType = GEOM::SHELL;
5332         break;
5333       default:;
5334       }
5335     }
5336   }
5337   return anElementPosition;
5338 }
5339
5340 //=============================================================================
5341 /*!
5342  * If given element is node return IDs of shape from position
5343  * If there is not node for given ID - return -1
5344  */
5345 //=============================================================================
5346
5347 CORBA::Long SMESH_Mesh_i::GetShapeID(const SMESH::smIdType id)
5348 {
5349   if ( _preMeshInfo )
5350     _preMeshInfo->FullLoadFromFile();
5351
5352   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5353   if ( aMeshDS == NULL )
5354     return -1;
5355
5356   // try to find node
5357   const SMDS_MeshNode* aNode = aMeshDS->FindNode(id);
5358   if(aNode) {
5359     return aNode->getshapeId();
5360   }
5361
5362   return -1;
5363 }
5364
5365
5366 //=============================================================================
5367 /*!
5368  * For given element return ID of result shape after
5369  * ::FindShape() from SMESH_MeshEditor
5370  * If there is not element for given ID - return -1
5371  */
5372 //=============================================================================
5373
5374 CORBA::Long SMESH_Mesh_i::GetShapeIDForElem(const SMESH::smIdType id)
5375 {
5376   if ( _preMeshInfo )
5377     _preMeshInfo->FullLoadFromFile();
5378
5379   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5380   if ( aMeshDS == NULL )
5381     return -1;
5382
5383   // try to find element
5384   const SMDS_MeshElement* elem = aMeshDS->FindElement(id);
5385   if(!elem)
5386     return -1;
5387
5388   ::SMESH_MeshEditor aMeshEditor(_impl);
5389   int index = aMeshEditor.FindShape( elem );
5390   if(index>0)
5391     return index;
5392
5393   return -1;
5394 }
5395
5396
5397 //=============================================================================
5398 /*!
5399  * Return number of nodes for given element
5400  * If there is not element for given ID - return -1
5401  */
5402 //=============================================================================
5403
5404 CORBA::Short SMESH_Mesh_i::GetElemNbNodes(const SMESH::smIdType id)
5405 {
5406   if ( _preMeshInfo )
5407     _preMeshInfo->FullLoadFromFile();
5408
5409   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5410   if ( aMeshDS == NULL ) return -1;
5411   // try to find element
5412   const SMDS_MeshElement* elem = aMeshDS->FindElement(id);
5413   if(!elem) return -1;
5414   return elem->NbNodes();
5415 }
5416
5417
5418 //=============================================================================
5419 /*!
5420  * Return ID of node by given index for given element
5421  * If there is not element for given ID - return -1
5422  * If there is not node for given index - return -2
5423  */
5424 //=============================================================================
5425
5426 SMESH::smIdType SMESH_Mesh_i::GetElemNode(const SMESH::smIdType id, const CORBA::Short index)
5427 {
5428   if ( _preMeshInfo )
5429     _preMeshInfo->FullLoadFromFile();
5430
5431   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5432   if ( aMeshDS == NULL ) return -1;
5433   const SMDS_MeshElement* elem = aMeshDS->FindElement(id);
5434   if(!elem) return -1;
5435   if( index>=elem->NbNodes() || index<0 ) return -1;
5436   return elem->GetNode(index)->GetID();
5437 }
5438
5439 //=============================================================================
5440 /*!
5441  * Return IDs of nodes of given element
5442  */
5443 //=============================================================================
5444
5445 SMESH::smIdType_array* SMESH_Mesh_i::GetElemNodes(const SMESH::smIdType id)
5446 {
5447   if ( _preMeshInfo )
5448     _preMeshInfo->FullLoadFromFile();
5449
5450   SMESH::smIdType_array_var aResult = new SMESH::smIdType_array();
5451   if ( SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS() )
5452   {
5453     if ( const SMDS_MeshElement* elem = aMeshDS->FindElement(id) )
5454     {
5455       aResult->length( elem->NbNodes() );
5456       for ( SMESH::smIdType i = 0; i < aResult->length(); ++i )
5457         if ( const SMDS_MeshNode* n = elem->GetNode( i ))
5458           aResult[ i ] = n->GetID();
5459     }
5460   }
5461   return aResult._retn();
5462 }
5463
5464 //=============================================================================
5465 /*!
5466  * Return true if given node is medium node
5467  * in given quadratic element
5468  */
5469 //=============================================================================
5470
5471 CORBA::Boolean SMESH_Mesh_i::IsMediumNode(const SMESH::smIdType ide, const SMESH::smIdType idn)
5472 {
5473   if ( _preMeshInfo )
5474     _preMeshInfo->FullLoadFromFile();
5475
5476   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5477   if ( aMeshDS == NULL ) return false;
5478   // try to find node
5479   const SMDS_MeshNode* aNode = aMeshDS->FindNode(idn);
5480   if(!aNode) return false;
5481   // try to find element
5482   const SMDS_MeshElement* elem = aMeshDS->FindElement(ide);
5483   if(!elem) return false;
5484
5485   return elem->IsMediumNode(aNode);
5486 }
5487
5488
5489 //=============================================================================
5490 /*!
5491  * Return true if given node is medium node
5492  * in one of quadratic elements
5493  */
5494 //=============================================================================
5495
5496 CORBA::Boolean SMESH_Mesh_i::IsMediumNodeOfAnyElem(const SMESH::smIdType idn,
5497                                                    SMESH::ElementType theElemType)
5498 {
5499   if ( _preMeshInfo )
5500     _preMeshInfo->FullLoadFromFile();
5501
5502   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5503   if ( aMeshDS == NULL ) return false;
5504
5505   // try to find node
5506   const SMDS_MeshNode* aNode = aMeshDS->FindNode(idn);
5507   if(!aNode) return false;
5508
5509   SMESH_MesherHelper aHelper( *(_impl) );
5510
5511   SMDSAbs_ElementType aType;
5512   if(theElemType==SMESH::EDGE) aType = SMDSAbs_Edge;
5513   else if(theElemType==SMESH::FACE) aType = SMDSAbs_Face;
5514   else if(theElemType==SMESH::VOLUME) aType = SMDSAbs_Volume;
5515   else aType = SMDSAbs_All;
5516
5517   return aHelper.IsMedium(aNode,aType);
5518 }
5519
5520
5521 //=============================================================================
5522 /*!
5523  * Return number of edges for given element
5524  */
5525 //=============================================================================
5526
5527 CORBA::Long SMESH_Mesh_i::ElemNbEdges(const SMESH::smIdType id)
5528 {
5529   if ( _preMeshInfo )
5530     _preMeshInfo->FullLoadFromFile();
5531
5532   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5533   if ( aMeshDS == NULL ) return -1;
5534   const SMDS_MeshElement* elem = aMeshDS->FindElement(id);
5535   if(!elem) return -1;
5536   return elem->NbEdges();
5537 }
5538
5539
5540 //=============================================================================
5541 /*!
5542  * Return number of faces for given element
5543  */
5544 //=============================================================================
5545
5546 CORBA::Long SMESH_Mesh_i::ElemNbFaces(const SMESH::smIdType id)
5547 {
5548   if ( _preMeshInfo )
5549     _preMeshInfo->FullLoadFromFile();
5550
5551   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5552   if ( aMeshDS == NULL ) return -1;
5553   const SMDS_MeshElement* elem = aMeshDS->FindElement(id);
5554   if(!elem) return -1;
5555   return elem->NbFaces();
5556 }
5557
5558 //================================================================================
5559 /*!
5560  * \brief Return nodes of given face (counted from zero) for given element.
5561  */
5562 //================================================================================
5563
5564 SMESH::smIdType_array* SMESH_Mesh_i::GetElemFaceNodes(SMESH::smIdType  elemId,
5565                                                       CORBA::Short     faceIndex)
5566 {
5567   if ( _preMeshInfo )
5568     _preMeshInfo->FullLoadFromFile();
5569
5570   SMESH::smIdType_array_var aResult = new SMESH::smIdType_array();
5571   if ( SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS() )
5572   {
5573     if ( const SMDS_MeshElement* elem = aMeshDS->FindElement(elemId) )
5574     {
5575       SMDS_VolumeTool vtool( elem, /*skipCentralNodes = */false );
5576       if ( faceIndex < vtool.NbFaces() )
5577       {
5578         aResult->length( vtool.NbFaceNodes( faceIndex ));
5579         const SMDS_MeshNode** nn = vtool.GetFaceNodes( faceIndex );
5580         for ( SMESH::smIdType i = 0; i < aResult->length(); ++i )
5581           aResult[ i ] = nn[ i ]->GetID();
5582       }
5583     }
5584   }
5585   return aResult._retn();
5586 }
5587
5588 //================================================================================
5589 /*!
5590  * \brief Return three components of normal of given mesh face.
5591  */
5592 //================================================================================
5593
5594 SMESH::double_array* SMESH_Mesh_i::GetFaceNormal(CORBA::Long    elemId,
5595                                                  CORBA::Boolean normalized)
5596 {
5597   if ( _preMeshInfo )
5598     _preMeshInfo->FullLoadFromFile();
5599
5600   SMESH::double_array_var aResult = new SMESH::double_array();
5601
5602   if ( SMESHDS_Mesh* mesh = _impl->GetMeshDS() )
5603   {
5604     gp_XYZ normal;
5605     if ( SMESH_MeshAlgos::FaceNormal( mesh->FindElement(elemId), normal, normalized ))
5606     {
5607       aResult->length( 3 );
5608       aResult[ 0 ] = normal.X();
5609       aResult[ 1 ] = normal.Y();
5610       aResult[ 2 ] = normal.Z();
5611     }
5612   }
5613   return aResult._retn();
5614 }
5615
5616 //================================================================================
5617 /*!
5618  * \brief Return an element based on all given nodes.
5619  */
5620 //================================================================================
5621
5622 SMESH::smIdType SMESH_Mesh_i::FindElementByNodes(const SMESH::smIdType_array& nodes)
5623 {
5624   if ( _preMeshInfo )
5625     _preMeshInfo->FullLoadFromFile();
5626
5627   CORBA::Long elemID(0);
5628   if ( SMESHDS_Mesh* mesh = _impl->GetMeshDS() )
5629   {
5630     vector< const SMDS_MeshNode * > nn( nodes.length() );
5631     for ( CORBA::ULong i = 0; i < nodes.length(); ++i )
5632       if ( !( nn[i] = mesh->FindNode( nodes[i] )))
5633         return elemID;
5634
5635     const SMDS_MeshElement* elem = mesh->FindElement( nn, SMDSAbs_All, /*noMedium=*/false );
5636     if ( !elem && ( _impl->NbEdges  ( ORDER_QUADRATIC ) ||
5637                     _impl->NbFaces  ( ORDER_QUADRATIC ) ||
5638                     _impl->NbVolumes( ORDER_QUADRATIC )))
5639       elem = mesh->FindElement( nn, SMDSAbs_All, /*noMedium=*/true );
5640
5641     if ( elem ) elemID = CORBA::Long( elem->GetID() );
5642   }
5643   return elemID;
5644 }
5645
5646 //================================================================================
5647 /*!
5648  * \brief Return elements including all given nodes.
5649  */
5650 //================================================================================
5651
5652 SMESH::smIdType_array* SMESH_Mesh_i::GetElementsByNodes(const SMESH::smIdType_array& nodes,
5653                                                         SMESH::ElementType       elemType)
5654 {
5655   if ( _preMeshInfo )
5656     _preMeshInfo->FullLoadFromFile();
5657
5658   SMESH::smIdType_array_var result = new SMESH::smIdType_array();
5659
5660   if ( SMESHDS_Mesh* mesh = _impl->GetMeshDS() )
5661   {
5662     vector< const SMDS_MeshNode * > nn( nodes.length() );
5663     for ( SMESH::smIdType i = 0; i < nodes.length(); ++i )
5664       nn[i] = mesh->FindNode( nodes[i] );
5665
5666     std::vector<const SMDS_MeshElement *> elems;
5667     mesh->GetElementsByNodes( nn, elems, (SMDSAbs_ElementType) elemType );
5668     result->length( elems.size() );
5669     for ( size_t i = 0; i < elems.size(); ++i )
5670       result[i] = elems[i]->GetID();
5671   }
5672   return result._retn();
5673 }
5674
5675 //=============================================================================
5676 /*!
5677  * Return true if given element is polygon
5678  */
5679 //=============================================================================
5680
5681 CORBA::Boolean SMESH_Mesh_i::IsPoly(const SMESH::smIdType id)
5682 {
5683   if ( _preMeshInfo )
5684     _preMeshInfo->FullLoadFromFile();
5685
5686   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5687   if ( aMeshDS == NULL ) return false;
5688   const SMDS_MeshElement* elem = aMeshDS->FindElement(id);
5689   if(!elem) return false;
5690   return elem->IsPoly();
5691 }
5692
5693
5694 //=============================================================================
5695 /*!
5696  * Return true if given element is quadratic
5697  */
5698 //=============================================================================
5699
5700 CORBA::Boolean SMESH_Mesh_i::IsQuadratic(const SMESH::smIdType id)
5701 {
5702   if ( _preMeshInfo )
5703     _preMeshInfo->FullLoadFromFile();
5704
5705   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5706   if ( aMeshDS == NULL ) return false;
5707   const SMDS_MeshElement* elem = aMeshDS->FindElement(id);
5708   if(!elem) return false;
5709   return elem->IsQuadratic();
5710 }
5711
5712 //=============================================================================
5713 /*!
5714  * Return diameter of ball discrete element or zero in case of an invalid \a id
5715  */
5716 //=============================================================================
5717
5718 CORBA::Double SMESH_Mesh_i::GetBallDiameter(SMESH::smIdType id)
5719 {
5720   if ( _preMeshInfo )
5721     _preMeshInfo->FullLoadFromFile();
5722
5723   if ( const SMDS_BallElement* ball =
5724        SMDS_Mesh::DownCast<SMDS_BallElement>( _impl->GetMeshDS()->FindElement( id )))
5725     return ball->GetDiameter();
5726
5727   return 0;
5728 }
5729
5730 //=============================================================================
5731 /*!
5732  * Return bary center for given element
5733  */
5734 //=============================================================================
5735
5736 SMESH::double_array* SMESH_Mesh_i::BaryCenter(const SMESH::smIdType id)
5737 {
5738   if ( _preMeshInfo )
5739     _preMeshInfo->FullLoadFromFile();
5740
5741   SMESH::double_array_var aResult = new SMESH::double_array();
5742   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
5743   if ( aMeshDS == NULL )
5744     return aResult._retn();
5745
5746   const SMDS_MeshElement* elem = aMeshDS->FindElement(id);
5747   if(!elem)
5748     return aResult._retn();
5749
5750   if(elem->GetType()==SMDSAbs_Volume) {
5751     SMDS_VolumeTool aTool;
5752     if(aTool.Set(elem)) {
5753       aResult->length(3);
5754       if (!aTool.GetBaryCenter( aResult[0], aResult[1], aResult[2]) )
5755         aResult->length(0);
5756     }
5757   }
5758   else {
5759     SMDS_ElemIteratorPtr anIt = elem->nodesIterator();
5760     int nbn = 0;
5761     double x=0., y=0., z=0.;
5762     for(; anIt->more(); ) {
5763       nbn++;
5764       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>(anIt->next());
5765       x += aNode->X();
5766       y += aNode->Y();
5767       z += aNode->Z();
5768     }
5769     if(nbn>0) {
5770       // add coordinates
5771       aResult->length(3);
5772       aResult[0] = x/nbn;
5773       aResult[1] = y/nbn;
5774       aResult[2] = z/nbn;
5775     }
5776   }
5777
5778   return aResult._retn();
5779 }
5780
5781 //================================================================================
5782 /*!
5783  * \brief Create a group of elements preventing computation of a sub-shape
5784  */
5785 //================================================================================
5786
5787 SMESH::ListOfGroups*
5788 SMESH_Mesh_i::MakeGroupsOfBadInputElements( int         theSubShapeID,
5789                                             const char* theGroupName )
5790 {
5791   Unexpect aCatch(SALOME_SalomeException);
5792
5793   if ( !theGroupName || strlen( theGroupName) == 0 )
5794     THROW_SALOME_CORBA_EXCEPTION( "empty group name",SALOME::BAD_PARAM );
5795
5796   SMESH::ListOfGroups_var groups = new SMESH::ListOfGroups;
5797   ::SMESH_MeshEditor::ElemFeatures elemType;
5798
5799   // submesh by subshape id
5800   if ( !_impl->HasShapeToMesh() ) theSubShapeID = 1;
5801   if ( SMESH_subMesh * sm = _impl->GetSubMeshContaining( theSubShapeID ))
5802   {
5803     // compute error
5804     SMESH_ComputeErrorPtr error = sm->GetComputeError();
5805     if ( error && error->HasBadElems() )
5806     {
5807       // sort bad elements by type
5808       vector< const SMDS_MeshElement* > elemsByType[ SMDSAbs_NbElementTypes ];
5809       const list<const SMDS_MeshElement*>& badElems =
5810         static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
5811       list<const SMDS_MeshElement*>::const_iterator elemIt  = badElems.begin();
5812       list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
5813       for ( ; elemIt != elemEnd; ++elemIt )
5814       {
5815         const SMDS_MeshElement* elem = *elemIt;
5816         if ( !elem ) continue;
5817
5818         if ( elem->GetID() < 1 )
5819         {
5820           // elem is a temporary element, make a real element
5821           vector< const SMDS_MeshNode* > nodes;
5822           SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
5823           while ( nIt->more() && elem )
5824           {
5825             nodes.push_back( nIt->next() );
5826             if ( nodes.back()->GetID() < 1 )
5827               elem = 0;  // a temporary element on temporary nodes
5828           }
5829           if ( elem )
5830           {
5831             ::SMESH_MeshEditor editor( _impl );
5832             elem = editor.AddElement( nodes, elemType.Init( elem ));
5833           }
5834         }
5835         if ( elem )
5836           elemsByType[ elem->GetType() ].push_back( elem );
5837       }
5838
5839       // how many groups to create?
5840       int nbTypes = 0;
5841       for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
5842         nbTypes += int( !elemsByType[ i ].empty() );
5843       groups->length( nbTypes );
5844
5845       // create groups
5846       for ( int i = 0, iG = -1; i < SMDSAbs_NbElementTypes; ++i )
5847       {
5848         vector< const SMDS_MeshElement* >& elems = elemsByType[ i ];
5849         if ( elems.empty() ) continue;
5850
5851         groups[ ++iG ] = createGroup( SMESH::ElementType(i), theGroupName );
5852         if ( _gen_i->CanPublishInStudy( groups[ iG ] ))
5853         {
5854           SMESH::SMESH_Mesh_var mesh = _this();
5855           SALOMEDS::SObject_wrap aSO =
5856             _gen_i->PublishGroup( mesh, groups[ iG ],
5857                                  GEOM::GEOM_Object::_nil(), theGroupName);
5858         }
5859         SMESH_GroupBase_i* grp_i = SMESH::DownCast< SMESH_GroupBase_i* >( groups[ iG ]);
5860         if ( !grp_i ) continue;
5861
5862         if ( SMESHDS_Group*  grpDS = dynamic_cast< SMESHDS_Group* >( grp_i->GetGroupDS() ))
5863           for ( size_t iE = 0; iE < elems.size(); ++iE )
5864             grpDS->SMDSGroup().Add( elems[ iE ]);
5865       }
5866     }
5867   }
5868
5869   return groups._retn();
5870 }
5871
5872 //=============================================================================
5873 /*!
5874  * Create and publish group servants if any groups were imported or created anyhow
5875  */
5876 //=============================================================================
5877
5878 void SMESH_Mesh_i::CreateGroupServants()
5879 {
5880   SMESH::SMESH_Mesh_var aMesh = _this();
5881
5882   set<int> addedIDs;
5883   ::SMESH_Mesh::GroupIteratorPtr groupIt = _impl->GetGroups();
5884   while ( groupIt->more() )
5885   {
5886     ::SMESH_Group* group = groupIt->next();
5887     int             anId = group->GetID();
5888
5889     map<int, SMESH::SMESH_GroupBase_ptr>::iterator it = _mapGroups.find(anId);
5890     if ( it != _mapGroups.end() && !CORBA::is_nil( it->second ))
5891       continue;
5892     addedIDs.insert( anId );
5893
5894     SMESH_GroupBase_i* aGroupImpl;
5895     TopoDS_Shape       shape;
5896     if ( SMESHDS_GroupOnGeom* groupOnGeom =
5897          dynamic_cast<SMESHDS_GroupOnGeom*>( group->GetGroupDS() ))
5898     {
5899       aGroupImpl = new SMESH_GroupOnGeom_i( SMESH_Gen_i::GetPOA(), this, anId );
5900       shape      = groupOnGeom->GetShape();
5901     }
5902     else {
5903       aGroupImpl = new SMESH_Group_i( SMESH_Gen_i::GetPOA(), this, anId );
5904     }
5905
5906     SMESH::SMESH_GroupBase_var groupVar = aGroupImpl->_this();
5907     _mapGroups[anId] = SMESH::SMESH_GroupBase::_duplicate( groupVar );
5908     aGroupImpl->Register();
5909
5910     // register CORBA object for persistence
5911     int nextId = _gen_i->RegisterObject( groupVar );
5912     if(MYDEBUG) { MESSAGE( "Add group to map with id = "<< nextId); }
5913     else        { (void)nextId; } // avoid "unused variable" warning in release mode
5914
5915     // publishing the groups in the study
5916     GEOM::GEOM_Object_var shapeVar = _gen_i->ShapeToGeomObject( shape );
5917     _gen_i->PublishGroup( aMesh, groupVar, shapeVar, group->GetName());
5918   }
5919
5920   if ( !addedIDs.empty() )
5921   {
5922     // python dump
5923     map<int, SMESH::SMESH_GroupBase_ptr>::iterator i_grp = _mapGroups.begin();
5924     for ( int index = 0; i_grp != _mapGroups.end(); ++index, ++i_grp )
5925     {
5926       set<int>::iterator it = addedIDs.find( i_grp->first );
5927       if ( it != addedIDs.end() )
5928       {
5929         TPythonDump() << i_grp->second << " = " << aMesh << ".GetGroups()[ "<< index << " ]";
5930         addedIDs.erase( it );
5931         if ( addedIDs.empty() )
5932           break;
5933       }
5934     }
5935   }
5936 }
5937
5938 //=============================================================================
5939 /*!
5940  * \brief Return true if all sub-meshes are computed OK - to update an icon
5941  */
5942 //=============================================================================
5943
5944 bool SMESH_Mesh_i::IsComputedOK()
5945 {
5946   return _impl->IsComputedOK();
5947 }
5948
5949 //=============================================================================
5950 /*!
5951  * \brief Return groups cantained in _mapGroups by their IDs
5952  */
5953 //=============================================================================
5954
5955 SMESH::ListOfGroups* SMESH_Mesh_i::GetGroups(const list<int>& groupIDs) const
5956 {
5957   int nbGroups = groupIDs.size();
5958   SMESH::ListOfGroups_var aList = new SMESH::ListOfGroups();
5959   aList->length( nbGroups );
5960
5961   list<int>::const_iterator ids = groupIDs.begin();
5962   for ( nbGroups = 0; ids != groupIDs.end(); ++ids )
5963   {
5964     map<int, SMESH::SMESH_GroupBase_ptr>::const_iterator it = _mapGroups.find( *ids );
5965     if ( it != _mapGroups.end() && !CORBA::is_nil( it->second ))
5966       aList[nbGroups++] = SMESH::SMESH_GroupBase::_duplicate( it->second );
5967   }
5968   aList->length( nbGroups );
5969   return aList._retn();
5970 }
5971
5972 //=============================================================================
5973 /*!
5974  * \brief Return information about imported file
5975  */
5976 //=============================================================================
5977
5978 SMESH::MedFileInfo* SMESH_Mesh_i::GetMEDFileInfo()
5979 {
5980   SMESH::MedFileInfo_var res( _medFileInfo );
5981   if ( !res.operator->() ) {
5982     res = new SMESH::MedFileInfo;
5983     res->fileName = "";
5984     res->fileSize = res->major = res->minor = res->release = -1;
5985   }
5986   return res._retn();
5987 }
5988
5989 //=======================================================================
5990 //function : FileInfoToString
5991 //purpose  : Persistence of file info
5992 //=======================================================================
5993
5994 std::string SMESH_Mesh_i::FileInfoToString()
5995 {
5996   std::string s;
5997   if ( &_medFileInfo.in() && _medFileInfo->fileName[0] )
5998   {
5999     s = SMESH_Comment( _medFileInfo->fileSize )
6000       << " " << _medFileInfo->major
6001       << " " << _medFileInfo->minor
6002       << " " << _medFileInfo->release
6003       << " " << _medFileInfo->fileName;
6004   }
6005   return s;
6006 }
6007
6008 //=======================================================================
6009 //function : FileInfoFromString
6010 //purpose  : Persistence of file info
6011 //=======================================================================
6012
6013 void SMESH_Mesh_i::FileInfoFromString(const std::string& info)
6014 {
6015   std::string size, major, minor, release, fileName;
6016   std::istringstream is(info);
6017   is >> size >> major >> minor >> release;
6018   fileName = info.data() + ( size.size()   + 1 +
6019                              major.size()  + 1 +
6020                              minor.size()  + 1 +
6021                              release.size()+ 1 );
6022
6023   _medFileInfo           = new SMESH::MedFileInfo();
6024   _medFileInfo->fileName = fileName.c_str();
6025   _medFileInfo->fileSize = atoi( size.c_str() );
6026   _medFileInfo->major    = atoi( major.c_str() );
6027   _medFileInfo->minor    = atoi( minor.c_str() );
6028   _medFileInfo->release  = atoi( release.c_str() );
6029 }
6030
6031 //=============================================================================
6032 /*!
6033  * \brief Pass names of mesh groups from study to mesh DS
6034  */
6035 //=============================================================================
6036
6037 void SMESH_Mesh_i::checkGroupNames()
6038 {
6039   int nbGrp = NbGroups();
6040   if ( !nbGrp )
6041     return;
6042
6043   SMESH::ListOfGroups* grpList = 0;
6044   // avoid dump of "GetGroups"
6045   {
6046     // store python dump into a local variable inside local scope
6047     SMESH::TPythonDump pDump; // do not delete this line of code
6048     grpList = GetGroups();
6049   }
6050
6051   for ( int gIndx = 0; gIndx < nbGrp; gIndx++ ) {
6052     SMESH::SMESH_GroupBase_ptr aGrp = (*grpList)[ gIndx ];
6053     if ( !aGrp )
6054       continue;
6055     SALOMEDS::SObject_wrap aGrpSO = _gen_i->ObjectToSObject( aGrp );
6056     if ( aGrpSO->_is_nil() )
6057       continue;
6058     // correct name of the mesh group if necessary
6059     const char* guiName = aGrpSO->GetName();
6060     if ( strcmp(guiName, aGrp->GetName()) )
6061       aGrp->SetName( guiName );
6062   }
6063 }
6064
6065 //=============================================================================
6066 /*!
6067  * \brief Set list of notebook variables used for Mesh operations separated by ":" symbol
6068  */
6069 //=============================================================================
6070 void SMESH_Mesh_i::SetParameters(const char* theParameters)
6071 {
6072   SMESH_Gen_i::GetSMESHGen()->UpdateParameters( CORBA::Object_var( _this() ).in(),
6073                                                 theParameters );
6074 }
6075
6076 //=============================================================================
6077 /*!
6078  * \brief Return list of notebook variables used for Mesh operations separated by ":" symbol
6079  */
6080 //=============================================================================
6081
6082 char* SMESH_Mesh_i::GetParameters()
6083 {
6084   return SMESH_Gen_i::GetSMESHGen()->GetParameters( SMESH::SMESH_Mesh_var( _this()) );
6085 }
6086
6087 //=============================================================================
6088 /*!
6089  * \brief Return list of notebook variables used for last Mesh operation
6090  */
6091 //=============================================================================
6092 SMESH::string_array* SMESH_Mesh_i::GetLastParameters()
6093 {
6094   SMESH::string_array_var aResult = new SMESH::string_array();
6095   SMESH_Gen_i *gen = SMESH_Gen_i::GetSMESHGen();
6096   if(gen) {
6097     CORBA::String_var aParameters = GetParameters();
6098     SALOMEDS::ListOfListOfStrings_var aSections = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->ParseVariables(aParameters);
6099     if ( aSections->length() > 0 ) {
6100       SALOMEDS::ListOfStrings aVars = aSections[ aSections->length() - 1 ];
6101       aResult->length( aVars.length() );
6102       for ( CORBA::ULong i = 0;i < aVars.length(); i++ )
6103         aResult[i] = CORBA::string_dup( aVars[i] );
6104     }
6105   }
6106   return aResult._retn();
6107 }
6108
6109 //================================================================================
6110 /*!
6111  * \brief Return types of elements it contains
6112  */
6113 //================================================================================
6114
6115 SMESH::array_of_ElementType* SMESH_Mesh_i::GetTypes()
6116 {
6117   if ( _preMeshInfo )
6118     return _preMeshInfo->GetTypes();
6119
6120   SMESH::array_of_ElementType_var types = new SMESH::array_of_ElementType;
6121
6122   types->length( 5 );
6123   int nbTypes = 0;
6124   if (_impl->NbEdges())      types[nbTypes++] = SMESH::EDGE;
6125   if (_impl->NbFaces())      types[nbTypes++] = SMESH::FACE;
6126   if (_impl->NbVolumes())    types[nbTypes++] = SMESH::VOLUME;
6127   if (_impl->Nb0DElements()) types[nbTypes++] = SMESH::ELEM0D;
6128   if (_impl->NbBalls())      types[nbTypes++] = SMESH::BALL;
6129   if (_impl->NbNodes() &&
6130       nbTypes == 0 )         types[nbTypes++] = SMESH::NODE;
6131   types->length( nbTypes );
6132
6133   return types._retn();
6134 }
6135
6136 //================================================================================
6137 /*!
6138  * \brief Return self
6139  */
6140 //================================================================================
6141
6142 SMESH::SMESH_Mesh_ptr SMESH_Mesh_i::GetMesh()
6143 {
6144   return SMESH::SMESH_Mesh::_duplicate( _this() );
6145 }
6146
6147 //================================================================================
6148 /*!
6149  * \brief Return false if GetMeshInfo() return incorrect information that may
6150  *        happen if mesh data is not yet fully loaded from the file of study.
6151  * 
6152  * 
6153  */
6154 //================================================================================
6155
6156 bool SMESH_Mesh_i::IsMeshInfoCorrect()
6157 {
6158   return _preMeshInfo ? _preMeshInfo->IsMeshInfoCorrect() : true;
6159 }
6160
6161 //=============================================================================
6162 /*!
6163  * \brief Return number of mesh elements per each \a EntityType
6164  */
6165 //=============================================================================
6166
6167 SMESH::smIdType_array* SMESH_Mesh_i::GetMeshInfo()
6168 {
6169   if ( _preMeshInfo )
6170     return _preMeshInfo->GetMeshInfo();
6171
6172   SMESH::smIdType_array_var aRes = new SMESH::smIdType_array();
6173   aRes->length(SMESH::Entity_Last);
6174   for (int i = SMESH::Entity_Node; i < SMESH::Entity_Last; i++)
6175     aRes[i] = 0;
6176   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
6177   if (!aMeshDS)
6178     return aRes._retn();
6179   const SMDS_MeshInfo& aMeshInfo = aMeshDS->GetMeshInfo();
6180   for (int i = SMESH::Entity_Node; i < SMESH::Entity_Last; i++)
6181     aRes[i] = aMeshInfo.NbEntities((SMDSAbs_EntityType)i);
6182   return aRes._retn();
6183 }
6184
6185 //=============================================================================
6186 /*!
6187  * \brief Return number of mesh elements per each \a ElementType
6188  */
6189 //=============================================================================
6190
6191 SMESH::smIdType_array* SMESH_Mesh_i::GetNbElementsByType()
6192 {
6193   SMESH::smIdType_array_var aRes = new SMESH::smIdType_array();
6194   aRes->length(SMESH::NB_ELEMENT_TYPES);
6195   for (smIdType i = 0; i < SMESH::NB_ELEMENT_TYPES; i++)
6196     aRes[ i ] = 0;
6197
6198   const SMDS_MeshInfo* meshInfo = 0;
6199   if ( _preMeshInfo )
6200     meshInfo = _preMeshInfo;
6201   else if ( SMESHDS_Mesh* meshDS = _impl->GetMeshDS() )
6202     meshInfo = & meshDS->GetMeshInfo();
6203
6204   if (meshInfo)
6205     for (smIdType i = 0; i < SMESH::NB_ELEMENT_TYPES; i++)
6206       aRes[i] = meshInfo->NbElements((SMDSAbs_ElementType)i);
6207
6208   return aRes._retn();
6209 }
6210
6211 //=============================================================================
6212 /*
6213  * Collect statistic of mesh elements given by iterator
6214  */
6215 //=============================================================================
6216
6217 void SMESH_Mesh_i::CollectMeshInfo(const SMDS_ElemIteratorPtr theItr,
6218                                    SMESH::smIdType_array&     theInfo)
6219 {
6220   if (!theItr) return;
6221   while (theItr->more())
6222     theInfo[ theItr->next()->GetEntityType() ]++;
6223 }
6224 //=============================================================================
6225 /*
6226  * Return mesh unstructed grid information.
6227  */
6228 //=============================================================================
6229
6230 SALOMEDS::TMPFile* SMESH_Mesh_i::GetVtkUgStream()
6231 {
6232   SALOMEDS::TMPFile_var SeqFile;
6233   if ( SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS() ) {
6234     SMDS_UnstructuredGrid* aGrid = aMeshDS->GetGrid();
6235     if(aGrid) {
6236       vtkUnstructuredGridWriter* aWriter = vtkUnstructuredGridWriter::New();
6237       aWriter->WriteToOutputStringOn();
6238       aWriter->SetInputData(aGrid);
6239       aWriter->SetFileTypeToBinary();
6240       aWriter->Write();
6241       char* str = aWriter->GetOutputString();
6242       int size = aWriter->GetOutputStringLength();
6243
6244       //Allocate octet buffer of required size
6245       CORBA::Octet* OctetBuf = SALOMEDS::TMPFile::allocbuf(size);
6246       //Copy ostrstream content to the octet buffer
6247       memcpy(OctetBuf, str, size);
6248       //Create and return TMPFile
6249       SeqFile = new SALOMEDS::TMPFile(size, size, OctetBuf, 1);
6250       aWriter->Delete();
6251     }
6252   }
6253   return SeqFile._retn();
6254 }
6255
6256 //=============================================================================
6257 namespace /* Iterators used in SMESH_Mesh_i::GetElements(SMESH::SMESH_IDSource_var obj,
6258            *                                             SMESH::ElementType        type) */
6259 {
6260   using namespace SMESH::Controls;
6261   //-----------------------------------------------------------------------------
6262   struct PredicateIterator : public SMDS_ElemIterator
6263   {
6264     SMDS_ElemIteratorPtr    _elemIter;
6265     PredicatePtr            _predicate;
6266     const SMDS_MeshElement* _elem;
6267     SMDSAbs_ElementType     _type;
6268
6269     PredicateIterator( SMDS_ElemIteratorPtr iterator,
6270                        PredicatePtr         predicate,
6271                        SMDSAbs_ElementType  type):
6272       _elemIter(iterator), _predicate(predicate), _type(type)
6273     {
6274       next();
6275     }
6276     virtual bool more()
6277     {
6278       return _elem;
6279     }
6280     virtual const SMDS_MeshElement* next()
6281     {
6282       const SMDS_MeshElement* res = _elem;
6283       _elem = 0;
6284       while ( _elemIter->more() && !_elem )
6285       {
6286         if ((_elem = _elemIter->next()) &&
6287             (( _type != SMDSAbs_All && _type != _elem->GetType() ) ||
6288              ( !_predicate->IsSatisfy( _elem->GetID() ))))
6289           _elem = 0;
6290       }
6291       return res;
6292     }
6293   };
6294
6295   //-----------------------------------------------------------------------------
6296   struct IDSourceIterator : public SMDS_ElemIterator
6297   {
6298     const SMESH::smIdType*        _idPtr;
6299     const SMESH::smIdType*        _idEndPtr;
6300     SMESH::smIdType_array_var     _idArray;
6301     const SMDS_Mesh*              _mesh;
6302     const SMDSAbs_ElementType     _type;
6303     const SMDS_MeshElement*       _elem;
6304
6305     IDSourceIterator( const SMDS_Mesh*       mesh,
6306                       const SMESH::smIdType* ids,
6307                       const smIdType         nbIds,
6308                       SMDSAbs_ElementType    type):
6309       _idPtr( ids ), _idEndPtr( ids + nbIds ), _mesh( mesh ), _type( type ), _elem( 0 )
6310     {
6311       if ( _idPtr && nbIds && _mesh )
6312         next();
6313     }
6314     IDSourceIterator( const SMDS_Mesh*       mesh,
6315                       SMESH::smIdType_array* idArray,
6316                       SMDSAbs_ElementType    type):
6317       _idPtr( 0 ), _idEndPtr( 0 ), _idArray( idArray), _mesh( mesh ), _type( type ), _elem( 0 )
6318     {
6319       if ( idArray && _mesh )
6320       {
6321         _idPtr    = &_idArray[0];
6322         _idEndPtr = _idPtr + _idArray->length();
6323         next();
6324       }
6325     }
6326     virtual bool more()
6327     {
6328       return _elem;
6329     }
6330     virtual const SMDS_MeshElement* next()
6331     {
6332       const SMDS_MeshElement* res = _elem;
6333       _elem = 0;
6334       while ( _idPtr < _idEndPtr && !_elem )
6335       {
6336         if ( _type == SMDSAbs_Node )
6337         {
6338           _elem = _mesh->FindNode( *_idPtr++ );
6339         }
6340         else if ((_elem = _mesh->FindElement( *_idPtr++ )) &&
6341                  (_elem->GetType() != _type && _type != SMDSAbs_All ))
6342         {
6343           _elem = 0;
6344         }
6345       }
6346       return res;
6347     }
6348   };
6349   //-----------------------------------------------------------------------------
6350
6351   struct NodeOfElemIterator : public SMDS_ElemIterator
6352   {
6353     TColStd_MapOfInteger    _checkedNodeIDs;
6354     SMDS_ElemIteratorPtr    _elemIter;
6355     SMDS_ElemIteratorPtr    _nodeIter;
6356     const SMDS_MeshElement* _node;
6357
6358     NodeOfElemIterator( SMDS_ElemIteratorPtr iter ): _elemIter( iter ), _node( 0 )
6359     {
6360       if ( _elemIter && _elemIter->more() )
6361       {
6362         _nodeIter = _elemIter->next()->nodesIterator();
6363         next();
6364       }
6365     }
6366     virtual bool more()
6367     {
6368       return _node;
6369     }
6370     virtual const SMDS_MeshElement* next()
6371     {
6372       const SMDS_MeshElement* res = _node;
6373       _node = 0;
6374       while ( !_node && ( _elemIter->more() || _nodeIter->more() ))
6375       {
6376         if ( _nodeIter->more() )
6377         {
6378           _node = _nodeIter->next();
6379           if ( !_checkedNodeIDs.Add( _node->GetID() ))
6380             _node = 0;
6381         }
6382         else
6383         {
6384           _nodeIter = _elemIter->next()->nodesIterator();
6385         }
6386       }
6387       return res;
6388     }
6389   };
6390 }
6391
6392 //=============================================================================
6393 /*
6394  * Return iterator on elements of given type in given object
6395  */
6396 //=============================================================================
6397
6398 SMDS_ElemIteratorPtr SMESH_Mesh_i::GetElements(SMESH::SMESH_IDSource_ptr theObject,
6399                                                SMESH::ElementType        theType)
6400 {
6401   SMDS_ElemIteratorPtr  elemIt;
6402   bool                  typeOK = ( theType == SMESH::ALL );
6403   SMDSAbs_ElementType elemType = SMDSAbs_ElementType( theType );
6404
6405   SMESH::SMESH_Mesh_var meshVar = theObject->GetMesh();
6406   SMESH_Mesh_i*          mesh_i = SMESH::DownCast<SMESH_Mesh_i*>( meshVar );
6407   if ( !mesh_i ) return elemIt;
6408   SMESHDS_Mesh*          meshDS = mesh_i->GetImpl().GetMeshDS();
6409
6410   if ( SMESH::DownCast<SMESH_Mesh_i*>( theObject ))
6411   {
6412     elemIt = meshDS->elementsIterator( elemType );
6413     typeOK = true;
6414   }
6415   else if ( SMESH_subMesh_i* submesh_i = SMESH::DownCast<SMESH_subMesh_i*>( theObject ))
6416   {
6417     SMESHDS_SubMesh* sm = ((SMESHDS_Mesh*) meshDS)->MeshElements( submesh_i->GetId() );
6418     if ( sm )
6419     {
6420       elemIt = sm->GetElements();
6421       if ( elemType != SMDSAbs_Node && elemType != SMDSAbs_All )
6422       {
6423         typeOK = ( elemIt && elemIt->more() && elemIt->next()->GetType() == elemType );
6424         elemIt = typeOK ? sm->GetElements() : SMDS_ElemIteratorPtr();
6425       }
6426     }
6427   }
6428   else if ( SMESH_GroupBase_i* group_i = SMESH::DownCast<SMESH_GroupBase_i*>( theObject ))
6429   {
6430     SMESHDS_GroupBase* groupDS = group_i->GetGroupDS();
6431     if ( groupDS && ( elemType == groupDS->GetType()  ||
6432                       elemType == SMDSAbs_Node ||
6433                       elemType == SMDSAbs_All ))
6434     {
6435       elemIt = groupDS->GetElements();
6436       typeOK = ( groupDS->GetType() == elemType || elemType == SMDSAbs_All );
6437     }
6438   }
6439   else if ( SMESH::Filter_i* filter_i = SMESH::DownCast<SMESH::Filter_i*>( theObject ))
6440   {
6441     if ( filter_i->GetElementType() == theType ||
6442          filter_i->GetElementType() == SMESH::ALL ||
6443          elemType == SMDSAbs_Node ||
6444          elemType == SMDSAbs_All)
6445     {
6446       SMESH::Predicate_i* pred_i = filter_i->GetPredicate_i();
6447       if ( pred_i && pred_i->GetPredicate() )
6448       {
6449         SMDSAbs_ElementType filterType = SMDSAbs_ElementType( filter_i->GetElementType() );
6450         SMDS_ElemIteratorPtr allElemIt = meshDS->elementsIterator( filterType );
6451         SMDSAbs_ElementType   iterType = elemType == SMDSAbs_Node ? filterType : elemType;
6452         elemIt = SMDS_ElemIteratorPtr
6453           ( new PredicateIterator( allElemIt, pred_i->GetPredicate(), iterType ));
6454         typeOK = ( elemType == SMDSAbs_Node ? filterType == SMDSAbs_Node : elemIt->more() );
6455       }
6456     }
6457   }
6458   else
6459   {
6460     SMESH::array_of_ElementType_var types = theObject->GetTypes();
6461     const bool                    isNodes = ( types->length() == 1 && types[0] == SMESH::NODE );
6462     if ( isNodes && elemType != SMDSAbs_Node && elemType != SMDSAbs_All )
6463       return elemIt;
6464     SMDSAbs_ElementType iterType = isNodes ? SMDSAbs_Node : elemType;
6465     if ( SMESH_MeshEditor_i::IsTemporaryIDSource( theObject ))
6466     {
6467       SMESH::smIdType nbIds;
6468       if ( SMESH::smIdType* ids = SMESH_MeshEditor_i::GetTemporaryIDs( theObject, nbIds ))
6469         elemIt = SMDS_ElemIteratorPtr( new IDSourceIterator( meshDS, ids, nbIds, iterType ));
6470     }
6471     else
6472     {
6473       SMESH::smIdType_array_var ids = theObject->GetIDs();
6474       elemIt = SMDS_ElemIteratorPtr( new IDSourceIterator( meshDS, ids._retn(), iterType ));
6475     }
6476     typeOK = ( isNodes == ( elemType == SMDSAbs_Node )) || ( elemType == SMDSAbs_All );
6477   }
6478
6479   if ( elemIt && elemIt->more() && !typeOK )
6480   {
6481     if ( elemType == SMDSAbs_Node )
6482     {
6483       elemIt = SMDS_ElemIteratorPtr( new NodeOfElemIterator( elemIt ));
6484     }
6485     else
6486     {
6487       elemIt = SMDS_ElemIteratorPtr();
6488     }
6489   }
6490   return elemIt;
6491 }
6492
6493 //=============================================================================
6494 namespace // Finding concurrent hypotheses
6495 //=============================================================================
6496 {
6497
6498 /*!
6499  * \brief mapping of mesh dimension into shape type
6500  */
6501 TopAbs_ShapeEnum shapeTypeByDim(const int theDim)
6502 {
6503   TopAbs_ShapeEnum aType = TopAbs_SOLID;
6504   switch ( theDim ) {
6505   case 0: aType = TopAbs_VERTEX; break;
6506   case 1: aType = TopAbs_EDGE; break;
6507   case 2: aType = TopAbs_FACE; break;
6508   case 3:
6509   default:aType = TopAbs_SOLID; break;
6510   }
6511   return aType;
6512 }
6513
6514 //-----------------------------------------------------------------------------
6515 /*!
6516  * \brief Internal structure used to find concurrent submeshes
6517  *
6518  * It represents a pair < submesh, concurrent dimension >, where
6519  * 'concurrent dimension' is dimension of shape where the submesh can concurrent
6520  *  with another submesh. In other words, it is dimension of a hypothesis assigned
6521  *  to submesh.
6522  */
6523 class SMESH_DimHyp
6524 {
6525  public:
6526   //! fields
6527   int _dim;    //!< a dimension the algo can build (concurrent dimension)
6528   int _ownDim; //!< dimension of shape of _subMesh (>=_dim)
6529   TopTools_MapOfShape  _shapeMap; //!< [sub-]shapes of dimension == _dim
6530   const SMESH_subMesh* _subMesh;
6531   list<const SMESHDS_Hypothesis*> _hypotheses; //!< algo is first, then its parameters
6532
6533   //-----------------------------------------------------------------------------
6534   // Return the algorithm
6535   const SMESH_Algo* GetAlgo() const
6536   { return _hypotheses.empty() ? 0 : dynamic_cast<const SMESH_Algo*>( _hypotheses.front() ); }
6537
6538   //-----------------------------------------------------------------------------
6539   //! Constructors
6540   SMESH_DimHyp(const SMESH_subMesh* theSubMesh,
6541                const int            theDim,
6542                const TopoDS_Shape&  theShape)
6543   {
6544     _subMesh = theSubMesh;
6545     SetShape( theDim, theShape );
6546   }
6547
6548   //-----------------------------------------------------------------------------
6549   //! set shape
6550   void SetShape(const int           theDim,
6551                 const TopoDS_Shape& theShape)
6552   {
6553     _dim = theDim;
6554     _ownDim = SMESH_Gen::GetShapeDim(theShape);
6555     if (_dim >= _ownDim)
6556       _shapeMap.Add( theShape );
6557     else {
6558       TopExp_Explorer anExp( theShape, shapeTypeByDim(theDim) );
6559       for( ; anExp.More(); anExp.Next() )
6560         _shapeMap.Add( anExp.Current() );
6561     }
6562   }
6563
6564   //-----------------------------------------------------------------------------
6565   //! Check sharing of sub-shapes
6566   static bool isShareSubShapes(const TopTools_MapOfShape& theToCheck,
6567                                const TopTools_MapOfShape& theToFind,
6568                                const TopAbs_ShapeEnum     theType)
6569   {
6570     bool isShared = false;
6571     TopTools_MapIteratorOfMapOfShape anItr( theToCheck );
6572     for (; !isShared && anItr.More(); anItr.Next() )
6573     {
6574       const TopoDS_Shape& aSubSh = anItr.Key();
6575       // check for case when concurrent dimensions are same
6576       isShared = theToFind.Contains( aSubSh );
6577       // check for sub-shape with concurrent dimension
6578       TopExp_Explorer anExp( aSubSh, theType );
6579       for ( ; !isShared && anExp.More(); anExp.Next() )
6580         isShared = theToFind.Contains( anExp.Current() );
6581     }
6582     return isShared;
6583   }
6584
6585   //-----------------------------------------------------------------------------
6586   //! check algorithms
6587   static bool checkAlgo(const SMESHDS_Hypothesis* theA1,
6588                         const SMESHDS_Hypothesis* theA2)
6589   {
6590     if ( !theA1 || !theA2 ||
6591          theA1->GetType() == SMESHDS_Hypothesis::PARAM_ALGO ||
6592          theA2->GetType() == SMESHDS_Hypothesis::PARAM_ALGO )
6593       return false; // one of the hypothesis is not algorithm
6594     // check algorithm names (should be equal)
6595     return strcmp( theA1->GetName(), theA2->GetName() ) == 0;
6596   }
6597
6598
6599   //-----------------------------------------------------------------------------
6600   //! Check if sub-shape hypotheses are concurrent
6601   bool IsConcurrent(const SMESH_DimHyp* theOther) const
6602   {
6603     if ( _subMesh == theOther->_subMesh )
6604       return false; // same sub-shape - should not be
6605
6606     // if ( <own dim of either of submeshes> == <concurrent dim> &&
6607     //      any of the two submeshes is not on COMPOUND shape )
6608     //  -> no concurrency
6609     bool meIsCompound    = (_subMesh->GetSubMeshDS() &&
6610                             _subMesh->GetSubMeshDS()->IsComplexSubmesh());
6611     bool otherIsCompound = (theOther->_subMesh->GetSubMeshDS() &&
6612                             theOther->_subMesh->GetSubMeshDS()->IsComplexSubmesh());
6613     if ( (_ownDim == _dim  || theOther->_ownDim == _dim ) && (!meIsCompound || !otherIsCompound))
6614       return false;
6615
6616     bool checkSubShape = isShareSubShapes( _shapeMap, theOther->_shapeMap, shapeTypeByDim(_dim));
6617     if ( !checkSubShape )
6618       return false;
6619
6620     // check algorithms to be same
6621     const SMESH_Algo* a1 = this->GetAlgo();
6622     const SMESH_Algo* a2 = theOther->GetAlgo();
6623     bool isSame = checkAlgo( a1, a2 );
6624     if ( !isSame )
6625     {
6626       return true;
6627       // commented off for IPAL54678
6628       // if ( !a1 || !a2 )
6629       //   return false; // pb?
6630       // return a1->GetDim() == a2->GetDim(); // different algorithms of same dim -> concurrency !
6631     }
6632
6633     // check hypothesises for concurrence (skip first as algorithm)
6634     size_t nbSame = 0;
6635     // pointers should be same, because it is referened from mesh hypothesis partition
6636     list <const SMESHDS_Hypothesis*>::const_iterator hypIt = _hypotheses.begin();
6637     list <const SMESHDS_Hypothesis*>::const_iterator otheEndIt = theOther->_hypotheses.end();
6638     for ( hypIt++ /*skip first as algo*/; hypIt != _hypotheses.end(); hypIt++ )
6639       if ( find( theOther->_hypotheses.begin(), otheEndIt, *hypIt ) != otheEndIt )
6640         nbSame++;
6641     // the submeshes are concurrent if their algorithms has different parameters
6642     return nbSame != theOther->_hypotheses.size() - 1;
6643   }
6644
6645   // Return true if algorithm of this SMESH_DimHyp is used if no
6646   // sub-mesh order is imposed by the user
6647   bool IsHigherPriorityThan( const SMESH_DimHyp* theOther ) const
6648   {
6649     // NeedDiscreteBoundary() algo has a higher priority
6650     if ( this    ->GetAlgo()->NeedDiscreteBoundary() !=
6651          theOther->GetAlgo()->NeedDiscreteBoundary() )
6652       return !this->GetAlgo()->NeedDiscreteBoundary();
6653
6654     return ( this->_subMesh->GetId() < theOther->_subMesh->GetId() );
6655   }
6656
6657 }; // end of SMESH_DimHyp
6658 //-----------------------------------------------------------------------------
6659
6660 typedef list<const SMESH_DimHyp*> TDimHypList;
6661
6662 //-----------------------------------------------------------------------------
6663
6664 void addDimHypInstance(const int                               theDim,
6665                        const TopoDS_Shape&                     theShape,
6666                        const SMESH_Algo*                       theAlgo,
6667                        const SMESH_subMesh*                    theSubMesh,
6668                        const list <const SMESHDS_Hypothesis*>& theHypList,
6669                        TDimHypList*                            theDimHypListArr )
6670 {
6671   if ( !theAlgo->NeedDiscreteBoundary() &&
6672        theAlgo->NeedLowerHyps( theDim )) // IPAL54678
6673     return;
6674   TDimHypList& listOfdimHyp = theDimHypListArr[theDim];
6675   if ( listOfdimHyp.empty() || listOfdimHyp.back()->_subMesh != theSubMesh )
6676   {
6677     SMESH_DimHyp* dimHyp = new SMESH_DimHyp( theSubMesh, theDim, theShape );
6678     dimHyp->_hypotheses.push_front(theAlgo);
6679     listOfdimHyp.push_back( dimHyp );
6680   }
6681
6682   SMESH_DimHyp* dimHyp = const_cast<SMESH_DimHyp*>( listOfdimHyp.back() );
6683   dimHyp->_hypotheses.insert( dimHyp->_hypotheses.end(),
6684                               theHypList.begin(), theHypList.end() );
6685 }
6686
6687 //-----------------------------------------------------------------------------
6688 void addInOrderOfPriority( const SMESH_DimHyp* theDimHyp,
6689                            TDimHypList&        theListOfConcurr)
6690 {
6691   if ( theListOfConcurr.empty() )
6692   {
6693     theListOfConcurr.push_back( theDimHyp );
6694   }
6695   else
6696   {
6697     TDimHypList::iterator hypIt = theListOfConcurr.begin();
6698     while ( hypIt != theListOfConcurr.end() &&
6699             !theDimHyp->IsHigherPriorityThan( *hypIt ))
6700       ++hypIt;
6701     theListOfConcurr.insert( hypIt, theDimHyp );
6702   }
6703 }
6704
6705 //-----------------------------------------------------------------------------
6706 void findConcurrents(const SMESH_DimHyp* theDimHyp,
6707                      const TDimHypList&  theListOfDimHyp,
6708                      TDimHypList&        theListOfConcurrHyp,
6709                      set<int>&           theSetOfConcurrId )
6710 {
6711   TDimHypList::const_reverse_iterator rIt = theListOfDimHyp.rbegin();
6712   for ( ; rIt != theListOfDimHyp.rend(); rIt++ )
6713   {
6714     const SMESH_DimHyp* curDimHyp = *rIt;
6715     if ( curDimHyp == theDimHyp )
6716       break; // meet own dimHyp pointer in same dimension
6717
6718     if ( theDimHyp->IsConcurrent( curDimHyp ) &&
6719          theSetOfConcurrId.insert( curDimHyp->_subMesh->GetId() ).second )
6720     {
6721       addInOrderOfPriority( curDimHyp, theListOfConcurrHyp );
6722     }
6723   }
6724 }
6725
6726 //-----------------------------------------------------------------------------
6727 bool unionLists(TListOfInt&       theListOfId,
6728                 TListOfListOfInt& theListOfListOfId,
6729                 const int         theIndx )
6730 {
6731   bool changed = false;
6732   if ( theListOfId.empty() )
6733     return changed;
6734   TListOfListOfInt::iterator it = theListOfListOfId.begin();
6735   for ( int i = 0; it != theListOfListOfId.end(); it++, i++ )
6736   {
6737     if ( i < theIndx )
6738       continue; //skip already treated lists
6739     // check if other list has any same submesh object
6740     TListOfInt& otherListOfId = *it;
6741     if ( find_first_of( theListOfId.begin(), theListOfId.end(),
6742                         otherListOfId.begin(), otherListOfId.end() ) == theListOfId.end() )
6743       continue;
6744
6745     // union two lists (from source into target)
6746     TListOfInt::iterator it2 = otherListOfId.begin();
6747     for ( ; it2 != otherListOfId.end(); it2++ ) {
6748       if ( find( theListOfId.begin(), theListOfId.end(), (*it2) ) == theListOfId.end() )
6749       {
6750         theListOfId.push_back(*it2);
6751         changed = true;
6752       }
6753     }
6754     // clear source list
6755     otherListOfId.clear();
6756   }
6757   return changed;
6758 }
6759 //-----------------------------------------------------------------------------
6760
6761 //! free memory allocated for dimension-hypothesis objects
6762 void removeDimHyps( TDimHypList* theArrOfList )
6763 {
6764   for (int i = 0; i < 4; i++ ) {
6765     TDimHypList& listOfdimHyp = theArrOfList[i];
6766     TDimHypList::const_iterator it = listOfdimHyp.begin();
6767     for ( ; it != listOfdimHyp.end(); it++ )
6768       delete (*it);
6769   }
6770 }
6771
6772 //-----------------------------------------------------------------------------
6773 /*!
6774  * \brief find common submeshes with given submesh
6775  * \param theSubMeshList list of already collected submesh to check
6776  * \param theSubMesh given submesh to intersect with other
6777  * \param theCommonSubMeshes collected common submeshes
6778  */
6779 void findCommonSubMesh (list<const SMESH_subMesh*>& theSubMeshList,
6780                         const SMESH_subMesh*        theSubMesh,
6781                         set<const SMESH_subMesh*>&  theCommon )
6782 {
6783   if ( !theSubMesh )
6784     return;
6785   list<const SMESH_subMesh*>::const_iterator it = theSubMeshList.begin();
6786   for ( ; it != theSubMeshList.end(); it++ )
6787     theSubMesh->FindIntersection( *it, theCommon );
6788   theSubMeshList.push_back( theSubMesh );
6789   //theCommon.insert( theSubMesh );
6790 }
6791
6792 //-----------------------------------------------------------------------------
6793 bool isSubMeshInList ( int smID, const TListOfListOfInt& smLists )
6794 {
6795   TListOfListOfInt::const_iterator listsIt = smLists.begin();
6796   for ( ; listsIt != smLists.end(); ++listsIt )
6797   {
6798     const TListOfInt& smIDs = *listsIt;
6799     if ( std::find( smIDs.begin(), smIDs.end(), smID ) != smIDs.end() )
6800       return true;
6801   }
6802   return false;
6803 }
6804
6805 } // namespace
6806
6807 //=============================================================================
6808 /*!
6809  * \brief Return \c true if a meshing order not yet set for a concurrent sub-mesh
6810  */
6811 //=============================================================================
6812
6813 CORBA::Boolean SMESH_Mesh_i::IsUnorderedSubMesh(CORBA::Long submeshID)
6814 {
6815   TListOfListOfInt anOrder = GetImpl().GetMeshOrder(); // already defined order
6816   if ( isSubMeshInList( submeshID, anOrder ))
6817     return false;
6818
6819   TListOfListOfInt allConurrent = findConcurrentSubMeshes();
6820   return isSubMeshInList( submeshID, allConurrent );
6821 }
6822
6823 //=============================================================================
6824 /*!
6825  * \brief Return sub-mesh objects list in meshing order
6826  */
6827 //=============================================================================
6828
6829 SMESH::submesh_array_array* SMESH_Mesh_i::GetMeshOrder()
6830 {
6831   SMESH::submesh_array_array_var aResult = new SMESH::submesh_array_array();
6832
6833   SMESHDS_Mesh* aMeshDS = _impl->GetMeshDS();
6834   if ( !aMeshDS )
6835     return aResult._retn();
6836
6837   TListOfListOfInt      anOrder = GetImpl().GetMeshOrder(); // already defined order
6838   TListOfListOfInt allConurrent = findConcurrentSubMeshes();
6839   anOrder.splice( anOrder.end(), allConurrent );
6840
6841   bool changed;
6842   do {
6843     changed = false;
6844     TListOfListOfInt::iterator listIt = anOrder.begin();
6845     for ( int listIndx = 1; listIt != anOrder.end(); listIt++, listIndx++ )
6846       if ( unionLists( *listIt,  anOrder, listIndx ))
6847         changed = true;
6848   }
6849   while ( changed );
6850
6851   // convert submesh ids into interface instances
6852   //  and dump command into python
6853   convertMeshOrder( anOrder, aResult, false );
6854
6855   return aResult._retn();
6856 }
6857
6858 //=============================================================================
6859 /*!
6860  * \brief Finds concurrent sub-meshes
6861  */
6862 //=============================================================================
6863
6864 TListOfListOfInt SMESH_Mesh_i::findConcurrentSubMeshes()
6865 {
6866   TListOfListOfInt anOrder;
6867   ::SMESH_Mesh& mesh = GetImpl();
6868
6869   // collect submeshes and detect concurrent algorithms and hypothesises
6870   TDimHypList dimHypListArr[4]; // dimHyp list for each shape dimension
6871
6872   map<int, ::SMESH_subMesh*>::iterator i_sm = _mapSubMesh.begin();
6873   for ( ; i_sm != _mapSubMesh.end(); i_sm++ )
6874   {
6875     ::SMESH_subMesh* sm = (*i_sm).second;
6876     // shape of submesh
6877     const TopoDS_Shape& aSubMeshShape = sm->GetSubShape();
6878
6879     // list of assigned hypothesises
6880     const list <const SMESHDS_Hypothesis*>& hypList = mesh.GetHypothesisList(aSubMeshShape);
6881     // Find out dimensions where the submesh can be concurrent.
6882     // We define the dimensions by algo of each of hypotheses in hypList
6883     list <const SMESHDS_Hypothesis*>::const_iterator hypIt = hypList.begin();
6884     for( ; hypIt != hypList.end(); hypIt++ )
6885     {
6886       SMESH_Algo* anAlgo = 0;
6887       const SMESH_Hypothesis* hyp = dynamic_cast<const SMESH_Hypothesis*>(*hypIt);
6888       if ( hyp->GetType() != SMESHDS_Hypothesis::PARAM_ALGO )
6889         // hyp it-self is algo
6890         anAlgo = (SMESH_Algo*)dynamic_cast<const SMESH_Algo*>(hyp);
6891       else {
6892         // try to find algorithm with help of sub-shapes
6893         TopExp_Explorer anExp( aSubMeshShape, shapeTypeByDim(hyp->GetDim()) );
6894         for ( ; !anAlgo && anExp.More(); anExp.Next() )
6895           anAlgo = mesh.GetGen()->GetAlgo( mesh, anExp.Current() );
6896       }
6897       if (!anAlgo)
6898         continue; // no algorithm assigned to a current submesh
6899
6900       int dim = anAlgo->GetDim(); // top concurrent dimension (see comment to SMESH_DimHyp)
6901       // the submesh can concurrent at <dim> (or lower dims if !anAlgo->NeedDiscreteBoundary()
6902       // and !anAlgo->NeedLowerHyps( dim ))
6903
6904       // create instance of dimension-hypothesis for found concurrent dimension(s) and algorithm
6905       for ( int j = anAlgo->NeedDiscreteBoundary() ? dim : 1, jn = dim; j <= jn; j++ )
6906         addDimHypInstance( j, aSubMeshShape, anAlgo, sm, hypList, dimHypListArr );
6907     }
6908   } // end iterations on submesh
6909
6910     // iterate on created dimension-hypotheses and check for concurrents
6911   for ( int i = 0; i < 4; i++ )
6912   {
6913     const TDimHypList& listOfDimHyp = dimHypListArr[i];
6914     // check for concurrents in own and other dimensions (step-by-step)
6915     TDimHypList::const_iterator dhIt = listOfDimHyp.begin();
6916     for ( ; dhIt != listOfDimHyp.end(); dhIt++ )
6917     {
6918       const SMESH_DimHyp* dimHyp = *dhIt;
6919       TDimHypList listOfConcurr;
6920       set<int>    setOfConcurrIds;
6921       // looking for concurrents and collect into own list
6922       for ( int j = i; j < 4; j++ )
6923         findConcurrents( dimHyp, dimHypListArr[j], listOfConcurr, setOfConcurrIds );
6924       // check if any concurrents found
6925       if ( listOfConcurr.size() > 0 )
6926       {
6927         // add own submesh to list of concurrent
6928         addInOrderOfPriority( dimHyp, listOfConcurr );
6929         list<int> listOfConcurrIds;
6930         TDimHypList::iterator hypIt = listOfConcurr.begin();
6931         for ( ; hypIt != listOfConcurr.end(); ++hypIt )
6932           listOfConcurrIds.push_back( (*hypIt)->_subMesh->GetId() );
6933         anOrder.push_back( listOfConcurrIds );
6934       }
6935     }
6936   }
6937
6938   removeDimHyps(dimHypListArr);
6939
6940   // now, minimize the number of concurrent groups
6941   // Here we assume that lists of submeshes can have same submesh
6942   // in case of multi-dimension algorithms, as result
6943   //  list with common submesh has to be united into one list
6944   int listIndx = 0;
6945   TListOfListOfInt::iterator listIt = anOrder.begin();
6946   for(; listIt != anOrder.end(); listIt++, listIndx++ )
6947     unionLists( *listIt,  anOrder, listIndx + 1 );
6948
6949   return anOrder;
6950 }
6951
6952 //=============================================================================
6953 /*!
6954  * \brief Set submesh object order
6955  * \param theSubMeshArray submesh array order
6956  */
6957 //=============================================================================
6958
6959 ::CORBA::Boolean SMESH_Mesh_i::SetMeshOrder(const SMESH::submesh_array_array& theSubMeshArray)
6960 {
6961   if ( _preMeshInfo )
6962     _preMeshInfo->ForgetOrLoad();
6963
6964   bool res = false;
6965   ::SMESH_Mesh& mesh = GetImpl();
6966
6967   TPythonDump aPythonDump; // prevent dump of called methods
6968   aPythonDump << "isDone = " << SMESH::SMESH_Mesh_var(_this()) << ".SetMeshOrder( [ ";
6969
6970   TListOfListOfInt subMeshOrder;
6971   for ( int i = 0, n = theSubMeshArray.length(); i < n; i++ )
6972   {
6973     const SMESH::submesh_array& aSMArray = theSubMeshArray[i];
6974     TListOfInt subMeshIds;
6975     if ( i > 0 )
6976       aPythonDump << ", ";
6977     aPythonDump << "[ ";
6978     // Collect subMeshes which should be clear
6979     //  do it list-by-list, because modification of submesh order
6980     //  take effect between concurrent submeshes only
6981     set<const SMESH_subMesh*> subMeshToClear;
6982     list<const SMESH_subMesh*> subMeshList;
6983     for ( int j = 0, jn = aSMArray.length(); j < jn; j++ )
6984     {
6985       const SMESH::SMESH_subMesh_var subMesh = SMESH::SMESH_subMesh::_duplicate(aSMArray[j]);
6986       if ( j > 0 )
6987         aPythonDump << ", ";
6988       aPythonDump << subMesh;
6989       subMeshIds.push_back( subMesh->GetId() );
6990       // detect common parts of submeshes
6991       if ( _mapSubMesh.find(subMesh->GetId()) != _mapSubMesh.end() )
6992         findCommonSubMesh( subMeshList, _mapSubMesh[ subMesh->GetId() ], subMeshToClear );
6993     }
6994     aPythonDump << " ]";
6995     subMeshOrder.push_back( subMeshIds );
6996
6997     // clear collected sub-meshes
6998     set<const SMESH_subMesh*>::iterator clrIt = subMeshToClear.begin();
6999     for ( ; clrIt != subMeshToClear.end(); clrIt++ )
7000       if ( SMESH_subMesh* sm = (SMESH_subMesh*)*clrIt )
7001       {
7002         sm->ComputeStateEngine( SMESH_subMesh::CLEAN );
7003         if ( SMESH_Algo* algo = sm->GetAlgo() ) // #16748
7004           sm->AlgoStateEngine( SMESH_subMesh::MODIF_HYP, algo ); // to clear a cached algo
7005       }
7006   }
7007   aPythonDump << " ])";
7008
7009   mesh.SetMeshOrder( subMeshOrder );
7010   res = true;
7011
7012   SMESH::SMESH_Mesh_var me = _this();
7013   _gen_i->UpdateIcons( me );
7014
7015   return res;
7016 }
7017
7018 //=============================================================================
7019 /*!
7020  * \brief Convert submesh ids into submesh interfaces
7021  */
7022 //=============================================================================
7023
7024 void SMESH_Mesh_i::convertMeshOrder (const TListOfListOfInt&     theIdsOrder,
7025                                      SMESH::submesh_array_array& theResOrder,
7026                                      const bool                  theIsDump)
7027 {
7028   int nbSet = theIdsOrder.size();
7029   TPythonDump aPythonDump; // prevent dump of called methods
7030   if ( theIsDump )
7031     aPythonDump << "[ ";
7032   theResOrder.length(nbSet);
7033   TListOfListOfInt::const_iterator it = theIdsOrder.begin();
7034   int listIndx = 0;
7035   for( ; it != theIdsOrder.end(); it++ )
7036   {
7037     // translate submesh identificators into submesh objects
7038     //  takeing into account real number of concurrent lists
7039     const TListOfInt& aSubOrder = (*it);
7040     if (!aSubOrder.size())
7041       continue;
7042     if ( theIsDump )
7043       aPythonDump << "[ ";
7044     // convert shape indices into interfaces
7045     SMESH::submesh_array_var aResSubSet = new SMESH::submesh_array();
7046     aResSubSet->length(aSubOrder.size());
7047     TListOfInt::const_iterator subIt = aSubOrder.begin();
7048     int j;
7049     for( j = 0; subIt != aSubOrder.end(); subIt++ )
7050     {
7051       if ( _mapSubMeshIor.find(*subIt) == _mapSubMeshIor.end() )
7052         continue;
7053       SMESH::SMESH_subMesh_var subMesh =
7054         SMESH::SMESH_subMesh::_duplicate( _mapSubMeshIor[*subIt] );
7055       if ( theIsDump ) {
7056         if ( j > 0 )
7057           aPythonDump << ", ";
7058         aPythonDump << subMesh;
7059       }
7060       aResSubSet[ j++ ] = subMesh;
7061     }
7062     if ( theIsDump )
7063       aPythonDump << " ]";
7064     if ( j > 1 )
7065       theResOrder[ listIndx++ ] = aResSubSet;
7066   }
7067   // correct number of lists
7068   theResOrder.length( listIndx );
7069
7070   if ( theIsDump ) {
7071     // finilise python dump
7072     aPythonDump << " ]";
7073     aPythonDump << " = " << SMESH::SMESH_Mesh_var(_this()) << ".GetMeshOrder()";
7074   }
7075 }
7076
7077 namespace // utils used by SMESH_MeshPartDS
7078 {
7079   /*!
7080    * \brief Class used to access to protected data of SMDS_MeshInfo
7081    */
7082   struct TMeshInfo : public SMDS_MeshInfo
7083   {
7084     void Add(const SMDS_MeshElement* e) { SMDS_MeshInfo::addWithPoly( e ); }
7085   };
7086   /*!
7087    * \brief Element holing its ID only
7088    */
7089   struct TElemID : public SMDS_LinearEdge
7090   {
7091     TElemID(int ID) : SMDS_LinearEdge(0,0) { setID( ID ); }
7092   };
7093 }
7094
7095 //================================================================================
7096 //
7097 // Implementation of SMESH_MeshPartDS
7098 //
7099 SMESH_MeshPartDS::SMESH_MeshPartDS(SMESH::SMESH_IDSource_ptr meshPart):
7100   SMESHDS_Mesh( /*meshID=*/-1, /*isEmbeddedMode=*/true)
7101 {
7102   SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
7103   SMESH_Mesh_i*       mesh_i = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
7104
7105   mesh_i->Load();
7106   _meshDS = mesh_i->GetImpl().GetMeshDS();
7107
7108   SetPersistentId( _meshDS->GetPersistentId() );
7109
7110   if ( mesh_i == SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
7111   {
7112     // <meshPart> is the whole mesh
7113     myInfo = _meshDS->GetMeshInfo(); // copy mesh info;
7114     // copy groups
7115     set<SMESHDS_GroupBase*>& myGroupSet = const_cast<set<SMESHDS_GroupBase*>&>( GetGroups() );
7116     myGroupSet = _meshDS->GetGroups();
7117   }
7118   else
7119   {
7120     TMeshInfo tmpInfo;
7121     SMESH::smIdType_array_var       anIDs = meshPart->GetIDs();
7122     SMESH::array_of_ElementType_var types = meshPart->GetTypes();
7123     if ( types->length() == 1 && types[0] == SMESH::NODE ) // group of nodes
7124     {
7125       for ( CORBA::ULong i=0; i < anIDs->length(); i++ )
7126         if ( const SMDS_MeshNode * n = _meshDS->FindNode( anIDs[i] ))
7127           if ( _elements[ SMDSAbs_Node ].insert( n ).second )
7128             tmpInfo.Add( n );
7129     }
7130     else
7131     {
7132       for ( CORBA::ULong i=0; i < anIDs->length(); i++ )
7133         if ( const SMDS_MeshElement * e = _meshDS->FindElement(anIDs[i]))
7134           if ( _elements[ e->GetType() ].insert( e ).second )
7135           {
7136             tmpInfo.Add( e );
7137             SMDS_ElemIteratorPtr nIt = e->nodesIterator();
7138             while ( nIt->more() )
7139             {
7140               const SMDS_MeshNode * n = (const SMDS_MeshNode*) nIt->next();
7141               if ( _elements[ SMDSAbs_Node ].insert( n ).second )
7142                 tmpInfo.Add( n );
7143             }
7144           }
7145     }
7146     myInfo = tmpInfo;
7147
7148     ShapeToMesh( _meshDS->ShapeToMesh() );
7149
7150     _meshDS = 0; // to enforce iteration on _elements and _nodes
7151   }
7152 }
7153 // -------------------------------------------------------------------------------------
7154 SMESH_MeshPartDS::SMESH_MeshPartDS(const std::list< const SMDS_MeshElement* > & meshPart):
7155   SMESHDS_Mesh( /*meshID=*/-1, /*isEmbeddedMode=*/true), _meshDS(0)
7156 {
7157   TMeshInfo tmpInfo;
7158   list< const SMDS_MeshElement* >::const_iterator partIt = meshPart.begin();
7159   for ( ; partIt != meshPart.end(); ++partIt )
7160     if ( const SMDS_MeshElement * e = *partIt )
7161       if ( _elements[ e->GetType() ].insert( e ).second )
7162       {
7163         tmpInfo.Add( e );
7164         SMDS_ElemIteratorPtr nIt = e->nodesIterator();
7165         while ( nIt->more() )
7166         {
7167           const SMDS_MeshNode * n = (const SMDS_MeshNode*) nIt->next();
7168           if ( _elements[ SMDSAbs_Node ].insert( n ).second )
7169             tmpInfo.Add( n );
7170         }
7171       }
7172   myInfo = tmpInfo;
7173 }
7174 // -------------------------------------------------------------------------------------
7175 const SMDS_MeshElement * SMESH_MeshPartDS::FindElement(int IDelem) const
7176 {
7177   if ( _meshDS ) return _meshDS->FindElement( IDelem );
7178
7179   TElemID elem( IDelem );
7180   for ( int iType = SMDSAbs_Edge; iType < SMDSAbs_NbElementTypes; ++iType )
7181     if ( !_elements[ iType ].empty() )
7182     {
7183       TIDSortedElemSet::const_iterator it = _elements[ iType ].find( &elem );
7184       if ( it != _elements[ iType ].end() )
7185         return *it;
7186     }
7187   return 0;
7188 }
7189 // -------------------------------------------------------------------------------------
7190 bool SMESH_MeshPartDS::HasNumerationHoles()
7191 {
7192   if ( _meshDS ) return _meshDS->HasNumerationHoles();
7193
7194   return ( MinNodeID() != 1 ||
7195            MaxNodeID() != NbNodes() ||
7196            MinElementID() != 1 ||
7197            MaxElementID() != NbElements() );
7198 }
7199 // -------------------------------------------------------------------------------------
7200 smIdType SMESH_MeshPartDS::MaxNodeID() const
7201 {
7202   if ( _meshDS ) return _meshDS->MaxNodeID();
7203   return NbNodes() == 0 ? 0 : (*_elements[ SMDSAbs_Node ].rbegin())->GetID();
7204 }
7205 // -------------------------------------------------------------------------------------
7206 smIdType SMESH_MeshPartDS::MinNodeID() const
7207 {
7208   if ( _meshDS ) return _meshDS->MinNodeID();
7209   return NbNodes() == 0 ? 0 : (*_elements[ SMDSAbs_Node ].begin())->GetID();
7210 }  
7211 // -------------------------------------------------------------------------------------
7212 smIdType SMESH_MeshPartDS::MaxElementID() const
7213 {
7214   if ( _meshDS ) return _meshDS->MaxElementID();
7215   smIdType maxID = 0;
7216   for ( int iType = SMDSAbs_Edge; iType < SMDSAbs_NbElementTypes; ++iType )
7217     if ( !_elements[ iType ].empty() )
7218       maxID = std::max( maxID, (*_elements[ iType ].rbegin())->GetID() );
7219   return maxID;
7220 }
7221 // -------------------------------------------------------------------------------------
7222 smIdType SMESH_MeshPartDS::MinElementID() const
7223 {
7224   if ( _meshDS ) return _meshDS->MinElementID();
7225   smIdType minID = 0;
7226   for ( int iType = SMDSAbs_Edge; iType < SMDSAbs_NbElementTypes; ++iType )
7227     if ( !_elements[ iType ].empty() )
7228       minID = std::min( minID, (*_elements[ iType ].begin())->GetID() );
7229   return minID;
7230 }
7231 // -------------------------------------------------------------------------------------
7232 SMDS_ElemIteratorPtr SMESH_MeshPartDS::elementGeomIterator(SMDSAbs_GeometryType geomType) const
7233 {
7234   if ( _meshDS ) return _meshDS->elementGeomIterator( geomType );
7235
7236   typedef SMDS_SetIterator
7237     <const SMDS_MeshElement*,
7238     TIDSortedElemSet::const_iterator,
7239     SMDS::SimpleAccessor<const SMDS_MeshElement*, TIDSortedElemSet::const_iterator>,
7240     SMDS_MeshElement::GeomFilter
7241     > TIter;
7242
7243   SMDSAbs_ElementType type = SMDS_MeshCell::ElemType( geomType );
7244
7245   return SMDS_ElemIteratorPtr( new TIter( _elements[type].begin(),
7246                                           _elements[type].end(),
7247                                           SMDS_MeshElement::GeomFilter( geomType )));
7248 }
7249 // -------------------------------------------------------------------------------------
7250 SMDS_ElemIteratorPtr SMESH_MeshPartDS::elementEntityIterator(SMDSAbs_EntityType entity) const
7251 {
7252   if ( _meshDS ) return _meshDS->elementEntityIterator( entity );
7253
7254   typedef SMDS_SetIterator
7255     <const SMDS_MeshElement*,
7256     TIDSortedElemSet::const_iterator,
7257     SMDS::SimpleAccessor<const SMDS_MeshElement*, TIDSortedElemSet::const_iterator>,
7258     SMDS_MeshElement::EntityFilter
7259     > TIter;
7260
7261   SMDSAbs_ElementType type = SMDS_MeshCell::ElemType( entity );
7262
7263   return SMDS_ElemIteratorPtr( new TIter( _elements[type].begin(),
7264                                           _elements[type].end(),
7265                                           SMDS_MeshElement::EntityFilter( entity )));
7266 }
7267 // -------------------------------------------------------------------------------------
7268 SMDS_ElemIteratorPtr SMESH_MeshPartDS::elementsIterator(SMDSAbs_ElementType type) const
7269 {
7270   typedef SMDS_SetIterator<const SMDS_MeshElement*, TIDSortedElemSet::const_iterator > TIter;
7271   if ( type == SMDSAbs_All && !_meshDS )
7272   {
7273     typedef vector< SMDS_ElemIteratorPtr > TIterVec;
7274     TIterVec iterVec;
7275     for ( int i = 0; i < SMDSAbs_NbElementTypes; ++i )
7276       if ( !_elements[i].empty() && i != SMDSAbs_Node )
7277         iterVec.push_back
7278           ( SMDS_ElemIteratorPtr( new TIter( _elements[i].begin(), _elements[i].end() )));
7279
7280     typedef SMDS_IteratorOnIterators<const SMDS_MeshElement*, TIterVec > TIterOnIters;
7281     return SMDS_ElemIteratorPtr( new TIterOnIters( iterVec ));
7282   }
7283   return _meshDS ? _meshDS->elementsIterator(type) : SMDS_ElemIteratorPtr
7284       ( new TIter( _elements[type].begin(), _elements[type].end() ));
7285 }
7286 // -------------------------------------------------------------------------------------
7287 #define _GET_ITER_DEFINE( iterType, methName, elem, elemType)                       \
7288   iterType SMESH_MeshPartDS::methName() const                 \
7289   {                                                                                 \
7290     typedef SMDS_SetIterator<const elem*, TIDSortedElemSet::const_iterator > TIter; \
7291     return _meshDS ? _meshDS->methName() : iterType                 \
7292       ( new TIter( _elements[elemType].begin(), _elements[elemType].end() ));       \
7293   }
7294 // -------------------------------------------------------------------------------------
7295 _GET_ITER_DEFINE( SMDS_NodeIteratorPtr, nodesIterator, SMDS_MeshNode, SMDSAbs_Node )
7296 _GET_ITER_DEFINE( SMDS_EdgeIteratorPtr, edgesIterator, SMDS_MeshEdge, SMDSAbs_Edge )
7297 _GET_ITER_DEFINE( SMDS_FaceIteratorPtr, facesIterator, SMDS_MeshFace, SMDSAbs_Face )
7298 _GET_ITER_DEFINE( SMDS_VolumeIteratorPtr, volumesIterator, SMDS_MeshVolume, SMDSAbs_Volume)
7299 #undef _GET_ITER_DEFINE
7300 //
7301 // END Implementation of SMESH_MeshPartDS
7302 //
7303 //================================================================================