Salome HOME
Implementation of NPAL13504 improvement.
[modules/smesh.git] / src / SMESH_I / SMESH_Mesh_i.cxx
1 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 //  File   : SMESH_Mesh_i.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SMESH
27 //  $Header$
28
29 #include "SMESH_Mesh_i.hxx"
30 #include "SMESH_subMesh_i.hxx"
31 #include "SMESH_MEDMesh_i.hxx"
32 #include "SMESH_Group_i.hxx"
33 #include "SMESH_Filter_i.hxx"
34 #include "SMESH_PythonDump.hxx"
35
36 #include "Utils_CorbaException.hxx"
37 #include "Utils_ExceptHandlers.hxx"
38 #include "utilities.h"
39
40 #include "SALOME_NamingService.hxx"
41 #include "Utils_SINGLETON.hxx"
42 #include "OpUtil.hxx"
43
44 #include "SMESHDS_Command.hxx"
45 #include "SMESHDS_CommandType.hxx"
46 #include "SMESH_MeshEditor_i.hxx"
47 #include "SMESH_Gen_i.hxx"
48 #include "DriverMED_R_SMESHDS_Mesh.h"
49 //#include "SMDS_ElemIterator.hxx"
50 #include "SMDS_VolumeTool.hxx"
51 #include "SMESH_MesherHelper.hxx"
52 #include "SMESH_MeshEditor.hxx"
53
54 // OCCT Includes
55 #include <BRep_Builder.hxx>
56 #include <OSD_Path.hxx>
57 #include <OSD_File.hxx>
58 #include <OSD_Directory.hxx>
59 #include <OSD_Protection.hxx>
60 #include <TColStd_MapOfInteger.hxx>
61 #include <TColStd_MapIteratorOfMapOfInteger.hxx>
62 #include <TColStd_SequenceOfInteger.hxx>
63 #include <TCollection_AsciiString.hxx>
64 #include <TopoDS_Compound.hxx>
65
66 // STL Includes
67 #include <string>
68 #include <iostream>
69 #include <sstream>
70
71 #ifdef _DEBUG_
72 static int MYDEBUG = 0;
73 #else
74 static int MYDEBUG = 0;
75 #endif
76
77 using namespace std;
78 using SMESH::TPythonDump;
79
80 int SMESH_Mesh_i::myIdGenerator = 0;
81
82
83
84 //=============================================================================
85 /*!
86  *  Constructor
87  */
88 //=============================================================================
89
90 SMESH_Mesh_i::SMESH_Mesh_i( PortableServer::POA_ptr thePOA,
91                             SMESH_Gen_i*            gen_i,
92                             CORBA::Long studyId )
93 : SALOME::GenericObj_i( thePOA )
94 {
95   MESSAGE("SMESH_Mesh_i");
96   _impl = NULL;
97   _gen_i = gen_i;
98   _id = myIdGenerator++;
99   _studyId = studyId;
100 }
101
102 //=============================================================================
103 /*!
104  *  Destructor
105  */
106 //=============================================================================
107
108 SMESH_Mesh_i::~SMESH_Mesh_i()
109 {
110   INFOS("~SMESH_Mesh_i");
111   map<int, SMESH::SMESH_GroupBase_ptr>::iterator it;
112   for ( it = _mapGroups.begin(); it != _mapGroups.end(); it++ ) {
113     SMESH_GroupBase_i* aGroup = dynamic_cast<SMESH_GroupBase_i*>( SMESH_Gen_i::GetServant( it->second ).in() );
114     if ( aGroup ) {
115
116       // this method is colled from destructor of group (PAL6331)
117       //_impl->RemoveGroup( aGroup->GetLocalID() );
118
119       aGroup->Destroy();
120     }
121   }
122   _mapGroups.clear();
123 }
124
125 //=============================================================================
126 /*!
127  *  SetShape
128  *
129  *  Associates <this> mesh with <theShape> and puts a reference
130  *  to <theShape> into the current study;
131  *  the previous shape is substituted by the new one.
132  */
133 //=============================================================================
134
135 void SMESH_Mesh_i::SetShape( GEOM::GEOM_Object_ptr theShapeObject )
136     throw (SALOME::SALOME_Exception)
137 {
138   Unexpect aCatch(SALOME_SalomeException);
139   try {
140     _impl->ShapeToMesh( _gen_i->GeomObjectToShape( theShapeObject ));
141   }
142   catch(SALOME_Exception & S_ex) {
143     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
144   }
145 }
146
147 //================================================================================
148 /*!
149  * \brief return true if mesh has a shape to build a shape on
150  */
151 //================================================================================
152
153 CORBA::Boolean SMESH_Mesh_i::HasShapeToMesh()
154   throw (SALOME::SALOME_Exception)
155 {
156   Unexpect aCatch(SALOME_SalomeException);
157   bool res = false;
158   try {
159     res = _impl->HasShapeToMesh();
160   }
161   catch(SALOME_Exception & S_ex) {
162     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
163   }
164   return res;
165 }
166
167 //=======================================================================
168 //function : GetShapeToMesh
169 //purpose  :
170 //=======================================================================
171
172 GEOM::GEOM_Object_ptr SMESH_Mesh_i::GetShapeToMesh()
173     throw (SALOME::SALOME_Exception)
174 {
175   Unexpect aCatch(SALOME_SalomeException);
176   GEOM::GEOM_Object_var aShapeObj;
177   try {
178     TopoDS_Shape S = _impl->GetMeshDS()->ShapeToMesh();
179     if ( !S.IsNull() )
180       aShapeObj = _gen_i->ShapeToGeomObject( S );
181   }
182   catch(SALOME_Exception & S_ex) {
183     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
184   }
185   return aShapeObj._retn();
186 }
187
188 //=============================================================================
189 /*!
190  *
191  */
192 //=============================================================================
193
194 static SMESH::DriverMED_ReadStatus ConvertDriverMEDReadStatus (int theStatus)
195 {
196   SMESH::DriverMED_ReadStatus res;
197   switch (theStatus)
198   {
199   case DriverMED_R_SMESHDS_Mesh::DRS_OK:
200     res = SMESH::DRS_OK; break;
201   case DriverMED_R_SMESHDS_Mesh::DRS_EMPTY:
202     res = SMESH::DRS_EMPTY; break;
203   case DriverMED_R_SMESHDS_Mesh::DRS_WARN_RENUMBER:
204     res = SMESH::DRS_WARN_RENUMBER; break;
205   case DriverMED_R_SMESHDS_Mesh::DRS_WARN_SKIP_ELEM:
206     res = SMESH::DRS_WARN_SKIP_ELEM; break;
207   case DriverMED_R_SMESHDS_Mesh::DRS_FAIL:
208   default:
209     res = SMESH::DRS_FAIL; break;
210   }
211   return res;
212 }
213
214 //=============================================================================
215 /*!
216  *  ImportMEDFile
217  *
218  *  Imports mesh data from MED file
219  */
220 //=============================================================================
221
222 SMESH::DriverMED_ReadStatus
223 SMESH_Mesh_i::ImportMEDFile( const char* theFileName, const char* theMeshName )
224   throw ( SALOME::SALOME_Exception )
225 {
226   Unexpect aCatch(SALOME_SalomeException);
227   int status;
228   try {
229     status = importMEDFile( theFileName, theMeshName );
230   }
231   catch( SALOME_Exception& S_ex ) {
232     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
233   }
234   catch ( ... ) {
235     THROW_SALOME_CORBA_EXCEPTION("ImportMEDFile(): unknown exception", SALOME::BAD_PARAM);
236   }
237
238   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
239   if ( !aStudy->_is_nil() ) {
240     // publishing of the groups in the study (sub-meshes are out of scope of MED import)
241     map<int, SMESH::SMESH_GroupBase_ptr>::iterator it = _mapGroups.begin();
242     for (; it != _mapGroups.end(); it++ ) {
243       SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_duplicate( it->second );
244       _gen_i->PublishGroup( aStudy, _this(), aGroup,
245                            GEOM::GEOM_Object::_nil(), aGroup->GetName());
246     }
247   }
248   return ConvertDriverMEDReadStatus(status);
249 }
250
251 //=============================================================================
252 /*!
253  *  ImportUNVFile
254  *
255  *  Imports mesh data from MED file
256  */
257 //=============================================================================
258
259 int SMESH_Mesh_i::ImportUNVFile( const char* theFileName )
260   throw ( SALOME::SALOME_Exception )
261 {
262   // Read mesh with name = <theMeshName> into SMESH_Mesh
263   _impl->UNVToMesh( theFileName );
264
265   CreateGroupServants();
266
267   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
268   if ( !aStudy->_is_nil() ) {
269     // publishing of the groups in the study (sub-meshes are out of scope of UNV import)
270     map<int, SMESH::SMESH_GroupBase_ptr>::iterator it = _mapGroups.begin();
271     for (; it != _mapGroups.end(); it++ ) {
272       SMESH::SMESH_GroupBase_var aGroup = SMESH::SMESH_GroupBase::_duplicate( it->second );
273       _gen_i->PublishGroup( aStudy, _this(), aGroup,
274                            GEOM::GEOM_Object::_nil(), aGroup->GetName());
275     }
276   }
277   return 1;
278 }
279
280 //=============================================================================
281 /*!
282  *  ImportSTLFile
283  *
284  *  Imports mesh data from STL file
285  */
286 //=============================================================================
287 int SMESH_Mesh_i::ImportSTLFile( const char* theFileName )
288   throw ( SALOME::SALOME_Exception )
289 {
290   // Read mesh with name = <theMeshName> into SMESH_Mesh
291   _impl->STLToMesh( theFileName );
292
293   return 1;
294 }
295
296 //=============================================================================
297 /*!
298  *  importMEDFile
299  *
300  *  Imports mesh data from MED file
301  */
302 //=============================================================================
303
304 int SMESH_Mesh_i::importMEDFile( const char* theFileName, const char* theMeshName )
305 {
306   // Read mesh with name = <theMeshName> and all its groups into SMESH_Mesh
307   int status = _impl->MEDToMesh( theFileName, theMeshName );
308   CreateGroupServants();
309
310   return status;
311 }
312
313 //=============================================================================
314 /*!
315  *
316  */
317 //=============================================================================
318
319 #define RETURNCASE(hyp_stat) case SMESH_Hypothesis::hyp_stat: return SMESH::hyp_stat;
320
321 SMESH::Hypothesis_Status SMESH_Mesh_i::ConvertHypothesisStatus
322                          (SMESH_Hypothesis::Hypothesis_Status theStatus)
323 {
324   switch (theStatus) {
325   RETURNCASE( HYP_OK            );
326   RETURNCASE( HYP_MISSING       );
327   RETURNCASE( HYP_CONCURENT     );
328   RETURNCASE( HYP_BAD_PARAMETER );
329   RETURNCASE( HYP_HIDDEN_ALGO   );
330   RETURNCASE( HYP_HIDING_ALGO   );
331   RETURNCASE( HYP_UNKNOWN_FATAL );
332   RETURNCASE( HYP_INCOMPATIBLE  );
333   RETURNCASE( HYP_NOTCONFORM    );
334   RETURNCASE( HYP_ALREADY_EXIST );
335   RETURNCASE( HYP_BAD_DIM       );
336   RETURNCASE( HYP_BAD_SUBSHAPE  );
337   RETURNCASE( HYP_BAD_GEOMETRY  );
338   default:;
339   }
340   return SMESH::HYP_UNKNOWN_FATAL;
341 }
342
343 //=============================================================================
344 /*!
345  *  AddHypothesis
346  *
347  *  calls internal addHypothesis() and then adds a reference to <anHyp> under
348  *  the SObject actually having a reference to <aSubShape>.
349  *  NB: For this method to work, it is necessary to add a reference to sub-shape first.
350  */
351 //=============================================================================
352
353 SMESH::Hypothesis_Status SMESH_Mesh_i::AddHypothesis(GEOM::GEOM_Object_ptr aSubShapeObject,
354                                                      SMESH::SMESH_Hypothesis_ptr anHyp)
355   throw(SALOME::SALOME_Exception)
356 {
357   Unexpect aCatch(SALOME_SalomeException);
358   SMESH_Hypothesis::Hypothesis_Status status = addHypothesis( aSubShapeObject, anHyp );
359
360   if ( !SMESH_Hypothesis::IsStatusFatal(status) )
361     _gen_i->AddHypothesisToShape(_gen_i->GetCurrentStudy(), _this(),
362                                  aSubShapeObject, anHyp );
363
364   if(MYDEBUG) MESSAGE( " AddHypothesis(): status = " << status );
365
366   // Update Python script
367   if(_impl->HasShapeToMesh()) {
368     TPythonDump() << "status = " << _this() << ".AddHypothesis( "
369                   << aSubShapeObject << ", " << anHyp << " )";
370   }
371   else {
372     TPythonDump() << "status = " << _this() << ".AddHypothesis( "<< anHyp << " )";
373   }
374   
375   return ConvertHypothesisStatus(status);
376 }
377
378 //=============================================================================
379 /*!
380  *
381  */
382 //=============================================================================
383
384 SMESH_Hypothesis::Hypothesis_Status
385   SMESH_Mesh_i::addHypothesis(GEOM::GEOM_Object_ptr       aSubShapeObject,
386                               SMESH::SMESH_Hypothesis_ptr anHyp)
387 {
388   if(MYDEBUG) MESSAGE("addHypothesis");
389
390   if (CORBA::is_nil(aSubShapeObject) && HasShapeToMesh())
391     THROW_SALOME_CORBA_EXCEPTION("bad subShape reference",
392                                  SALOME::BAD_PARAM);
393
394   SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow(anHyp);
395   if (CORBA::is_nil(myHyp))
396     THROW_SALOME_CORBA_EXCEPTION("bad hypothesis reference",
397                                  SALOME::BAD_PARAM);
398
399   SMESH_Hypothesis::Hypothesis_Status status = SMESH_Hypothesis::HYP_OK;
400   try
401   {
402     TopoDS_Shape myLocSubShape;
403     //use PseudoShape in case if mesh has no shape
404     if(HasShapeToMesh())
405       myLocSubShape = _gen_i->GeomObjectToShape( aSubShapeObject);
406     else              
407       myLocSubShape = _impl->GetShapeToMesh();
408     
409     int hypId = myHyp->GetId();
410     status = _impl->AddHypothesis(myLocSubShape, hypId);
411     if ( !SMESH_Hypothesis::IsStatusFatal(status) ) {
412       _mapHypo[hypId] = SMESH::SMESH_Hypothesis::_duplicate( myHyp );
413       // assure there is a corresponding submesh
414       if ( !_impl->IsMainShape( myLocSubShape )) {
415         int shapeId = _impl->GetMeshDS()->ShapeToIndex( myLocSubShape );
416         if ( _mapSubMesh_i.find( shapeId ) == _mapSubMesh_i.end() )
417           createSubMesh( aSubShapeObject );
418       }
419     }
420   }
421   catch(SALOME_Exception & S_ex)
422   {
423     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
424   }
425   return status;
426 }
427
428 //=============================================================================
429 /*!
430  *
431  */
432 //=============================================================================
433
434 SMESH::Hypothesis_Status SMESH_Mesh_i::RemoveHypothesis(GEOM::GEOM_Object_ptr aSubShapeObject,
435                                                         SMESH::SMESH_Hypothesis_ptr anHyp)
436      throw(SALOME::SALOME_Exception)
437 {
438   Unexpect aCatch(SALOME_SalomeException);
439   SMESH_Hypothesis::Hypothesis_Status status = removeHypothesis( aSubShapeObject, anHyp );
440
441   if ( !SMESH_Hypothesis::IsStatusFatal(status) )
442     _gen_i->RemoveHypothesisFromShape(_gen_i->GetCurrentStudy(), _this(),
443                                       aSubShapeObject, anHyp );
444
445   // Update Python script
446     // Update Python script
447   if(_impl->HasShapeToMesh()) {
448   TPythonDump() << "status = " << _this() << ".RemoveHypothesis( "
449                 << aSubShapeObject << ", " << anHyp << " )";
450   }
451   else {
452     TPythonDump() << "status = " << _this() << ".RemoveHypothesis( "
453                   << anHyp << " )";
454   }
455
456   return ConvertHypothesisStatus(status);
457 }
458
459 //=============================================================================
460 /*!
461  *
462  */
463 //=============================================================================
464
465 SMESH_Hypothesis::Hypothesis_Status SMESH_Mesh_i::removeHypothesis(GEOM::GEOM_Object_ptr aSubShapeObject,
466                                  SMESH::SMESH_Hypothesis_ptr anHyp)
467 {
468         if(MYDEBUG) MESSAGE("removeHypothesis()");
469         // **** proposer liste de subShape (selection multiple)
470
471         if (CORBA::is_nil(aSubShapeObject) && HasShapeToMesh())
472                 THROW_SALOME_CORBA_EXCEPTION("bad subShape reference",
473                         SALOME::BAD_PARAM);
474
475         SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow(anHyp);
476         if (CORBA::is_nil(myHyp))
477           THROW_SALOME_CORBA_EXCEPTION("bad hypothesis reference",
478                         SALOME::BAD_PARAM);
479
480         SMESH_Hypothesis::Hypothesis_Status status = SMESH_Hypothesis::HYP_OK;
481         try
482         {
483                 TopoDS_Shape myLocSubShape;
484                 //use PseudoShape in case if mesh has no shape
485                 if(HasShapeToMesh())
486                   myLocSubShape = _gen_i->GeomObjectToShape( aSubShapeObject);
487                 else
488                   myLocSubShape = _impl->GetShapeToMesh();
489                 
490                 int hypId = myHyp->GetId();
491                 status = _impl->RemoveHypothesis(myLocSubShape, hypId);
492                 if ( !SMESH_Hypothesis::IsStatusFatal(status) )
493                   _mapHypo.erase( hypId );
494         }
495         catch(SALOME_Exception & S_ex)
496         {
497                 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
498         }
499         return status;
500 }
501
502 //=============================================================================
503 /*!
504  *
505  */
506 //=============================================================================
507
508 SMESH::ListOfHypothesis *
509         SMESH_Mesh_i::GetHypothesisList(GEOM::GEOM_Object_ptr aSubShapeObject)
510 throw(SALOME::SALOME_Exception)
511 {
512   Unexpect aCatch(SALOME_SalomeException);
513   if (MYDEBUG) MESSAGE("GetHypothesisList");
514   if (CORBA::is_nil(aSubShapeObject))
515     THROW_SALOME_CORBA_EXCEPTION("bad subShape reference",
516                                  SALOME::BAD_PARAM);
517
518   SMESH::ListOfHypothesis_var aList = new SMESH::ListOfHypothesis();
519
520   try {
521     TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(aSubShapeObject);
522     const list<const SMESHDS_Hypothesis*>& aLocalList = _impl->GetHypothesisList( myLocSubShape );
523     int i = 0, n = aLocalList.size();
524     aList->length( n );
525
526     for ( list<const SMESHDS_Hypothesis*>::const_iterator anIt = aLocalList.begin(); i < n && anIt != aLocalList.end(); anIt++ ) {
527       SMESHDS_Hypothesis* aHyp = (SMESHDS_Hypothesis*)(*anIt);
528       if ( _mapHypo.find( aHyp->GetID() ) != _mapHypo.end() )
529         aList[i++] = SMESH::SMESH_Hypothesis::_narrow( _mapHypo[aHyp->GetID()] );
530     }
531
532     aList->length( i );
533   }
534   catch(SALOME_Exception & S_ex) {
535     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
536   }
537
538   return aList._retn();
539 }
540
541 //=============================================================================
542 /*!
543  *
544  */
545 //=============================================================================
546 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::GetSubMesh(GEOM::GEOM_Object_ptr aSubShapeObject,
547                                                   const char*           theName )
548      throw(SALOME::SALOME_Exception)
549 {
550   Unexpect aCatch(SALOME_SalomeException);
551   MESSAGE("SMESH_Mesh_i::GetSubMesh");
552   if (CORBA::is_nil(aSubShapeObject))
553     THROW_SALOME_CORBA_EXCEPTION("bad subShape reference",
554                                  SALOME::BAD_PARAM);
555
556   SMESH::SMESH_subMesh_var subMesh;
557   SMESH::SMESH_Mesh_var    aMesh = SMESH::SMESH_Mesh::_narrow(_this());
558   try {
559     TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(aSubShapeObject);
560
561     //Get or Create the SMESH_subMesh object implementation
562
563     int subMeshId = _impl->GetMeshDS()->ShapeToIndex( myLocSubShape );
564     subMesh = getSubMesh( subMeshId );
565
566     // create a new subMesh object servant if there is none for the shape
567     if ( subMesh->_is_nil() )
568       subMesh = createSubMesh( aSubShapeObject );
569
570     if ( _gen_i->CanPublishInStudy( subMesh )) {
571       SALOMEDS::SObject_var aSO =
572         _gen_i->PublishSubMesh(_gen_i->GetCurrentStudy(), aMesh,
573                                subMesh, aSubShapeObject, theName );
574       if ( !aSO->_is_nil()) {
575         // Update Python script
576         TPythonDump() << aSO << " = " << _this() << ".GetSubMesh( "
577                       << aSubShapeObject << ", '" << theName << "' )";
578       }
579     }
580   }
581   catch(SALOME_Exception & S_ex) {
582     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
583   }
584   return subMesh._retn();
585 }
586
587 //=============================================================================
588 /*!
589  *
590  */
591 //=============================================================================
592
593 void SMESH_Mesh_i::RemoveSubMesh( SMESH::SMESH_subMesh_ptr theSubMesh )
594      throw (SALOME::SALOME_Exception)
595 {
596   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::RemoveSubMesh");
597   if ( theSubMesh->_is_nil() )
598     return;
599
600   GEOM::GEOM_Object_var aSubShapeObject;
601   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
602   if ( !aStudy->_is_nil() )  {
603     // Remove submesh's SObject
604     SALOMEDS::SObject_var anSO = _gen_i->ObjectToSObject( aStudy, theSubMesh );
605     if ( !anSO->_is_nil() ) {
606       long aTag = SMESH_Gen_i::GetRefOnShapeTag();
607       SALOMEDS::SObject_var anObj, aRef;
608       if ( anSO->FindSubObject( aTag, anObj ) && anObj->ReferencedObject( aRef ) )
609         aSubShapeObject = GEOM::GEOM_Object::_narrow( aRef->GetObject() );
610
611       aStudy->NewBuilder()->RemoveObjectWithChildren( anSO );
612
613       // Update Python script
614       TPythonDump() << _this() << ".RemoveSubMesh( " << anSO << " )";
615     }
616   }
617
618   removeSubMesh( theSubMesh, aSubShapeObject.in() );
619 }
620
621 //=============================================================================
622 /*!
623  *  ElementTypeString
624  */
625 //=============================================================================
626 #define CASE2STRING(enum) case SMESH::enum: return "SMESH."#enum;
627 inline TCollection_AsciiString ElementTypeString (SMESH::ElementType theElemType)
628 {
629   switch (theElemType) {
630     CASE2STRING( ALL );
631     CASE2STRING( NODE );
632     CASE2STRING( EDGE );
633     CASE2STRING( FACE );
634     CASE2STRING( VOLUME );
635   default:;
636   }
637   return "";
638 }
639
640 //=============================================================================
641 /*!
642  *
643  */
644 //=============================================================================
645
646 SMESH::SMESH_Group_ptr SMESH_Mesh_i::CreateGroup( SMESH::ElementType theElemType,
647                                                  const char*         theName )
648      throw(SALOME::SALOME_Exception)
649 {
650   Unexpect aCatch(SALOME_SalomeException);
651   SMESH::SMESH_Group_var aNewGroup =
652     SMESH::SMESH_Group::_narrow( createGroup( theElemType, theName ));
653
654   if ( _gen_i->CanPublishInStudy( aNewGroup ) ) {
655     SALOMEDS::SObject_var aSO =
656       _gen_i->PublishGroup(_gen_i->GetCurrentStudy(), _this(),
657                            aNewGroup, GEOM::GEOM_Object::_nil(), theName);
658     if ( !aSO->_is_nil()) {
659       // Update Python script
660       TPythonDump() << aSO << " = " << _this() << ".CreateGroup( "
661                     << ElementTypeString(theElemType) << ", '" << theName << "' )";
662     }
663   }
664   return aNewGroup._retn();
665 }
666
667
668 //=============================================================================
669 /*!
670  *
671  */
672 //=============================================================================
673 SMESH::SMESH_GroupOnGeom_ptr SMESH_Mesh_i::CreateGroupFromGEOM (SMESH::ElementType    theElemType,
674                                                                 const char*           theName,
675                                                                 GEOM::GEOM_Object_ptr theGeomObj)
676      throw(SALOME::SALOME_Exception)
677 {
678   Unexpect aCatch(SALOME_SalomeException);
679   SMESH::SMESH_GroupOnGeom_var aNewGroup;
680
681   TopoDS_Shape aShape = _gen_i->GeomObjectToShape( theGeomObj );
682   if ( !aShape.IsNull() ) {
683     aNewGroup = SMESH::SMESH_GroupOnGeom::_narrow
684       ( createGroup( theElemType, theName, aShape ));
685     if ( _gen_i->CanPublishInStudy( aNewGroup ) ) {
686       SALOMEDS::SObject_var aSO =
687         _gen_i->PublishGroup(_gen_i->GetCurrentStudy(), _this(),
688                              aNewGroup, theGeomObj, theName);
689       if ( !aSO->_is_nil()) {
690         // Update Python script
691         TPythonDump() << aSO << " = " << _this() << ".CreateGroupFromGEOM("
692                       << ElementTypeString(theElemType) << ", '" << theName << "', "
693                       << theGeomObj << " )";
694       }
695     }
696   }
697
698   return aNewGroup._retn();
699 }
700
701 //=============================================================================
702 /*!
703  *
704  */
705 //=============================================================================
706
707 void SMESH_Mesh_i::RemoveGroup( SMESH::SMESH_GroupBase_ptr theGroup )
708      throw (SALOME::SALOME_Exception)
709 {
710   if ( theGroup->_is_nil() )
711     return;
712
713   SMESH_GroupBase_i* aGroup =
714     dynamic_cast<SMESH_GroupBase_i*>( SMESH_Gen_i::GetServant( theGroup ).in() );
715   if ( !aGroup )
716     return;
717
718   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
719   if ( !aStudy->_is_nil() )  {
720     SALOMEDS::SObject_var aGroupSO = _gen_i->ObjectToSObject( aStudy, theGroup );
721
722     if ( !aGroupSO->_is_nil() ) {
723       // Update Python script
724       TPythonDump() << _this() << ".RemoveGroup( " << aGroupSO << " )";
725
726       // Remove group's SObject
727       aStudy->NewBuilder()->RemoveObject( aGroupSO );
728     }
729   }
730
731   // Remove the group from SMESH data structures
732   removeGroup( aGroup->GetLocalID() );
733 }
734
735 //=============================================================================
736 /*! RemoveGroupWithContents
737  *  Remove group with its contents
738  */
739 //=============================================================================
740 void SMESH_Mesh_i::RemoveGroupWithContents( SMESH::SMESH_GroupBase_ptr theGroup )
741   throw (SALOME::SALOME_Exception)
742 {
743   if ( theGroup->_is_nil() )
744     return;
745
746   SMESH_GroupBase_i* aGroup =
747     dynamic_cast<SMESH_GroupBase_i*>( SMESH_Gen_i::GetServant( theGroup ).in() );
748   if ( !aGroup )
749     return;
750
751   SMESH::long_array_var anIds = aGroup->GetListOfID();
752   SMESH::SMESH_MeshEditor_var aMeshEditor = SMESH_Mesh_i::GetMeshEditor();
753
754   // Update Python script
755   TPythonDump() << _this() << ".RemoveGroupWithContents( " << theGroup << " )";
756
757   // Remove contents
758   if ( aGroup->GetType() == SMESH::NODE )
759     aMeshEditor->RemoveNodes( anIds );
760   else
761     aMeshEditor->RemoveElements( anIds );
762
763   // Remove group
764   RemoveGroup( theGroup );
765
766   // Clear python lines, created by RemoveNodes/Elements() and RemoveGroup()
767   _gen_i->RemoveLastFromPythonScript(_gen_i->GetCurrentStudy()->StudyId());
768   _gen_i->RemoveLastFromPythonScript(_gen_i->GetCurrentStudy()->StudyId());
769 }
770
771
772 //================================================================================
773 /*!
774  * \brief Get the list of groups existing in the mesh
775   * \retval SMESH::ListOfGroups * - list of groups
776  */
777 //================================================================================
778
779 SMESH::ListOfGroups * SMESH_Mesh_i::GetGroups() throw(SALOME::SALOME_Exception)
780 {
781   Unexpect aCatch(SALOME_SalomeException);
782   if (MYDEBUG) MESSAGE("GetGroups");
783
784   SMESH::ListOfGroups_var aList = new SMESH::ListOfGroups();
785
786   // Python Dump
787   TPythonDump aPythonDump;
788   if ( !_mapGroups.empty() ) // (IMP13463) avoid "SyntaxError: can't assign to []"
789     aPythonDump << "[ ";
790
791   try {
792     aList->length( _mapGroups.size() );
793     int i = 0;
794     map<int, SMESH::SMESH_GroupBase_ptr>::iterator it = _mapGroups.begin();
795     for ( ; it != _mapGroups.end(); it++ ) {
796       if ( CORBA::is_nil( it->second )) continue;
797       aList[i++] = SMESH::SMESH_GroupBase::_duplicate( it->second );
798       // Python Dump
799       if (i > 1) aPythonDump << ", ";
800       aPythonDump << it->second;
801     }
802     aList->length( i );
803   }
804   catch(SALOME_Exception & S_ex) {
805     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
806   }
807
808   // Update Python script
809   if ( !_mapGroups.empty() ) // (IMP13463) avoid "SyntaxError: can't assign to []"
810     aPythonDump << " ] = " << _this() << ".GetGroups()";
811
812   return aList._retn();
813 }
814
815 //=============================================================================
816 /*! UnionGroups
817  *  New group is created. All mesh elements that are
818  *  present in initial groups are added to the new one
819  */
820 //=============================================================================
821 SMESH::SMESH_Group_ptr SMESH_Mesh_i::UnionGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
822                                                   SMESH::SMESH_GroupBase_ptr theGroup2,
823                                                   const char* theName )
824   throw (SALOME::SALOME_Exception)
825 {
826   try
827   {
828     if ( theGroup1->_is_nil() || theGroup2->_is_nil() ||
829          theGroup1->GetType() != theGroup2->GetType() )
830       return SMESH::SMESH_Group::_nil();
831
832     // Create Union
833     SMESH::SMESH_Group_var aResGrp = CreateGroup( theGroup1->GetType(), theName );
834     if ( aResGrp->_is_nil() )
835       return SMESH::SMESH_Group::_nil();
836
837     SMESH::long_array_var anIds1 = theGroup1->GetListOfID();
838     SMESH::long_array_var anIds2 = theGroup2->GetListOfID();
839
840     TColStd_MapOfInteger aResMap;
841
842     for ( int i1 = 0, n1 = anIds1->length(); i1 < n1; i1++ )
843       aResMap.Add( anIds1[ i1 ] );
844
845     for ( int i2 = 0, n2 = anIds2->length(); i2 < n2; i2++ )
846       aResMap.Add( anIds2[ i2 ] );
847
848     SMESH::long_array_var aResIds = new SMESH::long_array;
849     aResIds->length( aResMap.Extent() );
850
851     int resI = 0;
852     TColStd_MapIteratorOfMapOfInteger anIter( aResMap );
853     for( ; anIter.More(); anIter.Next() )
854       aResIds[ resI++ ] = anIter.Key();
855
856     aResGrp->Add( aResIds );
857
858     // Clear python lines, created by CreateGroup() and Add()
859     SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
860     _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
861     _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
862
863     // Update Python script
864     TPythonDump() << aResGrp << " = " << _this() << ".UnionGroups( "
865                   << theGroup1 << ", " << theGroup2 << ", '"
866                   << theName << "' )";
867
868     return aResGrp._retn();
869   }
870   catch( ... )
871   {
872     return SMESH::SMESH_Group::_nil();
873   }
874 }
875
876 //=============================================================================
877 /*! IntersectGroups
878  *  New group is created. All mesh elements that are
879  *  present in both initial groups are added to the new one.
880  */
881 //=============================================================================
882 SMESH::SMESH_Group_ptr SMESH_Mesh_i::IntersectGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
883                                                       SMESH::SMESH_GroupBase_ptr theGroup2,
884                                                       const char* theName )
885   throw (SALOME::SALOME_Exception)
886 {
887   if ( theGroup1->_is_nil() || theGroup2->_is_nil() ||
888        theGroup1->GetType() != theGroup2->GetType() )
889     return SMESH::SMESH_Group::_nil();
890
891   // Create Intersection
892   SMESH::SMESH_Group_var aResGrp = CreateGroup( theGroup1->GetType(), theName );
893   if ( aResGrp->_is_nil() )
894     return aResGrp;
895
896   SMESH::long_array_var anIds1 = theGroup1->GetListOfID();
897   SMESH::long_array_var anIds2 = theGroup2->GetListOfID();
898
899   TColStd_MapOfInteger aMap1;
900
901   for ( int i1 = 0, n1 = anIds1->length(); i1 < n1; i1++ )
902     aMap1.Add( anIds1[ i1 ] );
903
904   TColStd_SequenceOfInteger aSeq;
905
906   for ( int i2 = 0, n2 = anIds2->length(); i2 < n2; i2++ )
907     if ( aMap1.Contains( anIds2[ i2 ] ) )
908       aSeq.Append( anIds2[ i2 ] );
909
910   SMESH::long_array_var aResIds = new SMESH::long_array;
911   aResIds->length( aSeq.Length() );
912
913   for ( int resI = 0, resN = aSeq.Length(); resI < resN; resI++ )
914     aResIds[ resI ] = aSeq( resI + 1 );
915
916   aResGrp->Add( aResIds );
917
918   // Clear python lines, created by CreateGroup() and Add()
919   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
920   _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
921   _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
922
923   // Update Python script
924   TPythonDump() << aResGrp << " = " << _this() << ".IntersectGroups( "
925                 << theGroup1 << ", " << theGroup2 << ", '" << theName << "')";
926
927   return aResGrp._retn();
928 }
929
930 //=============================================================================
931 /*! CutGroups
932  *  New group is created. All mesh elements that are present in
933  *  main group but do not present in tool group are added to the new one
934  */
935 //=============================================================================
936 SMESH::SMESH_Group_ptr SMESH_Mesh_i::CutGroups( SMESH::SMESH_GroupBase_ptr theGroup1,
937                                                 SMESH::SMESH_GroupBase_ptr theGroup2,
938                                                 const char* theName )
939   throw (SALOME::SALOME_Exception)
940 {
941   if ( theGroup1->_is_nil() || theGroup2->_is_nil() ||
942        theGroup1->GetType() != theGroup2->GetType() )
943     return SMESH::SMESH_Group::_nil();
944
945   // Perform Cutting
946   SMESH::SMESH_Group_var aResGrp = CreateGroup( theGroup1->GetType(), theName );
947   if ( aResGrp->_is_nil() )
948     return aResGrp;
949
950   SMESH::long_array_var anIds1 = theGroup1->GetListOfID();
951   SMESH::long_array_var anIds2 = theGroup2->GetListOfID();
952
953   TColStd_MapOfInteger aMap2;
954
955   for ( int i2 = 0, n2 = anIds2->length(); i2 < n2; i2++ )
956     aMap2.Add( anIds2[ i2 ] );
957
958
959   TColStd_SequenceOfInteger aSeq;
960   for ( int i1 = 0, n1 = anIds1->length(); i1 < n1; i1++ )
961     if ( !aMap2.Contains( anIds1[ i1 ] ) )
962       aSeq.Append( anIds1[ i1 ] );
963
964   SMESH::long_array_var aResIds = new SMESH::long_array;
965   aResIds->length( aSeq.Length() );
966
967   for ( int resI = 0, resN = aSeq.Length(); resI < resN; resI++ )
968     aResIds[ resI ] = aSeq( resI + 1 );
969
970   aResGrp->Add( aResIds );
971
972   // Clear python lines, created by CreateGroup() and Add()
973   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
974   _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
975   _gen_i->RemoveLastFromPythonScript(aStudy->StudyId());
976
977   // Update Python script
978   TPythonDump() << aResGrp << " = " << _this() << ".CutGroups( "
979                 << theGroup1 << ", " << theGroup2 << ", '"
980                 << theName << "' )";
981
982   return aResGrp._retn();
983 }
984
985 //================================================================================
986 /*!
987  * \brief Return group items of a group present in a study
988  */
989 //================================================================================
990
991 static GEOM::GEOM_Object_ptr getGroupItemsFromStudy(CORBA::Object_ptr    theMesh,
992                                                     SMESH_Gen_i*         theGen,
993                                                     list<TopoDS_Shape> & theItems)
994 {
995   GEOM::GEOM_Object_var groupObj;
996   SALOMEDS::Study_var  study = theGen->GetCurrentStudy();
997   GEOM::GEOM_Gen_var geomGen = theGen->GetGeomEngine();
998   if ( study->_is_nil() || geomGen->_is_nil() )
999     return groupObj._retn();
1000   
1001   GEOM::GEOM_IGroupOperations_var groupOp =
1002     geomGen->GetIGroupOperations( theGen->GetCurrentStudyID() );
1003   GEOM::GEOM_IShapesOperations_var shapeOp =
1004     geomGen->GetIShapesOperations( theGen->GetCurrentStudyID() );
1005
1006   SALOMEDS::SObject_var meshOS = theGen->ObjectToSObject(study, theMesh);
1007   if ( meshOS->_is_nil() || groupOp->_is_nil() || shapeOp->_is_nil() )
1008     return groupObj._retn();
1009   SALOMEDS::SObject_var fatherSO = meshOS->GetFather();
1010   if ( fatherSO->_is_nil() || fatherSO->Tag() != theGen->GetSubMeshOnCompoundTag() )
1011     return groupObj._retn(); // keep only submeshes on groups
1012
1013   SALOMEDS::ChildIterator_var anIter = study->NewChildIterator(meshOS);
1014   if ( anIter->_is_nil() ) return groupObj._retn();
1015   for ( ; anIter->More(); anIter->Next())
1016   {
1017     SALOMEDS::SObject_var aSObject = anIter->Value();
1018     SALOMEDS::SObject_var aRefSO;
1019     if ( !aSObject->_is_nil() && aSObject->ReferencedObject(aRefSO) )
1020     {
1021       groupObj = GEOM::GEOM_Object::_narrow(aRefSO->GetObject());
1022       if ( groupObj->_is_nil() ) break;
1023       GEOM::ListOfLong_var  ids = groupOp->GetObjects( groupObj );
1024       GEOM::GEOM_Object_var mainShape = groupObj->GetMainShape();
1025       for ( int i = 0; i < ids->length(); ++i ) {
1026         GEOM::GEOM_Object_var subShape = shapeOp->GetSubShape( mainShape, ids[i] );
1027         TopoDS_Shape S = theGen->GeomObjectToShape( subShape );
1028         if ( !S.IsNull() )
1029           theItems.push_back( S );
1030       }
1031       break;
1032     }
1033   }
1034   return groupObj._retn();
1035 }
1036
1037 //=============================================================================
1038 /*!
1039  * \brief Update hypotheses assigned to geom groups if the latter change
1040  * 
1041  * NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1042  */
1043 //=============================================================================
1044
1045 void SMESH_Mesh_i::CheckGeomGroupModif()
1046 {
1047   if ( !_impl->HasShapeToMesh() ) return;
1048
1049   SALOMEDS::Study_var study = _gen_i->GetCurrentStudy();
1050   if ( study->_is_nil() ) return;
1051
1052   // check if items of groups changed
1053   map<int, ::SMESH_subMesh*>::iterator i_sm = _mapSubMesh.begin();
1054   for ( ; i_sm != _mapSubMesh.end(); ++i_sm )
1055   {
1056     const TopoDS_Shape & oldGroupShape = i_sm->second->GetSubShape();
1057     SMESHDS_SubMesh * oldDS = i_sm->second->GetSubMeshDS();
1058     if ( !oldDS /*|| !oldDS->IsComplexSubmesh()*/ )
1059       continue;
1060     int oldID = i_sm->first;
1061     map<int, SMESH::SMESH_subMesh_ptr>::iterator i_smIor = _mapSubMeshIor.find( oldID );
1062     if ( i_smIor == _mapSubMeshIor.end() )
1063       continue;
1064     list< TopoDS_Shape> newItems;
1065     GEOM::GEOM_Object_var groupObj = getGroupItemsFromStudy ( i_smIor->second, _gen_i, newItems );
1066     if ( groupObj->_is_nil() )
1067       continue;
1068
1069     int nbOldItems = oldDS->IsComplexSubmesh() ? oldDS->NbSubMeshes() : 1;
1070     int nbNewItems = newItems.size();
1071     bool groupChanged = ( nbOldItems != nbNewItems);
1072     if ( !groupChanged ) {
1073       if ( !oldDS->IsComplexSubmesh() ) { // old group has one item
1074         groupChanged = ( oldGroupShape != newItems.front() );
1075       }
1076       else {
1077         list<TopoDS_Shape>::iterator item = newItems.begin();
1078         for ( ; item != newItems.end() && !groupChanged; ++item )
1079         {
1080           SMESHDS_SubMesh * itemDS = _impl->GetMeshDS()->MeshElements( *item );
1081           groupChanged = ( !itemDS || !oldDS->ContainsSubMesh( itemDS ));
1082         }
1083       }
1084     }
1085     // update hypotheses and submeshes if necessary
1086     if ( groupChanged )
1087     {
1088       // get a new group shape
1089       GEOM_Client* geomClient = _gen_i->GetShapeReader();
1090       if ( !geomClient ) continue;
1091       TCollection_AsciiString groupIOR = _gen_i->GetGeomEngine()->GetStringFromIOR( groupObj );
1092       geomClient->RemoveShapeFromBuffer( groupIOR );
1093       TopoDS_Shape newGroupShape = _gen_i->GeomObjectToShape( groupObj );
1094       // update hypotheses
1095       list <const SMESHDS_Hypothesis * > hyps = _impl->GetHypothesisList(oldGroupShape);
1096       list <const SMESHDS_Hypothesis * >::iterator hypIt;
1097       for ( hypIt = hyps.begin(); hypIt != hyps.end(); ++hypIt )
1098       {
1099         _impl->RemoveHypothesis( oldGroupShape, (*hypIt)->GetID());
1100         _impl->AddHypothesis   ( newGroupShape, (*hypIt)->GetID());
1101       }
1102       // care of submeshes
1103       SMESH_subMesh* newSubmesh = _impl->GetSubMesh( newGroupShape );
1104       int newID = newSubmesh->GetId();
1105       if ( newID != oldID ) {
1106         _mapSubMesh   [ newID ] = newSubmesh;
1107         _mapSubMesh_i [ newID ] = _mapSubMesh_i [ oldID ];
1108         _mapSubMeshIor[ newID ] = _mapSubMeshIor[ oldID ];
1109         _mapSubMesh.erase   (oldID);
1110         _mapSubMesh_i.erase (oldID);
1111         _mapSubMeshIor.erase(oldID);
1112         _mapSubMesh_i [ newID ]->changeLocalId( newID );
1113       }
1114     }
1115   }
1116 }
1117
1118 //=============================================================================
1119 /*!
1120  *
1121  */
1122 //=============================================================================
1123
1124 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::createSubMesh( GEOM::GEOM_Object_ptr theSubShapeObject )
1125 {
1126   if(MYDEBUG) MESSAGE( "createSubMesh" );
1127   TopoDS_Shape myLocSubShape = _gen_i->GeomObjectToShape(theSubShapeObject);
1128
1129   ::SMESH_subMesh * mySubMesh = _impl->GetSubMesh(myLocSubShape);
1130   int subMeshId = _impl->GetMeshDS()->ShapeToIndex( myLocSubShape );
1131   SMESH_subMesh_i *subMeshServant = new SMESH_subMesh_i(myPOA, _gen_i, this, subMeshId);
1132   SMESH::SMESH_subMesh_var subMesh
1133     = SMESH::SMESH_subMesh::_narrow(subMeshServant->_this());
1134
1135   _mapSubMesh[subMeshId] = mySubMesh;
1136   _mapSubMesh_i[subMeshId] = subMeshServant;
1137   _mapSubMeshIor[subMeshId] = SMESH::SMESH_subMesh::_duplicate(subMesh);
1138
1139   // register CORBA object for persistence
1140   int nextId = _gen_i->RegisterObject( subMesh );
1141   if(MYDEBUG) MESSAGE( "Add submesh to map with id = "<< nextId);
1142
1143   return subMesh._retn();
1144 }
1145
1146 //=======================================================================
1147 //function : getSubMesh
1148 //purpose  :
1149 //=======================================================================
1150
1151 SMESH::SMESH_subMesh_ptr SMESH_Mesh_i::getSubMesh(int shapeID)
1152 {
1153   map<int, SMESH::SMESH_subMesh_ptr>::iterator it = _mapSubMeshIor.find( shapeID );
1154   if ( it == _mapSubMeshIor.end() )
1155     return SMESH::SMESH_subMesh::_nil();
1156
1157   return SMESH::SMESH_subMesh::_duplicate( (*it).second );
1158 }
1159
1160
1161 //=============================================================================
1162 /*!
1163  *
1164  */
1165 //=============================================================================
1166
1167 void SMESH_Mesh_i::removeSubMesh (SMESH::SMESH_subMesh_ptr theSubMesh,
1168                                   GEOM::GEOM_Object_ptr    theSubShapeObject )
1169 {
1170   MESSAGE("SMESH_Mesh_i::removeSubMesh()");
1171   if ( theSubMesh->_is_nil() || theSubShapeObject->_is_nil() )
1172     return;
1173
1174   try {
1175     SMESH::ListOfHypothesis_var aHypList = GetHypothesisList( theSubShapeObject );
1176     for ( int i = 0, n = aHypList->length(); i < n; i++ ) {
1177       removeHypothesis( theSubShapeObject, aHypList[i] );
1178     }
1179   }
1180   catch( const SALOME::SALOME_Exception& ) {
1181     INFOS("SMESH_Mesh_i::removeSubMesh(): exception caught!");
1182   }
1183
1184   int subMeshId = theSubMesh->GetId();
1185
1186   _mapSubMesh.erase(subMeshId);
1187   _mapSubMesh_i.erase(subMeshId);
1188   _mapSubMeshIor.erase(subMeshId);
1189   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::removeSubMesh() completed");
1190 }
1191
1192 //=============================================================================
1193 /*!
1194  *
1195  */
1196 //=============================================================================
1197
1198 SMESH::SMESH_GroupBase_ptr SMESH_Mesh_i::createGroup (SMESH::ElementType theElemType,
1199                                                       const char*         theName,
1200                                                       const TopoDS_Shape& theShape )
1201 {
1202   int anId;
1203   SMESH::SMESH_GroupBase_var aGroup;
1204   if ( _impl->AddGroup( (SMDSAbs_ElementType)theElemType, theName, anId, theShape )) {
1205     SMESH_GroupBase_i* aGroupImpl;
1206     if ( !theShape.IsNull() )
1207       aGroupImpl = new SMESH_GroupOnGeom_i( SMESH_Gen_i::GetPOA(), this, anId );
1208     else
1209       aGroupImpl = new SMESH_Group_i( SMESH_Gen_i::GetPOA(), this, anId );
1210
1211     // PAL7962: san -- To ensure correct mapping of servant and correct reference counting in GenericObj_i
1212     SMESH_Gen_i::GetPOA()->activate_object( aGroupImpl );
1213     aGroupImpl->Register();
1214     // PAL7962: san -- To ensure correct mapping of servant and correct reference counting in GenericObj_i
1215
1216     aGroup = SMESH::SMESH_GroupBase::_narrow( aGroupImpl->_this() );
1217     _mapGroups[anId] = SMESH::SMESH_GroupBase::_duplicate( aGroup );
1218
1219     // register CORBA object for persistence
1220     int nextId = _gen_i->RegisterObject( aGroup );
1221     if(MYDEBUG) MESSAGE( "Add group to map with id = "<< nextId);
1222   }
1223   return aGroup._retn();
1224 }
1225
1226 //=============================================================================
1227 /*!
1228  * SMESH_Mesh_i::removeGroup
1229  *
1230  * Should be called by ~SMESH_Group_i()
1231  */
1232 //=============================================================================
1233
1234 void SMESH_Mesh_i::removeGroup( const int theId )
1235 {
1236   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::removeGroup()" );
1237   if ( _mapGroups.find( theId ) != _mapGroups.end() ) {
1238     _mapGroups.erase( theId );
1239     _impl->RemoveGroup( theId );
1240   }
1241 }
1242
1243
1244 //=============================================================================
1245 /*!
1246  *
1247  */
1248 //=============================================================================
1249
1250 SMESH::log_array * SMESH_Mesh_i::GetLog(CORBA::Boolean clearAfterGet)
1251 throw(SALOME::SALOME_Exception)
1252 {
1253   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::GetLog");
1254
1255   SMESH::log_array_var aLog;
1256   try{
1257     list < SMESHDS_Command * >logDS = _impl->GetLog();
1258     aLog = new SMESH::log_array;
1259     int indexLog = 0;
1260     int lg = logDS.size();
1261     SCRUTE(lg);
1262     aLog->length(lg);
1263     list < SMESHDS_Command * >::iterator its = logDS.begin();
1264     while(its != logDS.end()){
1265       SMESHDS_Command *com = *its;
1266       int comType = com->GetType();
1267       //SCRUTE(comType);
1268       int lgcom = com->GetNumber();
1269       //SCRUTE(lgcom);
1270       const list < int >&intList = com->GetIndexes();
1271       int inum = intList.size();
1272       //SCRUTE(inum);
1273       list < int >::const_iterator ii = intList.begin();
1274       const list < double >&coordList = com->GetCoords();
1275       int rnum = coordList.size();
1276       //SCRUTE(rnum);
1277       list < double >::const_iterator ir = coordList.begin();
1278       aLog[indexLog].commandType = comType;
1279       aLog[indexLog].number = lgcom;
1280       aLog[indexLog].coords.length(rnum);
1281       aLog[indexLog].indexes.length(inum);
1282       for(int i = 0; i < rnum; i++){
1283         aLog[indexLog].coords[i] = *ir;
1284         //MESSAGE(" "<<i<<" "<<ir.Value());
1285         ir++;
1286       }
1287       for(int i = 0; i < inum; i++){
1288         aLog[indexLog].indexes[i] = *ii;
1289         //MESSAGE(" "<<i<<" "<<ii.Value());
1290         ii++;
1291       }
1292       indexLog++;
1293       its++;
1294     }
1295     if(clearAfterGet)
1296       _impl->ClearLog();
1297   }
1298   catch(SALOME_Exception & S_ex){
1299     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1300   }
1301   return aLog._retn();
1302 }
1303
1304
1305 //=============================================================================
1306 /*!
1307  *
1308  */
1309 //=============================================================================
1310
1311 void SMESH_Mesh_i::ClearLog() throw(SALOME::SALOME_Exception)
1312 {
1313   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::ClearLog");
1314   // ****
1315 }
1316
1317 //=============================================================================
1318 /*!
1319  *
1320  */
1321 //=============================================================================
1322
1323 CORBA::Long SMESH_Mesh_i::GetId()throw(SALOME::SALOME_Exception)
1324 {
1325   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::GetId");
1326   return _id;
1327 }
1328
1329 //=============================================================================
1330 /*!
1331  *
1332  */
1333 //=============================================================================
1334
1335 CORBA::Long SMESH_Mesh_i::GetStudyId()throw(SALOME::SALOME_Exception)
1336 {
1337   return _studyId;
1338 }
1339
1340 //=============================================================================
1341 /*!
1342  *
1343  */
1344 //=============================================================================
1345
1346 void SMESH_Mesh_i::SetImpl(::SMESH_Mesh * impl)
1347 {
1348   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::SetImpl");
1349   _impl = impl;
1350 }
1351
1352 //=============================================================================
1353 /*!
1354  *
1355  */
1356 //=============================================================================
1357
1358 ::SMESH_Mesh & SMESH_Mesh_i::GetImpl()
1359 {
1360   if(MYDEBUG) MESSAGE("SMESH_Mesh_i::GetImpl()");
1361   return *_impl;
1362 }
1363
1364 //=============================================================================
1365 /*!
1366  * Return mesh editor
1367  */
1368 //=============================================================================
1369
1370 SMESH::SMESH_MeshEditor_ptr SMESH_Mesh_i::GetMeshEditor()
1371 {
1372   // Create MeshEditor
1373   SMESH_MeshEditor_i *aMeshEditor = new SMESH_MeshEditor_i( _impl, false );
1374   SMESH::SMESH_MeshEditor_var aMesh = aMeshEditor->_this();
1375
1376   // Update Python script
1377   TPythonDump() << aMeshEditor << " = " << _this() << ".GetMeshEditor()";
1378
1379   return aMesh._retn();
1380 }
1381
1382 //=============================================================================
1383 /*!
1384  * Return mesh edition previewer
1385  */
1386 //=============================================================================
1387
1388 SMESH::SMESH_MeshEditor_ptr SMESH_Mesh_i::GetMeshEditPreviewer()
1389 {
1390   SMESH_MeshEditor_i *aMeshEditor = new SMESH_MeshEditor_i( _impl, true );
1391   SMESH::SMESH_MeshEditor_var aMesh = aMeshEditor->_this();
1392   return aMesh._retn();
1393 }
1394
1395 //=============================================================================
1396 /*!
1397  *  Export in different formats
1398  */
1399 //=============================================================================
1400
1401 CORBA::Boolean SMESH_Mesh_i::HasDuplicatedGroupNamesMED()
1402 {
1403   return _impl->HasDuplicatedGroupNamesMED();
1404 }
1405
1406 static void PrepareForWriting (const char* file)
1407 {
1408   TCollection_AsciiString aFullName ((char*)file);
1409   OSD_Path aPath (aFullName);
1410   OSD_File aFile (aPath);
1411   if (aFile.Exists()) {
1412     // existing filesystem node
1413     if (aFile.KindOfFile() == OSD_FILE) {
1414       if (aFile.IsWriteable()) {
1415         aFile.Reset();
1416         aFile.Remove();
1417         if (aFile.Failed()) {
1418           TCollection_AsciiString msg ("File ");
1419           msg += aFullName + " cannot be replaced.";
1420           THROW_SALOME_CORBA_EXCEPTION(msg.ToCString(), SALOME::BAD_PARAM);
1421         }
1422       } else {
1423         TCollection_AsciiString msg ("File ");
1424         msg += aFullName + " cannot be overwritten.";
1425         THROW_SALOME_CORBA_EXCEPTION(msg.ToCString(), SALOME::BAD_PARAM);
1426       }
1427     } else {
1428       TCollection_AsciiString msg ("Location ");
1429       msg += aFullName + " is not a file.";
1430       THROW_SALOME_CORBA_EXCEPTION(msg.ToCString(), SALOME::BAD_PARAM);
1431     }
1432   } else {
1433     // nonexisting file; check if it can be created
1434     aFile.Reset();
1435     aFile.Build(OSD_WriteOnly, OSD_Protection());
1436     if (aFile.Failed()) {
1437       TCollection_AsciiString msg ("You cannot create the file ");
1438       msg += aFullName + ". Check the directory existance and access rights.";
1439       THROW_SALOME_CORBA_EXCEPTION(msg.ToCString(), SALOME::BAD_PARAM);
1440     } else {
1441       aFile.Close();
1442       aFile.Remove();
1443     }
1444   }
1445 }
1446
1447 void SMESH_Mesh_i::ExportToMED (const char* file,
1448                                 CORBA::Boolean auto_groups,
1449                                 SMESH::MED_VERSION theVersion)
1450   throw(SALOME::SALOME_Exception)
1451 {
1452   Unexpect aCatch(SALOME_SalomeException);
1453
1454   // Update Python script
1455   TPythonDump() << _this() << ".ExportToMED( '"
1456                 << file << "', " << auto_groups << ", " << theVersion << " )";
1457
1458   // Perform Export
1459   PrepareForWriting(file);
1460   char* aMeshName = "Mesh";
1461   SALOMEDS::Study_ptr aStudy = _gen_i->GetCurrentStudy();
1462   if ( !aStudy->_is_nil() ) {
1463     SALOMEDS::SObject_var aMeshSO = _gen_i->ObjectToSObject( aStudy, _this() );
1464     if ( !aMeshSO->_is_nil() ) {
1465       aMeshName = aMeshSO->GetName();
1466       //SCRUTE(file);
1467       //SCRUTE(aMeshName);
1468       //SCRUTE(aMeshSO->GetID());
1469
1470       // asv : 27.10.04 : fix of 6903: check for StudyLocked before adding attributes
1471       if ( !aStudy->GetProperties()->IsLocked() )
1472         {
1473         SALOMEDS::GenericAttribute_var anAttr;
1474         SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
1475         SALOMEDS::AttributeExternalFileDef_var aFileName;
1476         anAttr=aStudyBuilder->FindOrCreateAttribute(aMeshSO, "AttributeExternalFileDef");
1477         aFileName = SALOMEDS::AttributeExternalFileDef::_narrow(anAttr);
1478         ASSERT(!aFileName->_is_nil());
1479         aFileName->SetValue(file);
1480         SALOMEDS::AttributeFileType_var aFileType;
1481         anAttr=aStudyBuilder->FindOrCreateAttribute(aMeshSO, "AttributeFileType");
1482         aFileType = SALOMEDS::AttributeFileType::_narrow(anAttr);
1483         ASSERT(!aFileType->_is_nil());
1484         aFileType->SetValue("FICHIERMED");
1485         }
1486     }
1487   }
1488   _impl->ExportMED( file, aMeshName, auto_groups, theVersion );
1489 }
1490
1491 void SMESH_Mesh_i::ExportMED (const char* file,
1492                               CORBA::Boolean auto_groups)
1493   throw(SALOME::SALOME_Exception)
1494 {
1495   ExportToMED(file,auto_groups,SMESH::MED_V2_1);
1496 }
1497
1498 void SMESH_Mesh_i::ExportDAT (const char *file)
1499   throw(SALOME::SALOME_Exception)
1500 {
1501   Unexpect aCatch(SALOME_SalomeException);
1502
1503   // Update Python script
1504   TPythonDump() << _this() << ".ExportDAT( '" << file << "' )";
1505
1506   // Perform Export
1507   PrepareForWriting(file);
1508   _impl->ExportDAT(file);
1509 }
1510
1511 void SMESH_Mesh_i::ExportUNV (const char *file)
1512   throw(SALOME::SALOME_Exception)
1513 {
1514   Unexpect aCatch(SALOME_SalomeException);
1515
1516   // Update Python script
1517   TPythonDump() << _this() << ".ExportUNV( '" << file << "' )";
1518
1519   // Perform Export
1520   PrepareForWriting(file);
1521   _impl->ExportUNV(file);
1522 }
1523
1524 void SMESH_Mesh_i::ExportSTL (const char *file, const bool isascii)
1525   throw(SALOME::SALOME_Exception)
1526 {
1527   Unexpect aCatch(SALOME_SalomeException);
1528
1529   // Update Python script
1530   TPythonDump() << _this() << ".ExportSTL( '" << file << "', " << isascii << " )";
1531
1532   // Perform Export
1533   PrepareForWriting(file);
1534   _impl->ExportSTL(file, isascii);
1535 }
1536
1537 //=============================================================================
1538 /*!
1539  *
1540  */
1541 //=============================================================================
1542
1543 SALOME_MED::MESH_ptr SMESH_Mesh_i::GetMEDMesh()throw(SALOME::SALOME_Exception)
1544 {
1545   Unexpect aCatch(SALOME_SalomeException);
1546   SMESH_MEDMesh_i *aMedMesh = new SMESH_MEDMesh_i(this);
1547   SALOME_MED::MESH_var aMesh = aMedMesh->_this();
1548   return aMesh._retn();
1549 }
1550
1551 //=============================================================================
1552 /*!
1553  *
1554  */
1555 //=============================================================================
1556 CORBA::Long SMESH_Mesh_i::NbNodes()throw(SALOME::SALOME_Exception)
1557 {
1558   Unexpect aCatch(SALOME_SalomeException);
1559   return _impl->NbNodes();
1560 }
1561
1562 //=============================================================================
1563 /*!
1564  *
1565  */
1566 //=============================================================================
1567 CORBA::Long SMESH_Mesh_i::NbElements()throw (SALOME::SALOME_Exception)
1568 {
1569   Unexpect aCatch(SALOME_SalomeException);
1570   return NbEdges() + NbFaces() + NbVolumes();
1571 }
1572
1573 //=============================================================================
1574 /*!
1575  *
1576  */
1577 //=============================================================================
1578 CORBA::Long SMESH_Mesh_i::NbEdges()throw(SALOME::SALOME_Exception)
1579 {
1580   Unexpect aCatch(SALOME_SalomeException);
1581   return _impl->NbEdges();
1582 }
1583
1584 CORBA::Long SMESH_Mesh_i::NbEdgesOfOrder(SMESH::ElementOrder order)
1585   throw(SALOME::SALOME_Exception)
1586 {
1587   Unexpect aCatch(SALOME_SalomeException);
1588   return _impl->NbEdges( (SMDSAbs_ElementOrder) order);
1589 }
1590
1591 //=============================================================================
1592 /*!
1593  *
1594  */
1595 //=============================================================================
1596 CORBA::Long SMESH_Mesh_i::NbFaces()throw(SALOME::SALOME_Exception)
1597 {
1598   Unexpect aCatch(SALOME_SalomeException);
1599   return _impl->NbFaces();
1600 }
1601
1602 CORBA::Long SMESH_Mesh_i::NbTriangles()throw(SALOME::SALOME_Exception)
1603 {
1604   Unexpect aCatch(SALOME_SalomeException);
1605   return _impl->NbTriangles();
1606 }
1607
1608 CORBA::Long SMESH_Mesh_i::NbQuadrangles()throw(SALOME::SALOME_Exception)
1609 {
1610   Unexpect aCatch(SALOME_SalomeException);
1611   return _impl->NbQuadrangles();
1612 }
1613
1614 CORBA::Long SMESH_Mesh_i::NbPolygons()throw(SALOME::SALOME_Exception)
1615 {
1616   Unexpect aCatch(SALOME_SalomeException);
1617   return _impl->NbPolygons();
1618 }
1619
1620 CORBA::Long SMESH_Mesh_i::NbFacesOfOrder(SMESH::ElementOrder order)
1621   throw(SALOME::SALOME_Exception)
1622 {
1623   Unexpect aCatch(SALOME_SalomeException);
1624   return _impl->NbFaces( (SMDSAbs_ElementOrder) order);
1625 }
1626
1627 CORBA::Long SMESH_Mesh_i::NbTrianglesOfOrder(SMESH::ElementOrder order)
1628   throw(SALOME::SALOME_Exception)
1629 {
1630   Unexpect aCatch(SALOME_SalomeException);
1631   return _impl->NbTriangles( (SMDSAbs_ElementOrder) order);
1632 }
1633
1634 CORBA::Long SMESH_Mesh_i::NbQuadranglesOfOrder(SMESH::ElementOrder order)
1635   throw(SALOME::SALOME_Exception)
1636 {
1637   Unexpect aCatch(SALOME_SalomeException);
1638   return _impl->NbQuadrangles( (SMDSAbs_ElementOrder) order);
1639 }
1640
1641 //=============================================================================
1642 /*!
1643  *
1644  */
1645 //=============================================================================
1646 CORBA::Long SMESH_Mesh_i::NbVolumes()throw(SALOME::SALOME_Exception)
1647 {
1648   Unexpect aCatch(SALOME_SalomeException);
1649   return _impl->NbVolumes();
1650 }
1651
1652 CORBA::Long SMESH_Mesh_i::NbTetras()throw(SALOME::SALOME_Exception)
1653 {
1654   Unexpect aCatch(SALOME_SalomeException);
1655   return _impl->NbTetras();
1656 }
1657
1658 CORBA::Long SMESH_Mesh_i::NbHexas()throw(SALOME::SALOME_Exception)
1659 {
1660   Unexpect aCatch(SALOME_SalomeException);
1661   return _impl->NbHexas();
1662 }
1663
1664 CORBA::Long SMESH_Mesh_i::NbPyramids()throw(SALOME::SALOME_Exception)
1665 {
1666   Unexpect aCatch(SALOME_SalomeException);
1667   return _impl->NbPyramids();
1668 }
1669
1670 CORBA::Long SMESH_Mesh_i::NbPrisms()throw(SALOME::SALOME_Exception)
1671 {
1672   Unexpect aCatch(SALOME_SalomeException);
1673   return _impl->NbPrisms();
1674 }
1675
1676 CORBA::Long SMESH_Mesh_i::NbPolyhedrons()throw(SALOME::SALOME_Exception)
1677 {
1678   Unexpect aCatch(SALOME_SalomeException);
1679   return _impl->NbPolyhedrons();
1680 }
1681
1682 CORBA::Long SMESH_Mesh_i::NbVolumesOfOrder(SMESH::ElementOrder order)
1683   throw(SALOME::SALOME_Exception)
1684 {
1685   Unexpect aCatch(SALOME_SalomeException);
1686   return _impl->NbVolumes( (SMDSAbs_ElementOrder) order);
1687 }
1688
1689 CORBA::Long SMESH_Mesh_i::NbTetrasOfOrder(SMESH::ElementOrder order)
1690   throw(SALOME::SALOME_Exception)
1691 {
1692   Unexpect aCatch(SALOME_SalomeException);
1693   return _impl->NbTetras( (SMDSAbs_ElementOrder) order);
1694 }
1695
1696 CORBA::Long SMESH_Mesh_i::NbHexasOfOrder(SMESH::ElementOrder order)
1697   throw(SALOME::SALOME_Exception)
1698 {
1699   Unexpect aCatch(SALOME_SalomeException);
1700   return _impl->NbHexas( (SMDSAbs_ElementOrder) order);
1701 }
1702
1703 CORBA::Long SMESH_Mesh_i::NbPyramidsOfOrder(SMESH::ElementOrder order)
1704   throw(SALOME::SALOME_Exception)
1705 {
1706   Unexpect aCatch(SALOME_SalomeException);
1707   return _impl->NbPyramids( (SMDSAbs_ElementOrder) order);
1708 }
1709
1710 CORBA::Long SMESH_Mesh_i::NbPrismsOfOrder(SMESH::ElementOrder order)
1711   throw(SALOME::SALOME_Exception)
1712 {
1713   Unexpect aCatch(SALOME_SalomeException);
1714   return _impl->NbPrisms( (SMDSAbs_ElementOrder) order);
1715 }
1716
1717 //=============================================================================
1718 /*!
1719  *
1720  */
1721 //=============================================================================
1722 CORBA::Long SMESH_Mesh_i::NbSubMesh()throw(SALOME::SALOME_Exception)
1723 {
1724   Unexpect aCatch(SALOME_SalomeException);
1725   return _impl->NbSubMesh();
1726 }
1727
1728 //=============================================================================
1729 /*!
1730  *
1731  */
1732 //=============================================================================
1733 char* SMESH_Mesh_i::Dump()
1734 {
1735   std::ostringstream os;
1736   _impl->Dump( os );
1737   return CORBA::string_dup( os.str().c_str() );
1738 }
1739
1740 //=============================================================================
1741 /*!
1742  *
1743  */
1744 //=============================================================================
1745 SMESH::long_array* SMESH_Mesh_i::GetIDs()
1746 {
1747 //   SMESH::long_array_var aResult = new SMESH::long_array();
1748 //   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1749 //   int aMinId = aSMESHDS_Mesh->MinElementID();
1750 //   int aMaxId =  aSMESHDS_Mesh->MaxElementID();
1751
1752 //   aResult->length(aMaxId - aMinId + 1);
1753
1754 //   for (int i = 0, id = aMinId; id <= aMaxId; id++  )
1755 //     aResult[i++] = id;
1756
1757 //   return aResult._retn();
1758   // PAL12398
1759   return GetElementsId();
1760 }
1761
1762 //=============================================================================
1763 /*!
1764  *
1765  */
1766 //=============================================================================
1767
1768 SMESH::long_array* SMESH_Mesh_i::GetElementsId()
1769      throw (SALOME::SALOME_Exception)
1770 {
1771   Unexpect aCatch(SALOME_SalomeException);
1772   MESSAGE("SMESH_Mesh_i::GetElementsId");
1773   SMESH::long_array_var aResult = new SMESH::long_array();
1774   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1775
1776   if ( aSMESHDS_Mesh == NULL )
1777     return aResult._retn();
1778
1779   long nbElements = NbElements();
1780   aResult->length( nbElements );
1781   SMDS_ElemIteratorPtr anIt = aSMESHDS_Mesh->elementsIterator();
1782   for ( int i = 0, n = nbElements; i < n && anIt->more(); i++ )
1783     aResult[i] = anIt->next()->GetID();
1784
1785   return aResult._retn();
1786 }
1787
1788
1789 //=============================================================================
1790 /*!
1791  *
1792  */
1793 //=============================================================================
1794
1795 SMESH::long_array* SMESH_Mesh_i::GetElementsByType( SMESH::ElementType theElemType )
1796     throw (SALOME::SALOME_Exception)
1797 {
1798   Unexpect aCatch(SALOME_SalomeException);
1799   MESSAGE("SMESH_subMesh_i::GetElementsByType");
1800   SMESH::long_array_var aResult = new SMESH::long_array();
1801   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1802
1803   if ( aSMESHDS_Mesh == NULL )
1804     return aResult._retn();
1805
1806   long nbElements = NbElements();
1807
1808   // No sense in returning ids of elements along with ids of nodes:
1809   // when theElemType == SMESH::ALL, return node ids only if
1810   // there are no elements
1811   if ( theElemType == SMESH::NODE || theElemType == SMESH::ALL && nbElements == 0 )
1812     return GetNodesId();
1813
1814   aResult->length( nbElements );
1815
1816   int i = 0;
1817
1818   SMDS_ElemIteratorPtr anIt = aSMESHDS_Mesh->elementsIterator();
1819   while ( i < nbElements && anIt->more() ) {
1820     const SMDS_MeshElement* anElem = anIt->next();
1821     if ( theElemType == SMESH::ALL || anElem->GetType() == (SMDSAbs_ElementType)theElemType )
1822       aResult[i++] = anElem->GetID();
1823   }
1824
1825   aResult->length( i );
1826
1827   return aResult._retn();
1828 }
1829
1830 //=============================================================================
1831 /*!
1832  *
1833  */
1834 //=============================================================================
1835
1836 SMESH::long_array* SMESH_Mesh_i::GetNodesId()
1837   throw (SALOME::SALOME_Exception)
1838 {
1839   Unexpect aCatch(SALOME_SalomeException);
1840   MESSAGE("SMESH_subMesh_i::GetNodesId");
1841   SMESH::long_array_var aResult = new SMESH::long_array();
1842   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1843
1844   if ( aSMESHDS_Mesh == NULL )
1845     return aResult._retn();
1846
1847   long nbNodes = NbNodes();
1848   aResult->length( nbNodes );
1849   SMDS_NodeIteratorPtr anIt = aSMESHDS_Mesh->nodesIterator();
1850   for ( int i = 0, n = nbNodes; i < n && anIt->more(); i++ )
1851     aResult[i] = anIt->next()->GetID();
1852
1853   return aResult._retn();
1854 }
1855
1856 //=============================================================================
1857 /*!
1858  *
1859  */
1860 //=============================================================================
1861
1862 SMESH::ElementType SMESH_Mesh_i::GetElementType( const CORBA::Long id, const bool iselem )
1863   throw (SALOME::SALOME_Exception)
1864 {
1865   return ( SMESH::ElementType )_impl->GetElementType( id, iselem );
1866 }
1867
1868
1869 //=============================================================================
1870 /*!
1871  * Returns ID of elements for given submesh
1872  */
1873 //=============================================================================
1874 SMESH::long_array* SMESH_Mesh_i::GetSubMeshElementsId(const CORBA::Long ShapeID)
1875      throw (SALOME::SALOME_Exception)
1876 {
1877   SMESH::long_array_var aResult = new SMESH::long_array();
1878
1879   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
1880   if(!SM) return aResult._retn();
1881
1882   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
1883   if(!SDSM) return aResult._retn();
1884
1885   aResult->length(SDSM->NbElements());
1886
1887   SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
1888   int i = 0;
1889   while ( eIt->more() ) {
1890     aResult[i++] = eIt->next()->GetID();
1891   }
1892
1893   return aResult._retn();
1894 }
1895
1896
1897 //=============================================================================
1898 /*!
1899  * Returns ID of nodes for given submesh
1900  * If param all==true - returns all nodes, else -
1901  * returns only nodes on shapes.
1902  */
1903 //=============================================================================
1904 SMESH::long_array* SMESH_Mesh_i::GetSubMeshNodesId(const CORBA::Long ShapeID, CORBA::Boolean all)
1905      throw (SALOME::SALOME_Exception)
1906 {
1907   SMESH::long_array_var aResult = new SMESH::long_array();
1908
1909   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
1910   if(!SM) return aResult._retn();
1911
1912   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
1913   if(!SDSM) return aResult._retn();
1914
1915   map<int,const SMDS_MeshElement*> theElems;
1916   if( !all || (SDSM->NbElements()==0 && SDSM->NbNodes()==1) ) {
1917     SMDS_NodeIteratorPtr nIt = SDSM->GetNodes();
1918     while ( nIt->more() ) {
1919       const SMDS_MeshNode* elem = nIt->next();
1920       theElems.insert( make_pair(elem->GetID(),elem) );
1921     }
1922   }
1923   else { // all nodes of submesh elements
1924     SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
1925     while ( eIt->more() ) {
1926       const SMDS_MeshElement* anElem = eIt->next();
1927       SMDS_ElemIteratorPtr nIt = anElem->nodesIterator();
1928       while ( nIt->more() ) {
1929         const SMDS_MeshElement* elem = nIt->next();
1930         theElems.insert( make_pair(elem->GetID(),elem) );
1931       }
1932     }
1933   }
1934
1935   aResult->length(theElems.size());
1936   map<int, const SMDS_MeshElement * >::iterator itElem;
1937   int i = 0;
1938   for ( itElem = theElems.begin(); itElem != theElems.end(); itElem++ )
1939     aResult[i++] = (*itElem).first;
1940
1941   return aResult._retn();
1942 }
1943   
1944
1945 //=============================================================================
1946 /*!
1947  * Returns type of elements for given submesh
1948  */
1949 //=============================================================================
1950 SMESH::ElementType SMESH_Mesh_i::GetSubMeshElementType(const CORBA::Long ShapeID)
1951      throw (SALOME::SALOME_Exception)
1952 {
1953   SMESH_subMesh* SM = _impl->GetSubMeshContaining(ShapeID);
1954   if(!SM) return SMESH::ALL;
1955
1956   SMESHDS_SubMesh* SDSM = SM->GetSubMeshDS();
1957   if(!SDSM) return SMESH::ALL;
1958
1959   if(SDSM->NbElements()==0)
1960     return (SM->GetSubShape().ShapeType() == TopAbs_VERTEX) ? SMESH::NODE : SMESH::ALL;
1961
1962   SMDS_ElemIteratorPtr eIt = SDSM->GetElements();
1963   const SMDS_MeshElement* anElem = eIt->next();
1964   return ( SMESH::ElementType ) anElem->GetType();
1965 }
1966   
1967
1968 //=============================================================================
1969 /*!
1970  *
1971  */
1972 //=============================================================================
1973
1974 CORBA::LongLong SMESH_Mesh_i::GetMeshPtr()
1975 {
1976   CORBA::LongLong pointeur = CORBA::LongLong(_impl);
1977   cerr << "CORBA::LongLong SMESH_Mesh_i::GetMeshPtr() " << pointeur << endl;
1978   return pointeur;
1979 }
1980
1981
1982 //=============================================================================
1983 /*!
1984  * Get XYZ coordinates of node as list of double
1985  * If there is not node for given ID - returns empty list
1986  */
1987 //=============================================================================
1988
1989 SMESH::double_array* SMESH_Mesh_i::GetNodeXYZ(const CORBA::Long id)
1990 {
1991   SMESH::double_array_var aResult = new SMESH::double_array();
1992   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
1993   if ( aSMESHDS_Mesh == NULL )
1994     return aResult._retn();
1995
1996   // find node
1997   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(id);
1998   if(!aNode)
1999     return aResult._retn();
2000
2001   // add coordinates
2002   aResult->length(3);
2003   aResult[0] = aNode->X();
2004   aResult[1] = aNode->Y();
2005   aResult[2] = aNode->Z();
2006   return aResult._retn();
2007 }
2008
2009
2010 //=============================================================================
2011 /*!
2012  * For given node returns list of IDs of inverse elements
2013  * If there is not node for given ID - returns empty list
2014  */
2015 //=============================================================================
2016
2017 SMESH::long_array* SMESH_Mesh_i::GetNodeInverseElements(const CORBA::Long id)
2018 {
2019   SMESH::long_array_var aResult = new SMESH::long_array();
2020   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2021   if ( aSMESHDS_Mesh == NULL )
2022     return aResult._retn();
2023
2024   // find node
2025   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(id);
2026   if(!aNode)
2027     return aResult._retn();
2028
2029   // find inverse elements
2030   SMDS_ElemIteratorPtr eIt = aNode->GetInverseElementIterator();
2031   TColStd_SequenceOfInteger IDs;
2032   while(eIt->more()) {
2033     const SMDS_MeshElement* elem = eIt->next();
2034     IDs.Append(elem->GetID());
2035   }
2036   if(IDs.Length()>0) {
2037     aResult->length(IDs.Length());
2038     int i = 1;
2039     for(; i<=IDs.Length(); i++) {
2040       aResult[i-1] = IDs.Value(i);
2041     }
2042   }
2043   return aResult._retn();
2044 }
2045
2046
2047 //=============================================================================
2048 /*!
2049  * If given element is node returns IDs of shape from position
2050  * If there is not node for given ID - returns -1
2051  */
2052 //=============================================================================
2053
2054 CORBA::Long SMESH_Mesh_i::GetShapeID(const CORBA::Long id)
2055 {
2056   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2057   if ( aSMESHDS_Mesh == NULL )
2058     return -1;
2059
2060   // try to find node
2061   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(id);
2062   if(aNode) {
2063     SMDS_PositionPtr pos = aNode->GetPosition();
2064     if(!pos)
2065       return -1;
2066     else
2067       return pos->GetShapeId();
2068   }
2069
2070   return -1;
2071 }
2072
2073
2074 //=============================================================================
2075 /*!
2076  * For given element returns ID of result shape after 
2077  * ::FindShape() from SMESH_MeshEditor
2078  * If there is not element for given ID - returns -1
2079  */
2080 //=============================================================================
2081
2082 CORBA::Long SMESH_Mesh_i::GetShapeIDForElem(const CORBA::Long id)
2083 {
2084   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2085   if ( aSMESHDS_Mesh == NULL )
2086     return -1;
2087
2088   // try to find element
2089   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2090   if(!elem)
2091     return -1;
2092
2093   //SMESH::SMESH_MeshEditor_var aMeshEditor = SMESH_Mesh_i::GetMeshEditor();
2094   ::SMESH_MeshEditor aMeshEditor(_impl);
2095   int index = aMeshEditor.FindShape( elem );
2096   if(index>0)
2097     return index;
2098
2099   return -1;
2100 }
2101
2102
2103 //=============================================================================
2104 /*!
2105  * Returns number of nodes for given element
2106  * If there is not element for given ID - returns -1
2107  */
2108 //=============================================================================
2109
2110 CORBA::Long SMESH_Mesh_i::GetElemNbNodes(const CORBA::Long id)
2111 {
2112   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2113   if ( aSMESHDS_Mesh == NULL ) return -1;
2114   // try to find element
2115   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2116   if(!elem) return -1;
2117   return elem->NbNodes();
2118 }
2119
2120
2121 //=============================================================================
2122 /*!
2123  * Returns ID of node by given index for given element
2124  * If there is not element for given ID - returns -1
2125  * If there is not node for given index - returns -2
2126  */
2127 //=============================================================================
2128
2129 CORBA::Long SMESH_Mesh_i::GetElemNode(const CORBA::Long id, const CORBA::Long index)
2130 {
2131   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2132   if ( aSMESHDS_Mesh == NULL ) return -1;
2133   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2134   if(!elem) return -1;
2135   if( index>=elem->NbNodes() || index<0 ) return -1;
2136   return elem->GetNode(index)->GetID();
2137 }
2138
2139 //=============================================================================
2140 /*!
2141  * Returns IDs of nodes of given element
2142  */
2143 //=============================================================================
2144
2145 SMESH::long_array* SMESH_Mesh_i::GetElemNodes(const CORBA::Long id)
2146 {
2147   SMESH::long_array_var aResult = new SMESH::long_array();
2148   if ( SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS() )
2149   {
2150     if ( const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id) )
2151     {
2152       aResult->length( elem->NbNodes() );
2153       for ( int i = 0; i < elem->NbNodes(); ++i )
2154         aResult[ i ] = elem->GetNode( i )->GetID();
2155     }
2156   }
2157   return aResult._retn();
2158 }
2159
2160 //=============================================================================
2161 /*!
2162  * Returns true if given node is medium node
2163  * in given quadratic element
2164  */
2165 //=============================================================================
2166
2167 CORBA::Boolean SMESH_Mesh_i::IsMediumNode(const CORBA::Long ide, const CORBA::Long idn)
2168 {
2169   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2170   if ( aSMESHDS_Mesh == NULL ) return false;
2171   // try to find node
2172   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(idn);
2173   if(!aNode) return false;
2174   // try to find element
2175   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(ide);
2176   if(!elem) return false;
2177
2178   return elem->IsMediumNode(aNode);
2179 }
2180
2181
2182 //=============================================================================
2183 /*!
2184  * Returns true if given node is medium node
2185  * in one of quadratic elements
2186  */
2187 //=============================================================================
2188
2189 CORBA::Boolean SMESH_Mesh_i::IsMediumNodeOfAnyElem(const CORBA::Long idn,
2190                                                    SMESH::ElementType theElemType)
2191 {
2192   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2193   if ( aSMESHDS_Mesh == NULL ) return false;
2194
2195   // try to find node
2196   const SMDS_MeshNode* aNode = aSMESHDS_Mesh->FindNode(idn);
2197   if(!aNode) return false;
2198
2199   SMESH_MesherHelper aHelper( *(_impl) );
2200
2201   SMDSAbs_ElementType aType;
2202   if(theElemType==SMESH::EDGE) aType = SMDSAbs_Edge;
2203   else if(theElemType==SMESH::FACE) aType = SMDSAbs_Face;
2204   else if(theElemType==SMESH::VOLUME) aType = SMDSAbs_Volume;
2205   else aType = SMDSAbs_All;
2206
2207   return aHelper.IsMedium(aNode,aType);
2208 }
2209
2210
2211 //=============================================================================
2212 /*!
2213  * Returns number of edges for given element
2214  */
2215 //=============================================================================
2216
2217 CORBA::Long SMESH_Mesh_i::ElemNbEdges(const CORBA::Long id)
2218 {
2219   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2220   if ( aSMESHDS_Mesh == NULL ) return -1;
2221   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2222   if(!elem) return -1;
2223   return elem->NbEdges();
2224 }
2225
2226
2227 //=============================================================================
2228 /*!
2229  * Returns number of faces for given element
2230  */
2231 //=============================================================================
2232
2233 CORBA::Long SMESH_Mesh_i::ElemNbFaces(const CORBA::Long id)
2234 {
2235   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2236   if ( aSMESHDS_Mesh == NULL ) return -1;
2237   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2238   if(!elem) return -1;
2239   return elem->NbFaces();
2240 }
2241
2242
2243 //=============================================================================
2244 /*!
2245  * Returns true if given element is polygon
2246  */
2247 //=============================================================================
2248
2249 CORBA::Boolean SMESH_Mesh_i::IsPoly(const CORBA::Long id)
2250 {
2251   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2252   if ( aSMESHDS_Mesh == NULL ) return false;
2253   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2254   if(!elem) return false;
2255   return elem->IsPoly();
2256 }
2257
2258
2259 //=============================================================================
2260 /*!
2261  * Returns true if given element is quadratic
2262  */
2263 //=============================================================================
2264
2265 CORBA::Boolean SMESH_Mesh_i::IsQuadratic(const CORBA::Long id)
2266 {
2267   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2268   if ( aSMESHDS_Mesh == NULL ) return false;
2269   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2270   if(!elem) return false;
2271   return elem->IsQuadratic();
2272 }
2273
2274
2275 //=============================================================================
2276 /*!
2277  * Returns bary center for given element
2278  */
2279 //=============================================================================
2280
2281 SMESH::double_array* SMESH_Mesh_i::BaryCenter(const CORBA::Long id)
2282 {
2283   SMESH::double_array_var aResult = new SMESH::double_array();
2284   SMESHDS_Mesh* aSMESHDS_Mesh = _impl->GetMeshDS();
2285   if ( aSMESHDS_Mesh == NULL )
2286     return aResult._retn();
2287
2288   const SMDS_MeshElement* elem = aSMESHDS_Mesh->FindElement(id);
2289   if(!elem)
2290     return aResult._retn();
2291
2292   if(elem->GetType()==SMDSAbs_Volume) {
2293     // use SMDS_VolumeTool
2294     SMDS_VolumeTool aTool;
2295     if(aTool.Set(elem)) {
2296       double x=0., y=0., z=0.;
2297       if(aTool.GetBaryCenter(x,y,z)) {
2298         // add coordinates
2299         aResult->length(3);
2300         aResult[0] = x;
2301         aResult[1] = y;
2302         aResult[2] = z;
2303       }
2304     }
2305   }
2306   else {
2307     SMDS_ElemIteratorPtr anIt = elem->nodesIterator();
2308     int nbn = 0;
2309     double x=0., y=0., z=0.;
2310     for(; anIt->more(); ) {
2311       nbn++;
2312       const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>(anIt->next());
2313       x += aNode->X();
2314       y += aNode->Y();
2315       z += aNode->Z();
2316     }
2317     if(nbn>0) {
2318       // add coordinates
2319       aResult->length(3);
2320       aResult[0] = x/nbn;
2321       aResult[1] = y/nbn;
2322       aResult[2] = z/nbn;
2323     }
2324   }
2325
2326   return aResult._retn();
2327 }
2328
2329
2330 //=============================================================================
2331 /*!
2332  *
2333  */
2334 //=============================================================================
2335 void SMESH_Mesh_i::CreateGroupServants() 
2336 {
2337   // Create group servants, if any groups were imported
2338   list<int> aGroupIds = _impl->GetGroupIds();
2339   for ( list<int>::iterator it = aGroupIds.begin(); it != aGroupIds.end(); it++ ) {
2340     SMESH_Group_i* aGroupImpl     = new SMESH_Group_i( SMESH_Gen_i::GetPOA(), this, *it );
2341
2342     // PAL7962: san -- To ensure correct mapping of servant and correct reference counting in GenericObj_i
2343     SMESH_Gen_i::GetPOA()->activate_object( aGroupImpl );
2344     aGroupImpl->Register();
2345     // PAL7962: san -- To ensure correct mapping of servant and correct reference counting in GenericObj_i
2346
2347     SMESH::SMESH_Group_var aGroup = SMESH::SMESH_Group::_narrow( aGroupImpl->_this() );
2348     _mapGroups[*it]               = SMESH::SMESH_Group::_duplicate( aGroup );
2349
2350     // register CORBA object for persistence
2351     int nextId = _gen_i->RegisterObject( aGroup );
2352     if(MYDEBUG) MESSAGE( "Add group to map with id = "<< nextId);
2353   }
2354 }
2355