Salome HOME
Update of CheckDone
[modules/smesh.git] / src / SMESH / SMESH_MeshEditor.hxx
1 // Copyright (C) 2007-2024  CEA, EDF, 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
23 // File      : SMESH_MeshEditor.hxx
24 // Created   : Mon Apr 12 14:56:19 2004
25 // Author    : Edward AGAPOV (eap)
26 // Module    : SMESH
27 //
28 #ifndef SMESH_MeshEditor_HeaderFile
29 #define SMESH_MeshEditor_HeaderFile
30
31 #include "SMESH_SMESH.hxx"
32
33 #include "SMESH_Controls.hxx"
34 #include "SMESH_TypeDefs.hxx"
35 #include "SMESH_ComputeError.hxx"
36
37 #include <utilities.h>
38
39 #include <TColStd_HSequenceOfReal.hxx>
40 #include <gp_Dir.hxx>
41
42 #include <list>
43 #include <map>
44 #include <set>
45
46 class SMDS_MeshElement;
47 class SMDS_MeshFace;
48 class SMDS_MeshNode;
49 class SMESHDS_Group;
50 class SMESHDS_Mesh;
51 class SMESHDS_SubMesh;
52 class SMESH_ElementSearcher;
53 class SMESH_Group;
54 class SMESH_Mesh;
55 class SMESH_MesherHelper;
56 class SMESH_NodeSearcher;
57 class SMESH_subMesh;
58 class TopoDS_Edge;
59 class TopoDS_Shape;
60 class TopoDS_Vertex;
61 class gp_Ax1;
62 class gp_Pnt;
63 class gp_Vec;
64
65 // ============================================================
66 /*!
67  * \brief Editor of a mesh
68  */
69 // ============================================================
70
71 class SMESH_EXPORT SMESH_MeshEditor
72 {
73 public:
74
75   SMESH_MeshEditor( SMESH_Mesh* theMesh );
76
77   SMESH_Mesh   *                 GetMesh() { return myMesh; }
78   SMESHDS_Mesh *                 GetMeshDS();
79
80   const SMESH_SequenceOfElemPtr& GetLastCreatedNodes() const { return myLastCreatedNodes; }
81   const SMESH_SequenceOfElemPtr& GetLastCreatedElems() const { return myLastCreatedElems; }
82   void                           ClearLastCreated();
83   SMESH_ComputeErrorPtr &        GetError() { return myError; }
84
85   // --------------------------------------------------------------------------------
86   struct ElemFeatures //!< Features of element to create
87   {
88     SMDSAbs_ElementType               myType;
89     bool                              myIsPoly, myIsQuad;
90     smIdType                          myID;
91     double                            myBallDiameter;
92     std::vector<int>                  myPolyhedQuantities;
93     std::vector<const SMDS_MeshNode*> myNodes; // not managed by ElemFeatures
94
95     SMESH_EXPORT ElemFeatures( SMDSAbs_ElementType type=SMDSAbs_All, bool isPoly=false, bool isQuad=false )
96       :myType( type ), myIsPoly(isPoly), myIsQuad(isQuad), myID(-1), myBallDiameter(0) {}
97
98     SMESH_EXPORT ElemFeatures& Init( SMDSAbs_ElementType type, bool isPoly=false, bool isQuad=false )
99     { myType = type; myIsPoly = isPoly; myIsQuad = isQuad; return *this; }
100
101     SMESH_EXPORT ElemFeatures& Init( const SMDS_MeshElement* elem, bool basicOnly=true );
102
103     SMESH_EXPORT ElemFeatures& Init( double diameter )
104     { myType = SMDSAbs_Ball; myBallDiameter = diameter; return *this; }
105
106     SMESH_EXPORT ElemFeatures& Init( std::vector<int>& quanities, bool isQuad=false )
107     { myType = SMDSAbs_Volume; myIsPoly = 1; myIsQuad = isQuad;
108       myPolyhedQuantities.swap( quanities ); return *this; }
109
110     SMESH_EXPORT ElemFeatures& Init( const std::vector<int>& quanities, bool isQuad=false )
111     { myType = SMDSAbs_Volume; myIsPoly = 1; myIsQuad = isQuad;
112       myPolyhedQuantities = quanities; return *this; }
113
114     SMESH_EXPORT ElemFeatures& SetPoly(bool isPoly) { myIsPoly = isPoly; return *this; }
115     SMESH_EXPORT ElemFeatures& SetQuad(bool isQuad) { myIsQuad = isQuad; return *this; }
116     SMESH_EXPORT ElemFeatures& SetID  (smIdType ID) { myID = ID; return *this; }
117   };
118
119   /*!
120    * \brief Add element
121    */
122   SMDS_MeshElement* AddElement(const std::vector<const SMDS_MeshNode*> & nodes,
123                                const ElemFeatures&                       features);
124   /*!
125    * \brief Add element
126    */
127   SMDS_MeshElement* AddElement(const std::vector<smIdType> & nodeIDs,
128                                const ElemFeatures&           features);
129   /*!
130    * \brief Remove a node and fill a hole appeared by changing surrounding faces
131    */
132   void RemoveNodeWithReconnection( const SMDS_MeshNode* node );
133
134   smIdType Remove (const std::list< smIdType >& theElemIDs, const bool isNodes);
135   // Remove a node or an element.
136   // Modify a compute state of sub-meshes which become empty
137
138   void Create0DElementsOnAllNodes( const TIDSortedElemSet& elements,
139                                    TIDSortedElemSet&       all0DElems,
140                                    const bool              duplicateElements);
141   // Create 0D elements on all nodes of the given. \a all0DElems returns
142   // all 0D elements found or created on nodes of \a elements
143
144   bool InverseDiag (const SMDS_MeshElement * theTria1,
145                     const SMDS_MeshElement * theTria2 );
146   // Replace two neighbour triangles with ones built on the same 4 nodes
147   // but having other common link.
148   // Return False if args are improper
149
150   bool InverseDiag (const SMDS_MeshNode * theNode1,
151                     const SMDS_MeshNode * theNode2 );
152   // Replace two neighbour triangles sharing theNode1-theNode2 link
153   // with ones built on the same 4 nodes but having other common link.
154   // Return false if proper faces not found
155
156   bool DeleteDiag (const SMDS_MeshNode * theNode1,
157                    const SMDS_MeshNode * theNode2 );
158   // Replace two neighbour triangles sharing theNode1-theNode2 link
159   // with a quadrangle built on the same 4 nodes.
160   // Return false if proper faces not found
161
162   void SplitEdge (const SMDS_MeshNode * theNode1,
163                   const SMDS_MeshNode * theNode2,
164                   double                thePosition);
165   // Replace each triangle bound by theNode1-theNode2 link
166   // with two triangles by connecting a node made on the link with a node opposite to the link.
167
168   void SplitFace (const SMDS_MeshElement * theFace,
169                   double                   theX,
170                   double                   theY,
171                   double                   theZ );
172   // Split a face into triangles each formed by two nodes of the face and a new node added
173   // at the given coordinates.
174
175
176   bool Reorient (const SMDS_MeshElement * theElement);
177   // Reverse theElement orientation
178
179   int Reorient2D (TIDSortedElemSet &  theFaces,
180                   const gp_Vec&       theDirection,
181                   TIDSortedElemSet &  theRefFaces,
182                   bool                theAllowNonManifold);
183   // Reverse theFaces whose orientation to be same as that of theRefFaces
184   // optionally oriented according to theDirection. Return nb of reoriented faces
185
186   int Reorient2DBy3D (TIDSortedElemSet & theFaces,
187                       TIDSortedElemSet & theVolumes,
188                       const bool         theOutsideNormal);
189   // Reorient faces basing on orientation of adjacent volumes.
190   // Return nb of reoriented faces
191
192   /*!
193    * \brief Fuse neighbour triangles into quadrangles.
194    * \param theElems     - The triangles to be fused.
195    * \param theCriterion - Is used to choose a neighbour to fuse with.
196    * \param theMaxAngle  - Is a max angle between element normals at which fusion
197    *                       is still performed; theMaxAngle is measured in radians.
198    * \return bool - Success or not.
199    */
200   bool TriToQuad (TIDSortedElemSet &                   theElems,
201                   SMESH::Controls::NumericalFunctorPtr theCriterion,
202                   const double                         theMaxAngle);
203   /*!
204    * \brief Split quadrangles into triangles.
205    * \param theElems     - The faces to be split.
206    * \param theCriterion - Is used to choose a diagonal for splitting.
207    * \return bool - Success or not.
208    */
209   bool QuadToTri (TIDSortedElemSet &                   theElems,
210                   SMESH::Controls::NumericalFunctorPtr theCriterion);
211   /*!
212    * \brief Split quadrangles into triangles.
213    * \param theElems  - The faces to be split.
214    * \param the13Diag - Is used to choose a diagonal for splitting.
215    * \return bool - Success or not.
216    */
217   bool QuadToTri (TIDSortedElemSet & theElems,
218                   const bool         the13Diag);
219   /*!
220    * \brief Split each of given quadrangles into 4 triangles.
221    * \param theElems - The faces to be split. If empty all faces are split.
222    */
223   void QuadTo4Tri (TIDSortedElemSet & theElems);
224
225   /*!
226    * \brief Find better diagonal for splitting.
227    * \param theQuad      - The face to find better splitting of.
228    * \param theCriterion - Is used to choose a diagonal for splitting.
229    * \return int - 1 for 1-3 diagonal, 2 for 2-4, -1 - for errors.
230    */
231   int BestSplit (const SMDS_MeshElement*              theQuad,
232                  SMESH::Controls::NumericalFunctorPtr theCriterion);
233
234
235   typedef std::map < const SMDS_MeshElement*, int, TIDCompare > TFacetOfElem;
236
237     //!<2nd arg of SplitVolumes()
238   enum SplitVolumToTetraFlags { HEXA_TO_5 = 1, // split into tetrahedra
239                                 HEXA_TO_6,
240                                 HEXA_TO_24,
241                                 HEXA_TO_2_PRISMS, // split into prisms
242                                 HEXA_TO_4_PRISMS };
243   /*!
244    * \brief Split volumic elements into tetrahedra or prisms.
245    *        If facet ID < 0, element is split into tetrahedra,
246    *        else a hexahedron is split into prisms so that the given facet is
247    *        split into triangles
248    */
249   void SplitVolumes (const TFacetOfElem & theElems, const int theMethodFlags);
250
251   /*!
252    * \brief For hexahedra that will be split into prisms, finds facets to
253    *        split into triangles
254    *  \param [in,out] theHexas - the hexahedra
255    *  \param [in]     theFacetNormal - facet normal
256    *  \param [out]    theFacets - the hexahedra and found facet IDs
257    */
258   void GetHexaFacetsToSplit( TIDSortedElemSet& theHexas,
259                              const gp_Ax1&     theFacetNormal,
260                              TFacetOfElem &    theFacets);
261
262   /*!
263    * \brief Split bi-quadratic elements into linear ones without creation of additional nodes
264    *   - bi-quadratic triangle will be split into 3 linear quadrangles;
265    *   - bi-quadratic quadrangle will be split into 4 linear quadrangles;
266    *   - tri-quadratic hexahedron will be split into 8 linear hexahedra;
267    *   Quadratic elements of lower dimension  adjacent to the split bi-quadratic element
268    *   will be split in order to keep the mesh conformal.
269    *  \param elems - elements to split
270    */
271   void SplitBiQuadraticIntoLinear(TIDSortedElemSet& theElems);
272
273   enum SmoothMethod { LAPLACIAN = 0, CENTROIDAL };
274
275   void Smooth (TIDSortedElemSet &               theElements,
276                std::set<const SMDS_MeshNode*> & theFixedNodes,
277                const SmoothMethod               theSmoothMethod,
278                const int                        theNbIterations,
279                double                           theTgtAspectRatio = 1.0,
280                const bool                       the2D = true);
281   // Smooth theElements using theSmoothMethod during theNbIterations
282   // or until a worst element has aspect ratio <= theTgtAspectRatio.
283   // Aspect Ratio varies in range [1.0, inf].
284   // If theElements is empty, the whole mesh is smoothed.
285   // theFixedNodes contains additionally fixed nodes. Nodes built
286   // on edges and boundary nodes are always fixed.
287   // If the2D, smoothing is performed using UV parameters of nodes
288   // on geometrical faces
289
290   typedef TIDTypeCompare TElemSort;
291   typedef std::map < const SMDS_MeshElement*,
292     std::list<const SMDS_MeshElement*>, TElemSort >                        TTElemOfElemListMap;
293   typedef std::map<const SMDS_MeshNode*, std::list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
294   typedef TNodeOfNodeListMap::iterator                                     TNodeOfNodeListMapItr;
295   typedef std::vector<TNodeOfNodeListMapItr>                               TVecOfNnlmiMap;
296   typedef std::map<const SMDS_MeshElement*, TVecOfNnlmiMap, TElemSort >    TElemOfVecOfNnlmiMap;
297   typedef std::unique_ptr< std::list< int > >                              PGroupIDs;
298
299   PGroupIDs RotationSweep (TIDSortedElemSet   theElements[2],
300                            const gp_Ax1&      theAxis,
301                            const double       theAngle,
302                            const int          theNbSteps,
303                            const double       theToler,
304                            const bool         theMakeGroups,
305                            const bool         theMakeWalls=true);
306   // Generate new elements by rotation of theElements around theAxis
307   // by theAngle by theNbSteps
308
309   /*!
310    * Flags of extrusion.
311    * BOUNDARY: create or not boundary for result of extrusion
312    * SEW:      try to use existing nodes or create new nodes in any case
313    * GROUPS:   to create groups
314    * BY_AVG_NORMAL: step size is measured along average normal to elements,
315    *                else step size is measured along average normal of any element
316    * USE_INPUT_ELEMS_ONLY: to use only input elements to compute extrusion direction
317    *                       for ExtrusionByNormal()
318    * SCALE_LINEAR_VARIATION: to make linear variation of scale factors
319    * ANGLE_LINEAR_VARIATION: to make linear variation of angles
320    */
321   enum ExtrusionFlags {
322     EXTRUSION_FLAG_BOUNDARY = 0x01,
323     EXTRUSION_FLAG_SEW = 0x02,
324     EXTRUSION_FLAG_GROUPS = 0x04,
325     EXTRUSION_FLAG_BY_AVG_NORMAL = 0x08,
326     EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY = 0x10,
327     EXTRUSION_FLAG_SCALE_LINEAR_VARIATION = 0x20,
328     EXTRUSION_FLAG_ANGLE_LINEAR_VARIATION = 0x40
329   };
330
331   /*!
332    * Generator of nodes for extrusion functionality
333    */
334   class SMESH_EXPORT ExtrusParam
335   {
336   public:
337     //! Point on extrusion path
338     struct PathPoint
339     {
340       gp_Pnt myPnt;
341       gp_Dir myTgt;
342       double myAngle, myScale;
343       PathPoint(): myPnt(99., 99., 99.), myTgt(1.,0.,0.), myAngle(0), myScale(0) {}
344     };
345
346     ExtrusParam( const gp_Vec&                   theStep,
347                  const int                       theNbSteps,
348                  const std::list<double>&        theScales,
349                  const std::list<double>&        theAngles,
350                  const gp_XYZ*                   theBaseP,
351                  const int                       theFlags = 0,
352                  const double                    theTolerance = 1e-6);
353     ExtrusParam( const gp_Dir&                   theDir,
354                  Handle(TColStd_HSequenceOfReal) theSteps,
355                  const int                       theFlags = 0,
356                  const double                    theTolerance = 1e-6);
357     ExtrusParam( const double                    theStep,
358                  const int                       theNbSteps,
359                  const int                       theFlags,
360                  const int                       theDim); // for extrusion by normal
361     ExtrusParam( const std::vector< PathPoint >& thePoints,
362                  const gp_Pnt*                   theBaseP,
363                  const std::list<double>&        theScales,
364                  const bool                      theMakeGroups); // for extrusion along path
365
366     SMESH_SequenceOfNode& ChangeNodes() { return myNodes; }
367     int& Flags()                   { return myFlags; }
368     bool ToMakeBoundary()    const { return myFlags & EXTRUSION_FLAG_BOUNDARY; }
369     bool ToMakeGroups()      const { return myFlags & EXTRUSION_FLAG_GROUPS; }
370     bool ToUseInpElemsOnly() const { return myFlags & EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY; }
371     bool IsScaleVariation()  const { return myFlags & EXTRUSION_FLAG_SCALE_LINEAR_VARIATION; }
372     bool IsAngleVariation()  const { return myFlags & EXTRUSION_FLAG_ANGLE_LINEAR_VARIATION; }
373     int  NbSteps()           const {
374       return mySteps.IsNull() ? (int)myPathPoints.size() - 1: mySteps->Length();
375     }
376     // stores elements to use for extrusion by normal, depending on
377     // state of EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY flag;
378     // define myBaseP for scaling
379     void SetElementsToUse( const TIDSortedElemSet& elems, const TIDSortedElemSet& nodes );
380
381     // creates nodes and returns number of nodes added in \a newNodes
382     int MakeNodes( SMESHDS_Mesh*                     mesh,
383                    const SMDS_MeshNode*              srcNode,
384                    std::list<const SMDS_MeshNode*> & newNodes,
385                    const bool                        makeMediumNodes)
386     {
387       return (this->*myMakeNodesFun)( mesh, srcNode, newNodes, makeMediumNodes );
388     }
389   private:
390
391     gp_Dir                          myDir;   // direction of extrusion
392     Handle(TColStd_HSequenceOfReal) mySteps; // magnitudes for each step
393     std::vector<double>             myScales;// scale factors
394     std::vector<double>             myAngles;// angles
395     gp_XYZ                          myBaseP; // scaling/rotation center
396     SMESH_SequenceOfNode            myNodes; // nodes for using in sewing
397     int                             myFlags; // see ExtrusionFlags
398     double                          myTolerance; // tolerance for sewing nodes
399     const TIDSortedElemSet*         myElemsToUse; // elements to use for extrusion by normal
400     std::vector< PathPoint >        myPathPoints; // points along a path
401     int (ExtrusParam::*             myMakeNodesFun)(SMESHDS_Mesh*, // function of extrusion method
402                                                     const SMDS_MeshNode*,
403                                                     std::list<const SMDS_MeshNode*> &,
404                                                     const bool);
405     int makeNodesByDir( SMESHDS_Mesh*                     mesh,
406                         const SMDS_MeshNode*              srcNode,
407                         std::list<const SMDS_MeshNode*> & newNodes,
408                         const bool                        makeMediumNodes);
409     int makeNodesByDirAndSew( SMESHDS_Mesh*                     mesh,
410                               const SMDS_MeshNode*              srcNode,
411                               std::list<const SMDS_MeshNode*> & newNodes,
412                               const bool                        makeMediumNodes);
413     int makeNodesByNormal2D( SMESHDS_Mesh*                     mesh,
414                              const SMDS_MeshNode*              srcNode,
415                              std::list<const SMDS_MeshNode*> & newNodes,
416                              const bool                        makeMediumNodes);
417     int makeNodesByNormal1D( SMESHDS_Mesh*                     mesh,
418                              const SMDS_MeshNode*              srcNode,
419                              std::list<const SMDS_MeshNode*> & newNodes,
420                              const bool                        makeMediumNodes);
421     int makeNodesAlongTrack( SMESHDS_Mesh*                     mesh,
422                              const SMDS_MeshNode*              srcNode,
423                              std::list<const SMDS_MeshNode*> & newNodes,
424                              const bool                        makeMediumNodes);
425     // step iteration
426     void   beginStepIter( bool withMediumNodes );
427     bool   moreSteps();
428     double nextStep();
429     std::vector< double > myCurSteps;
430     bool                  myWithMediumNodes;
431     int                   myNextStep;
432   };
433
434   /*!
435    * Generate new elements by extrusion of theElements
436    * It is a method used in .idl file. All functionality
437    * is implemented in the next method (see below) which
438    * is used in the current method.
439    * @param theElems - list of elements for extrusion
440    * @param newElemsMap returns history of extrusion
441    * @param theFlags set flags for performing extrusion (see description
442    *   of enum ExtrusionFlags for additional information)
443    * @param theTolerance - uses for comparing locations of nodes if flag
444    *   EXTRUSION_FLAG_SEW is set
445    */
446   PGroupIDs ExtrusionSweep (TIDSortedElemSet     theElems[2],
447                             const gp_Vec&        theStep,
448                             const int            theNbSteps,
449                             TTElemOfElemListMap& newElemsMap,
450                             const int            theFlags,
451                             const double         theTolerance = 1.e-6);
452   
453   /*!
454    * Generate new elements by extrusion of theElements
455    * @param theElems - list of elements for extrusion
456    * @param newElemsMap returns history of extrusion
457    * @param theFlags set flags for performing extrusion (see description
458    *   of enum ExtrusionFlags for additional information)
459    * @param theTolerance - uses for comparing locations of nodes if flag
460    *   EXTRUSION_FLAG_SEW is set
461    * @param theParams - special structure for manage of extrusion
462    */
463   PGroupIDs ExtrusionSweep (TIDSortedElemSet     theElems[2],
464                             ExtrusParam&         theParams,
465                             TTElemOfElemListMap& newElemsMap);
466
467
468   // Generate new elements by extrusion of theElements 
469   // by theStep by theNbSteps
470
471   enum Extrusion_Error {
472     EXTR_OK,
473     EXTR_NO_ELEMENTS, 
474     EXTR_PATH_NOT_EDGE,
475     EXTR_BAD_PATH_SHAPE,
476     EXTR_BAD_STARTING_NODE,
477     EXTR_BAD_ANGLES_NUMBER,
478     EXTR_CANT_GET_TANGENT
479     };
480   
481   Extrusion_Error ExtrusionAlongTrack (TIDSortedElemSet     theElements[2],
482                                        SMESH_Mesh*          theTrackMesh,
483                                        SMDS_ElemIteratorPtr theTrackIterator,
484                                        const SMDS_MeshNode* theNodeStart,
485                                        std::list<double>&   theAngles,
486                                        const bool           theAngleVariation,
487                                        std::list<double>&   theScales,
488                                        const bool           theScaleVariation,
489                                        const gp_Pnt*        theRefPoint,
490                                        const bool           theMakeGroups);
491   // Generate new elements by extrusion of theElements along path given by theTrackIterator,
492   // theHasAngles are the rotation angles, base point can be given by theRefPoint
493
494   PGroupIDs Transform (TIDSortedElemSet & theElements,
495                        const gp_Trsf&     theTrsf,
496                        const bool         theCopy,
497                        const bool         theMakeGroups,
498                        SMESH_Mesh*        theTargetMesh=0);
499   // Move or copy theElements applying theTrsf to their nodes
500
501   PGroupIDs Offset( TIDSortedElemSet & theElements,
502                     const double       theValue,
503                     SMESH_Mesh*        theTgtMesh,
504                     const bool         theMakeGroups,
505                     const bool         theCopyElements,
506                     const bool         theFixSelfIntersection);
507   // Make an offset mesh from a source 2D mesh
508
509   typedef std::list< std::list< const SMDS_MeshNode* > > TListOfListOfNodes;
510
511   void FindCoincidentNodes (TIDSortedNodeSet &   theNodes,
512                             const double         theTolerance,
513                             TListOfListOfNodes & theGroupsOfNodes,
514                             bool                 theSeparateCornersAndMedium);
515   // Return list of group of nodes close to each other within theTolerance.
516   // Search among theNodes or in the whole mesh if theNodes is empty.
517
518   void MergeNodes (TListOfListOfNodes & theNodeGroups,
519                    const bool           theAvoidMakingHoles = false);
520   // In each group, the cdr of nodes are substituted by the first one
521   // in all elements.
522
523   typedef std::list< std::list< smIdType > > TListOfListOfElementsID;
524
525   void FindEqualElements(TIDSortedElemSet &        theElements,
526                          TListOfListOfElementsID & theGroupsOfElementsID);
527   // Return list of group of elements build on the same nodes.
528   // Search among theElements or in the whole mesh if theElements is empty.
529
530   void MergeElements(TListOfListOfElementsID & theGroupsOfElementsID);
531   // In each group remove all but first of elements.
532
533   void MergeEqualElements();
534   // Remove all but one of elements built on the same nodes.
535   // Return nb of successfully merged groups.
536
537   int SimplifyFace (const std::vector<const SMDS_MeshNode *>& faceNodes,
538                     std::vector<const SMDS_MeshNode *>&       poly_nodes,
539                     std::vector<int>&                         quantities) const;
540   // Split face, defined by <faceNodes>, into several faces by repeating nodes.
541   // Is used by MergeNodes()
542
543   static bool CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
544                                    const SMDS_MeshNode* theNode2,
545                                    const SMDS_MeshNode* theNode3 = 0);
546   // Return true if the three nodes are on a free border
547
548   static bool FindFreeBorder (const SMDS_MeshNode*                  theFirstNode,
549                               const SMDS_MeshNode*                  theSecondNode,
550                               const SMDS_MeshNode*                  theLastNode,
551                               std::list< const SMDS_MeshNode* > &   theNodes,
552                               std::list< const SMDS_MeshElement* >& theFaces);
553   // Return nodes and faces of a free border if found 
554
555   enum Sew_Error {
556     SEW_OK,
557     // for SewFreeBorder()
558     SEW_BORDER1_NOT_FOUND,
559     SEW_BORDER2_NOT_FOUND,
560     SEW_BOTH_BORDERS_NOT_FOUND,
561     SEW_BAD_SIDE_NODES,
562     SEW_VOLUMES_TO_SPLIT,
563     // for SewSideElements()
564     SEW_DIFF_NB_OF_ELEMENTS,
565     SEW_TOPO_DIFF_SETS_OF_ELEMENTS,
566     SEW_BAD_SIDE1_NODES,
567     SEW_BAD_SIDE2_NODES,
568     SEW_INTERNAL_ERROR
569     };
570     
571
572   Sew_Error SewFreeBorder (const SMDS_MeshNode* theBorderFirstNode,
573                            const SMDS_MeshNode* theBorderSecondNode,
574                            const SMDS_MeshNode* theBorderLastNode,
575                            const SMDS_MeshNode* theSide2FirstNode,
576                            const SMDS_MeshNode* theSide2SecondNode,
577                            const SMDS_MeshNode* theSide2ThirdNode = 0,
578                            const bool           theSide2IsFreeBorder = true,
579                            const bool           toCreatePolygons = false,
580                            const bool           toCreatePolyedrs = false);
581   // Sew the free border to the side2 by replacing nodes in
582   // elements on the free border with nodes of the elements
583   // of the side 2. If nb of links in the free border and
584   // between theSide2FirstNode and theSide2LastNode are different,
585   // additional nodes are inserted on a link provided that no
586   // volume elements share the split link.
587   // The side 2 is a free border if theSide2IsFreeBorder == true.
588   // Sewing is performed between the given first, second and last
589   // nodes on the sides.
590   // theBorderFirstNode is merged with theSide2FirstNode.
591   // if (!theSide2IsFreeBorder) then theSide2SecondNode gives
592   // the last node on the side 2, which will be merged with
593   // theBorderLastNode.
594   // if (theSide2IsFreeBorder) then theSide2SecondNode will
595   // be merged with theBorderSecondNode.
596   // if (theSide2IsFreeBorder && theSide2ThirdNode == 0) then
597   // the 2 free borders are sewn link by link and no additional
598   // nodes are inserted.
599   // Return false, if sewing failed.
600
601   Sew_Error SewSideElements (TIDSortedElemSet&    theSide1,
602                              TIDSortedElemSet&    theSide2,
603                              const SMDS_MeshNode* theFirstNode1ToMerge,
604                              const SMDS_MeshNode* theFirstNode2ToMerge,
605                              const SMDS_MeshNode* theSecondNode1ToMerge,
606                              const SMDS_MeshNode* theSecondNode2ToMerge);
607   // Sew two sides of a mesh. Nodes belonging to theSide1 are
608   // merged with nodes of elements of theSide2.
609   // Number of elements in theSide1 and in theSide2 must be
610   // equal and they should have similar node connectivity.
611   // The nodes to merge should belong to side s borders and
612   // the first node should be linked to the second.
613
614   void InsertNodesIntoLink(const SMDS_MeshElement*          theFace,
615                            const SMDS_MeshNode*             theBetweenNode1,
616                            const SMDS_MeshNode*             theBetweenNode2,
617                            std::list<const SMDS_MeshNode*>& theNodesToInsert,
618                            const bool                       toCreatePoly = false);
619   // insert theNodesToInsert into theFace between theBetweenNode1 and theBetweenNode2.
620   // If toCreatePoly is true, replace theFace by polygon, else split theFace.
621
622   void UpdateVolumes (const SMDS_MeshNode*             theBetweenNode1,
623                       const SMDS_MeshNode*             theBetweenNode2,
624                       std::list<const SMDS_MeshNode*>& theNodesToInsert);
625   // insert theNodesToInsert into all volumes, containing link
626   // theBetweenNode1 - theBetweenNode2, between theBetweenNode1 and theBetweenNode2.
627
628   void ConvertToQuadratic(const bool theForce3d, const bool theToBiQuad);
629   void ConvertToQuadratic(const bool theForce3d,
630                           TIDSortedElemSet& theElements, const bool theToBiQuad);
631   // Converts all mesh to quadratic or bi-quadratic one, deletes old elements, 
632   // replacing them with quadratic or bi-quadratic ones with the same id.
633   // If theForce3d = 1; this results in the medium node lying at the 
634   // middle of the line segments connecting start and end node of a mesh element.
635   // If theForce3d = 0; this results in the medium node lying at the 
636   // geometrical edge from which the mesh element is built.
637
638   bool ConvertFromQuadratic();
639   void ConvertFromQuadratic(TIDSortedElemSet& theElements);
640   // Converts all mesh from quadratic to ordinary ones, deletes old quadratic elements, replacing 
641   // them with ordinary mesh elements with the same id.
642   // Returns true in case of success, false otherwise.
643
644   static void AddToSameGroups (const SMDS_MeshElement* elemToAdd,
645                                const SMDS_MeshElement* elemInGroups,
646                                SMESHDS_Mesh *          aMesh);
647   // Add elemToAdd to the all groups the elemInGroups belongs to
648
649   static void RemoveElemFromGroups (const SMDS_MeshElement* element,
650                                     SMESHDS_Mesh *          aMesh);
651   // remove element from the all groups
652
653   static void ReplaceElemInGroups (const SMDS_MeshElement* elemToRm,
654                                    const SMDS_MeshElement* elemToAdd,
655                                    SMESHDS_Mesh *          aMesh);
656   // replace elemToRm by elemToAdd in the all groups
657
658   static void ReplaceElemInGroups (const SMDS_MeshElement*                     elemToRm,
659                                    const std::vector<const SMDS_MeshElement*>& elemToAdd,
660                                    SMESHDS_Mesh *                              aMesh);
661   // replace elemToRm by elemToAdd in the all groups
662
663   /*!
664    * \brief Return nodes linked to the given one in elements of the type
665    */
666   static void GetLinkedNodes( const SMDS_MeshNode* node,
667                               TIDSortedElemSet &   linkedNodes,
668                               SMDSAbs_ElementType  type = SMDSAbs_All );
669
670   /*!
671    * \brief Find corresponding nodes in two sets of faces 
672     * \param theSide1 - first face set
673     * \param theSide2 - second first face
674     * \param theFirstNode1 - a boundary node of set 1
675     * \param theFirstNode2 - a node of set 2 corresponding to theFirstNode1
676     * \param theSecondNode1 - a boundary node of set 1 linked with theFirstNode1
677     * \param theSecondNode2 - a node of set 2 corresponding to theSecondNode1
678     * \param nReplaceMap - output map of corresponding nodes
679     * \return Sew_Error  - is a success or not
680    */
681   static Sew_Error FindMatchingNodes(std::set<const SMDS_MeshElement*>& theSide1,
682                                      std::set<const SMDS_MeshElement*>& theSide2,
683                                      const SMDS_MeshNode*               theFirstNode1,
684                                      const SMDS_MeshNode*               theFirstNode2,
685                                      const SMDS_MeshNode*               theSecondNode1,
686                                      const SMDS_MeshNode*               theSecondNode2,
687                                      TNodeNodeMap &                     theNodeReplaceMap);
688
689   /*!
690    * \brief Returns true if given node is medium
691     * \param n - node to check
692     * \param typeToCheck - type of elements containing the node to ask about node status
693     * \return bool - check result
694    */
695   static bool IsMedium(const SMDS_MeshNode*      node,
696                        const SMDSAbs_ElementType typeToCheck = SMDSAbs_All);
697
698   int FindShape (const SMDS_MeshElement * theElem);
699   // Return an index of the shape theElem is on
700   // or zero if a shape not found
701
702   void DoubleElements( const TIDSortedElemSet& theElements );
703
704   bool DoubleNodes( const std::list< int >& theListOfNodes, 
705                     const std::list< int >& theListOfModifiedElems );
706   
707   bool DoubleNodes( const TIDSortedElemSet& theElems, 
708                     const TIDSortedElemSet& theNodesNot,
709                     const TIDSortedElemSet& theAffectedElems );
710
711   bool AffectedElemGroupsInRegion( const TIDSortedElemSet& theElems,
712                                    const TIDSortedElemSet& theNodesNot,
713                                    const TopoDS_Shape&     theShape,
714                                    TIDSortedElemSet& theAffectedElems);
715
716   bool DoubleNodesInRegion( const TIDSortedElemSet& theElems, 
717                             const TIDSortedElemSet& theNodesNot,
718                             const TopoDS_Shape&     theShape );
719   
720   double OrientedAngle(const gp_Pnt& p0, const gp_Pnt& p1, const gp_Pnt& g1, const gp_Pnt& g2);
721
722   bool DoubleNodesOnGroupBoundaries( const std::vector<TIDSortedElemSet>& theElems,
723                                      bool                                 createJointElems,
724                                      bool                                 onAllBoundaries);
725
726   bool CreateFlatElementsOnFacesGroups( const std::vector<TIDSortedElemSet>& theElems );
727
728   void CreateHoleSkin(double radius,
729                       const TopoDS_Shape& theShape,
730                       SMESH_NodeSearcher* theNodeSearcher,
731                       const char* groupName,
732                       std::vector<double>&   nodesCoords,
733                       std::vector<std::vector<int> >& listOfListOfNodes);
734
735   /*!
736    * \brief Generated skin mesh (containing 2D cells) from 3D mesh
737    * The created 2D mesh elements based on nodes of free faces of boundary volumes
738    * \return TRUE if operation has been completed successfully, FALSE otherwise
739    */
740   bool Make2DMeshFrom3D();
741
742   enum Bnd_Dimension { BND_2DFROM3D, BND_1DFROM3D, BND_1DFROM2D };
743
744   int MakeBoundaryMesh(const TIDSortedElemSet& elements,
745                        Bnd_Dimension           dimension,
746                        SMESH_Group*            group = 0,
747                        SMESH_Mesh*             targetMesh = 0,
748                        bool                    toCopyElements = false,
749                        bool                    toCopyExistingBondary = false,
750                        bool                    toAddExistingBondary = false,
751                        bool                    aroundElements = false,
752                        bool                    toCreateAllElements= false);
753
754  private:
755
756   /*!
757    * \brief Convert elements contained in a submesh to quadratic
758    * \return smIdType - nb of checked elements
759    */
760   smIdType convertElemToQuadratic(SMESHDS_SubMesh *   theSm,
761                                   SMESH_MesherHelper& theHelper,
762                                   const bool          theForce3d);
763
764   /*!
765    * \brief Convert quadratic elements to linear ones and remove quadratic nodes
766    * \return nb of checked elements
767    */
768   smIdType removeQuadElem( SMESHDS_SubMesh *    theSm,
769                            SMDS_ElemIteratorPtr theItr,
770                            const int            theShapeID);
771   /*!
772    * \brief Create groups of elements made during transformation
773    * \param nodeGens - nodes making corresponding myLastCreatedNodes
774    * \param elemGens - elements making corresponding myLastCreatedElems
775    * \param postfix - to append to names of new groups
776    * \param targetMesh - mesh to create groups in
777    * \param topPresent - is there "top" elements that are created by sweeping
778    */
779   PGroupIDs generateGroups(const SMESH_SequenceOfElemPtr& nodeGens,
780                            const SMESH_SequenceOfElemPtr& elemGens,
781                            const std::string&             postfix,
782                            SMESH_Mesh*                    targetMesh=0,
783                            const bool                     topPresent=true);
784   /*!
785    * \brief Create elements by sweeping an element
786    * \param elem - element to sweep
787    * \param newNodesItVec - nodes generated from each node of the element
788    * \param newElems - generated elements
789    * \param nbSteps - number of sweeping steps
790    * \param srcElements - to append elem for each generated element
791    */
792   void sweepElement(const SMDS_MeshElement*                    elem,
793                     const std::vector<TNodeOfNodeListMapItr> & newNodesItVec,
794                     std::list<const SMDS_MeshElement*>&        newElems,
795                     const size_t                               nbSteps,
796                     SMESH_SequenceOfElemPtr&                   srcElements);
797
798   /*!
799    * \brief Computes new connectivity of an element after merging nodes
800    *  \param [in] elems - the element
801    *  \param [out] newElemDefs - definition(s) of result element(s)
802    *  \param [inout] nodeNodeMap - nodes to merge
803    *  \param [in] avoidMakingHoles - if true and and the element becomes invalid
804    *             after merging (but not degenerated), removes nodes causing
805    *             the invalidity from \a nodeNodeMap.
806    *  \return bool - true if the element should be removed
807    */
808   bool applyMerge( const SMDS_MeshElement*      elems,
809                    std::vector< ElemFeatures >& newElemDefs,
810                    TNodeNodeMap&                nodeNodeMap,
811                    const bool                   avoidMakingHoles );
812   /*!
813    * \brief Create 1D and 2D elements around swept elements
814    * \param mapNewNodes - source nodes and ones generated from them
815    * \param newElemsMap - source elements and ones generated from them
816    * \param elemNewNodesMap - nodes generated from each node of each element
817    * \param elemSet - all swept elements
818    * \param nbSteps - number of sweeping steps
819    * \param srcElements - to append elem for each generated element
820    */
821   void makeWalls (TNodeOfNodeListMap &     mapNewNodes,
822                   TTElemOfElemListMap &    newElemsMap,
823                   TElemOfVecOfNnlmiMap &   elemNewNodesMap,
824                   TIDSortedElemSet&        elemSet,
825                   const int                nbSteps,
826                   SMESH_SequenceOfElemPtr& srcElements);
827
828   static void linearAngleVariation(const int          NbSteps,
829                                    std::list<double>& theAngles);
830   static void linearScaleVariation(const int          NbSteps,
831                                    std::list<double>& theScales);
832
833   bool doubleNodes( SMESHDS_Mesh*           theMeshDS,
834                     const TIDSortedElemSet& theElems,
835                     const TIDSortedElemSet& theNodesNot,
836                     TNodeNodeMap&           theNodeNodeMap,
837                     const bool              theIsDoubleElem );
838
839   void copyPosition( const SMDS_MeshNode* from,
840                      const SMDS_MeshNode* to );
841
842 private:
843
844   SMESH_Mesh *            myMesh;
845
846   // Nodes and elements created during last operation
847   SMESH_SequenceOfElemPtr myLastCreatedNodes, myLastCreatedElems;
848
849   // Description of error/warning occurred during last operation
850   SMESH_ComputeErrorPtr   myError;
851 };
852
853 #endif