Salome HOME
Merge branch 'V8_4_BR'
[modules/smesh.git] / src / SMESH / SMESH_MeshEditor.hxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
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     int                               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  (int 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<int> & nodeIDs,
128                                const ElemFeatures&      features);
129
130   int Remove (const std::list< int >& theElemIDs, const bool isNodes);
131   // Remove a node or an element.
132   // Modify a compute state of sub-meshes which become empty
133
134   void Create0DElementsOnAllNodes( const TIDSortedElemSet& elements,
135                                    TIDSortedElemSet&       all0DElems,
136                                    const bool              duplicateElements);
137   // Create 0D elements on all nodes of the given. \a all0DElems returns
138   // all 0D elements found or created on nodes of \a elements
139
140   bool InverseDiag (const SMDS_MeshElement * theTria1,
141                     const SMDS_MeshElement * theTria2 );
142   // Replace two neighbour triangles with ones built on the same 4 nodes
143   // but having other common link.
144   // Return False if args are improper
145
146   bool InverseDiag (const SMDS_MeshNode * theNode1,
147                     const SMDS_MeshNode * theNode2 );
148   // Replace two neighbour triangles sharing theNode1-theNode2 link
149   // with ones built on the same 4 nodes but having other common link.
150   // Return false if proper faces not found
151
152   bool DeleteDiag (const SMDS_MeshNode * theNode1,
153                    const SMDS_MeshNode * theNode2 );
154   // Replace two neighbour triangles sharing theNode1-theNode2 link
155   // with a quadrangle built on the same 4 nodes.
156   // Return false if proper faces not found
157
158   bool Reorient (const SMDS_MeshElement * theElement);
159   // Reverse theElement orientation
160
161   int Reorient2D (TIDSortedElemSet &       theFaces,
162                   const gp_Dir&            theDirection,
163                   const SMDS_MeshElement * theFace);
164   // Reverse theFaces whose orientation to be same as that of theFace
165   // oriented according to theDirection. Return nb of reoriented faces
166
167   int Reorient2DBy3D (TIDSortedElemSet & theFaces,
168                       TIDSortedElemSet & theVolumes,
169                       const bool         theOutsideNormal);
170   // Reorient faces basing on orientation of adjacent volumes.
171   // Return nb of reoriented faces
172
173   /*!
174    * \brief Fuse neighbour triangles into quadrangles.
175    * \param theElems     - The triangles to be fused.
176    * \param theCriterion - Is used to choose a neighbour to fuse with.
177    * \param theMaxAngle  - Is a max angle between element normals at which fusion
178    *                       is still performed; theMaxAngle is measured in radians.
179    * \return bool - Success or not.
180    */
181   bool TriToQuad (TIDSortedElemSet &                   theElems,
182                   SMESH::Controls::NumericalFunctorPtr theCriterion,
183                   const double                         theMaxAngle);
184   /*!
185    * \brief Split quadrangles into triangles.
186    * \param theElems     - The faces to be split.
187    * \param theCriterion - Is used to choose a diagonal for splitting.
188    * \return bool - Success or not.
189    */
190   bool QuadToTri (TIDSortedElemSet &                   theElems,
191                   SMESH::Controls::NumericalFunctorPtr theCriterion);
192   /*!
193    * \brief Split quadrangles into triangles.
194    * \param theElems  - The faces to be split.
195    * \param the13Diag - Is used to choose a diagonal for splitting.
196    * \return bool - Success or not.
197    */
198   bool QuadToTri (TIDSortedElemSet & theElems,
199                   const bool         the13Diag);
200   /*!
201    * \brief Split each of given quadrangles into 4 triangles.
202    * \param theElems - The faces to be split. If empty all faces are split.
203    */
204   void QuadTo4Tri (TIDSortedElemSet & theElems);
205
206   /*!
207    * \brief Find better diagonal for splitting.
208    * \param theQuad      - The face to find better splitting of.
209    * \param theCriterion - Is used to choose a diagonal for splitting.
210    * \return int - 1 for 1-3 diagonal, 2 for 2-4, -1 - for errors.
211    */
212   int BestSplit (const SMDS_MeshElement*              theQuad,
213                  SMESH::Controls::NumericalFunctorPtr theCriterion);
214
215
216   typedef std::map < const SMDS_MeshElement*, int, TIDCompare > TFacetOfElem;
217
218     //!<2nd arg of SplitVolumes()
219   enum SplitVolumToTetraFlags { HEXA_TO_5 = 1, // split into tetrahedra
220                                 HEXA_TO_6,
221                                 HEXA_TO_24,
222                                 HEXA_TO_2_PRISMS, // split into prisms
223                                 HEXA_TO_4_PRISMS };
224   /*!
225    * \brief Split volumic elements into tetrahedra or prisms.
226    *        If facet ID < 0, element is split into tetrahedra,
227    *        else a hexahedron is split into prisms so that the given facet is
228    *        split into triangles
229    */
230   void SplitVolumes (const TFacetOfElem & theElems, const int theMethodFlags);
231
232   /*!
233    * \brief For hexahedra that will be split into prisms, finds facets to
234    *        split into triangles
235    *  \param [in,out] theHexas - the hexahedra
236    *  \param [in]     theFacetNormal - facet normal
237    *  \param [out]    theFacets - the hexahedra and found facet IDs
238    */
239   void GetHexaFacetsToSplit( TIDSortedElemSet& theHexas,
240                              const gp_Ax1&     theFacetNormal,
241                              TFacetOfElem &    theFacets);
242
243   /*!
244    * \brief Split bi-quadratic elements into linear ones without creation of additional nodes
245    *   - bi-quadratic triangle will be split into 3 linear quadrangles;
246    *   - bi-quadratic quadrangle will be split into 4 linear quadrangles;
247    *   - tri-quadratic hexahedron will be split into 8 linear hexahedra;
248    *   Quadratic elements of lower dimension  adjacent to the split bi-quadratic element
249    *   will be split in order to keep the mesh conformal.
250    *  \param elems - elements to split
251    */
252   void SplitBiQuadraticIntoLinear(TIDSortedElemSet& theElems);
253
254   enum SmoothMethod { LAPLACIAN = 0, CENTROIDAL };
255
256   void Smooth (TIDSortedElemSet &               theElements,
257                std::set<const SMDS_MeshNode*> & theFixedNodes,
258                const SmoothMethod               theSmoothMethod,
259                const int                        theNbIterations,
260                double                           theTgtAspectRatio = 1.0,
261                const bool                       the2D = true);
262   // Smooth theElements using theSmoothMethod during theNbIterations
263   // or until a worst element has aspect ratio <= theTgtAspectRatio.
264   // Aspect Ratio varies in range [1.0, inf].
265   // If theElements is empty, the whole mesh is smoothed.
266   // theFixedNodes contains additionally fixed nodes. Nodes built
267   // on edges and boundary nodes are always fixed.
268   // If the2D, smoothing is performed using UV parameters of nodes
269   // on geometrical faces
270
271   typedef TIDTypeCompare TElemSort;
272   typedef std::map < const SMDS_MeshElement*,
273     std::list<const SMDS_MeshElement*>, TElemSort >                        TTElemOfElemListMap;
274   typedef std::map<const SMDS_MeshNode*, std::list<const SMDS_MeshNode*> > TNodeOfNodeListMap;
275   typedef TNodeOfNodeListMap::iterator                                     TNodeOfNodeListMapItr;
276   typedef std::vector<TNodeOfNodeListMapItr>                               TVecOfNnlmiMap;
277   typedef std::map<const SMDS_MeshElement*, TVecOfNnlmiMap, TElemSort >    TElemOfVecOfNnlmiMap;
278   typedef std::auto_ptr< std::list<int> > PGroupIDs;
279
280   PGroupIDs RotationSweep (TIDSortedElemSet   theElements[2],
281                            const gp_Ax1&      theAxis,
282                            const double       theAngle,
283                            const int          theNbSteps,
284                            const double       theToler,
285                            const bool         theMakeGroups,
286                            const bool         theMakeWalls=true);
287   // Generate new elements by rotation of theElements around theAxis
288   // by theAngle by theNbSteps
289
290   /*!
291    * Flags of extrusion.
292    * BOUNDARY: create or not boundary for result of extrusion
293    * SEW:      try to use existing nodes or create new nodes in any case
294    * GROUPS:   to create groups
295    * BY_AVG_NORMAL: step size is measured along average normal to elements,
296    *                else step size is measured along average normal of any element
297    * USE_INPUT_ELEMS_ONLY: to use only input elements to compute extrusion direction
298    *                       for ExtrusionByNormal()
299    * SCALE_LINEAR_VARIATION: to make linear variation of scale factors
300    */
301   enum ExtrusionFlags {
302     EXTRUSION_FLAG_BOUNDARY = 0x01,
303     EXTRUSION_FLAG_SEW = 0x02,
304     EXTRUSION_FLAG_GROUPS = 0x04,
305     EXTRUSION_FLAG_BY_AVG_NORMAL = 0x08,
306     EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY = 0x10,
307     EXTRUSION_FLAG_SCALE_LINEAR_VARIATION = 0x20
308   };
309
310   /*!
311    * Generator of nodes for extrusion functionality
312    */
313   class SMESH_EXPORT ExtrusParam
314   {
315     gp_Dir                          myDir;   // direction of extrusion
316     Handle(TColStd_HSequenceOfReal) mySteps; // magnitudes for each step
317     std::vector<double>             myScales, myMediumScales;// scale factors
318     gp_XYZ                          myBaseP; // scaling center
319     SMESH_SequenceOfNode            myNodes; // nodes for using in sewing
320     int                             myFlags; // see ExtrusionFlags
321     double                          myTolerance; // tolerance for sewing nodes
322     const TIDSortedElemSet*         myElemsToUse; // elements to use for extrusion by normal
323
324     int (ExtrusParam::*myMakeNodesFun)(SMESHDS_Mesh*                     mesh,
325                                        const SMDS_MeshNode*              srcNode,
326                                        std::list<const SMDS_MeshNode*> & newNodes,
327                                        const bool                        makeMediumNodes);
328
329   public:
330     ExtrusParam( const gp_Vec&                   theStep,
331                  const int                       theNbSteps,
332                  const std::list<double>&        theScales,
333                  const gp_XYZ*                   theBaseP,
334                  const int                       theFlags = 0,
335                  const double                    theTolerance = 1e-6);
336     ExtrusParam( const gp_Dir&                   theDir,
337                  Handle(TColStd_HSequenceOfReal) theSteps,
338                  const int                       theFlags = 0,
339                  const double                    theTolerance = 1e-6);
340     ExtrusParam( const double                    theStep,
341                  const int                       theNbSteps,
342                  const int                       theFlags,
343                  const int                       theDim); // for extrusion by normal
344
345     SMESH_SequenceOfNode& ChangeNodes() { return myNodes; }
346     int& Flags()                   { return myFlags; }
347     bool ToMakeBoundary()    const { return myFlags & EXTRUSION_FLAG_BOUNDARY; }
348     bool ToMakeGroups()      const { return myFlags & EXTRUSION_FLAG_GROUPS; }
349     bool ToUseInpElemsOnly() const { return myFlags & EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY; }
350     bool IsLinearVariation() const { return myFlags & EXTRUSION_FLAG_SCALE_LINEAR_VARIATION; }
351     int  NbSteps()           const { return mySteps->Length(); }
352
353     // stores elements to use for extrusion by normal, depending on
354     // state of EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY flag;
355     // define myBaseP for scaling
356     void SetElementsToUse( const TIDSortedElemSet& elems, const TIDSortedElemSet& nodes );
357
358     // creates nodes and returns number of nodes added in \a newNodes
359     int MakeNodes( SMESHDS_Mesh*                     mesh,
360                    const SMDS_MeshNode*              srcNode,
361                    std::list<const SMDS_MeshNode*> & newNodes,
362                    const bool                        makeMediumNodes)
363     {
364       return (this->*myMakeNodesFun)( mesh, srcNode, newNodes, makeMediumNodes );
365     }
366   private:
367
368     int makeNodesByDir( SMESHDS_Mesh*                     mesh,
369                         const SMDS_MeshNode*              srcNode,
370                         std::list<const SMDS_MeshNode*> & newNodes,
371                         const bool                        makeMediumNodes);
372     int makeNodesByDirAndSew( SMESHDS_Mesh*                     mesh,
373                               const SMDS_MeshNode*              srcNode,
374                               std::list<const SMDS_MeshNode*> & newNodes,
375                               const bool                        makeMediumNodes);
376     int makeNodesByNormal2D( SMESHDS_Mesh*                     mesh,
377                              const SMDS_MeshNode*              srcNode,
378                              std::list<const SMDS_MeshNode*> & newNodes,
379                              const bool                        makeMediumNodes);
380     int makeNodesByNormal1D( SMESHDS_Mesh*                     mesh,
381                              const SMDS_MeshNode*              srcNode,
382                              std::list<const SMDS_MeshNode*> & newNodes,
383                              const bool                        makeMediumNodes);
384     // step iteration
385     void   beginStepIter( bool withMediumNodes );
386     bool   moreSteps();
387     double nextStep();
388     std::vector< double > myCurSteps;
389     bool                  myWithMediumNodes;
390     int                   myNextStep;
391   };
392
393   /*!
394    * Generate new elements by extrusion of theElements
395    * It is a method used in .idl file. All functionality
396    * is implemented in the next method (see below) which
397    * is used in the current method.
398    * @param theElems - list of elements for extrusion
399    * @param newElemsMap returns history of extrusion
400    * @param theFlags set flags for performing extrusion (see description
401    *   of enum ExtrusionFlags for additional information)
402    * @param theTolerance - uses for comparing locations of nodes if flag
403    *   EXTRUSION_FLAG_SEW is set
404    */
405   PGroupIDs ExtrusionSweep (TIDSortedElemSet     theElems[2],
406                             const gp_Vec&        theStep,
407                             const int            theNbSteps,
408                             TTElemOfElemListMap& newElemsMap,
409                             const int            theFlags,
410                             const double         theTolerance = 1.e-6);
411   
412   /*!
413    * Generate new elements by extrusion of theElements
414    * @param theElems - list of elements for extrusion
415    * @param newElemsMap returns history of extrusion
416    * @param theFlags set flags for performing extrusion (see description
417    *   of enum ExtrusionFlags for additional information)
418    * @param theTolerance - uses for comparing locations of nodes if flag
419    *   EXTRUSION_FLAG_SEW is set
420    * @param theParams - special structure for manage of extrusion
421    */
422   PGroupIDs ExtrusionSweep (TIDSortedElemSet     theElems[2],
423                             ExtrusParam&         theParams,
424                             TTElemOfElemListMap& newElemsMap);
425
426
427   // Generate new elements by extrusion of theElements 
428   // by theStep by theNbSteps
429
430   enum Extrusion_Error {
431     EXTR_OK,
432     EXTR_NO_ELEMENTS, 
433     EXTR_PATH_NOT_EDGE,
434     EXTR_BAD_PATH_SHAPE,
435     EXTR_BAD_STARTING_NODE,
436     EXTR_BAD_ANGLES_NUMBER,
437     EXTR_CANT_GET_TANGENT
438     };
439   
440   Extrusion_Error ExtrusionAlongTrack (TIDSortedElemSet     theElements[2],
441                                        SMESH_subMesh*       theTrackPattern,
442                                        const SMDS_MeshNode* theNodeStart,
443                                        const bool           theHasAngles,
444                                        std::list<double>&   theAngles,
445                                        const bool           theLinearVariation,
446                                        const bool           theHasRefPoint,
447                                        const gp_Pnt&        theRefPoint,
448                                        const bool           theMakeGroups);
449   Extrusion_Error ExtrusionAlongTrack (TIDSortedElemSet     theElements[2],
450                                        SMESH_Mesh*          theTrackPattern,
451                                        const SMDS_MeshNode* theNodeStart,
452                                        const bool           theHasAngles,
453                                        std::list<double>&   theAngles,
454                                        const bool           theLinearVariation,
455                                        const bool           theHasRefPoint,
456                                        const gp_Pnt&        theRefPoint,
457                                        const bool           theMakeGroups);
458   // Generate new elements by extrusion of theElements along path given by theTrackPattern,
459   // theHasAngles are the rotation angles, base point can be given by theRefPoint
460
461   PGroupIDs Transform (TIDSortedElemSet & theElements,
462                        const gp_Trsf&     theTrsf,
463                        const bool         theCopy,
464                        const bool         theMakeGroups,
465                        SMESH_Mesh*        theTargetMesh=0);
466   // Move or copy theElements applying theTrsf to their nodes
467
468   PGroupIDs Offset( TIDSortedElemSet & theElements,
469                     const double       theValue,
470                     SMESH_Mesh*        theTgtMesh,
471                     const bool         theMakeGroups,
472                     const bool         theFixSelfIntersection);
473   // Make an offset mesh from a source 2D mesh
474
475   typedef std::list< std::list< const SMDS_MeshNode* > > TListOfListOfNodes;
476
477   void FindCoincidentNodes (TIDSortedNodeSet &   theNodes,
478                             const double         theTolerance,
479                             TListOfListOfNodes & theGroupsOfNodes,
480                             bool                 theSeparateCornersAndMedium);
481   // Return list of group of nodes close to each other within theTolerance.
482   // Search among theNodes or in the whole mesh if theNodes is empty.
483
484   void MergeNodes (TListOfListOfNodes & theNodeGroups,
485                    const bool           theAvoidMakingHoles = false);
486   // In each group, the cdr of nodes are substituted by the first one
487   // in all elements.
488
489   typedef std::list< std::list< int > > TListOfListOfElementsID;
490
491   void FindEqualElements(TIDSortedElemSet &        theElements,
492                          TListOfListOfElementsID & theGroupsOfElementsID);
493   // Return list of group of elements build on the same nodes.
494   // Search among theElements or in the whole mesh if theElements is empty.
495
496   void MergeElements(TListOfListOfElementsID & theGroupsOfElementsID);
497   // In each group remove all but first of elements.
498
499   void MergeEqualElements();
500   // Remove all but one of elements built on the same nodes.
501   // Return nb of successfully merged groups.
502
503   int SimplifyFace (const std::vector<const SMDS_MeshNode *>& faceNodes,
504                     std::vector<const SMDS_MeshNode *>&       poly_nodes,
505                     std::vector<int>&                         quantities) const;
506   // Split face, defined by <faceNodes>, into several faces by repeating nodes.
507   // Is used by MergeNodes()
508
509   static bool CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
510                                    const SMDS_MeshNode* theNode2,
511                                    const SMDS_MeshNode* theNode3 = 0);
512   // Return true if the three nodes are on a free border
513
514   static bool FindFreeBorder (const SMDS_MeshNode*                  theFirstNode,
515                               const SMDS_MeshNode*                  theSecondNode,
516                               const SMDS_MeshNode*                  theLastNode,
517                               std::list< const SMDS_MeshNode* > &   theNodes,
518                               std::list< const SMDS_MeshElement* >& theFaces);
519   // Return nodes and faces of a free border if found 
520
521   enum Sew_Error {
522     SEW_OK,
523     // for SewFreeBorder()
524     SEW_BORDER1_NOT_FOUND,
525     SEW_BORDER2_NOT_FOUND,
526     SEW_BOTH_BORDERS_NOT_FOUND,
527     SEW_BAD_SIDE_NODES,
528     SEW_VOLUMES_TO_SPLIT,
529     // for SewSideElements()
530     SEW_DIFF_NB_OF_ELEMENTS,
531     SEW_TOPO_DIFF_SETS_OF_ELEMENTS,
532     SEW_BAD_SIDE1_NODES,
533     SEW_BAD_SIDE2_NODES,
534     SEW_INTERNAL_ERROR
535     };
536     
537
538   Sew_Error SewFreeBorder (const SMDS_MeshNode* theBorderFirstNode,
539                            const SMDS_MeshNode* theBorderSecondNode,
540                            const SMDS_MeshNode* theBorderLastNode,
541                            const SMDS_MeshNode* theSide2FirstNode,
542                            const SMDS_MeshNode* theSide2SecondNode,
543                            const SMDS_MeshNode* theSide2ThirdNode = 0,
544                            const bool           theSide2IsFreeBorder = true,
545                            const bool           toCreatePolygons = false,
546                            const bool           toCreatePolyedrs = false);
547   // Sew the free border to the side2 by replacing nodes in
548   // elements on the free border with nodes of the elements
549   // of the side 2. If nb of links in the free border and
550   // between theSide2FirstNode and theSide2LastNode are different,
551   // additional nodes are inserted on a link provided that no
552   // volume elements share the split link.
553   // The side 2 is a free border if theSide2IsFreeBorder == true.
554   // Sewing is performed between the given first, second and last
555   // nodes on the sides.
556   // theBorderFirstNode is merged with theSide2FirstNode.
557   // if (!theSide2IsFreeBorder) then theSide2SecondNode gives
558   // the last node on the side 2, which will be merged with
559   // theBorderLastNode.
560   // if (theSide2IsFreeBorder) then theSide2SecondNode will
561   // be merged with theBorderSecondNode.
562   // if (theSide2IsFreeBorder && theSide2ThirdNode == 0) then
563   // the 2 free borders are sewn link by link and no additional
564   // nodes are inserted.
565   // Return false, if sewing failed.
566
567   Sew_Error SewSideElements (TIDSortedElemSet&    theSide1,
568                              TIDSortedElemSet&    theSide2,
569                              const SMDS_MeshNode* theFirstNode1ToMerge,
570                              const SMDS_MeshNode* theFirstNode2ToMerge,
571                              const SMDS_MeshNode* theSecondNode1ToMerge,
572                              const SMDS_MeshNode* theSecondNode2ToMerge);
573   // Sew two sides of a mesh. Nodes belonging to theSide1 are
574   // merged with nodes of elements of theSide2.
575   // Number of elements in theSide1 and in theSide2 must be
576   // equal and they should have similar node connectivity.
577   // The nodes to merge should belong to side s borders and
578   // the first node should be linked to the second.
579
580   void InsertNodesIntoLink(const SMDS_MeshElement*          theFace,
581                            const SMDS_MeshNode*             theBetweenNode1,
582                            const SMDS_MeshNode*             theBetweenNode2,
583                            std::list<const SMDS_MeshNode*>& theNodesToInsert,
584                            const bool                       toCreatePoly = false);
585   // insert theNodesToInsert into theFace between theBetweenNode1 and theBetweenNode2.
586   // If toCreatePoly is true, replace theFace by polygon, else split theFace.
587
588   void UpdateVolumes (const SMDS_MeshNode*             theBetweenNode1,
589                       const SMDS_MeshNode*             theBetweenNode2,
590                       std::list<const SMDS_MeshNode*>& theNodesToInsert);
591   // insert theNodesToInsert into all volumes, containing link
592   // theBetweenNode1 - theBetweenNode2, between theBetweenNode1 and theBetweenNode2.
593
594   void ConvertToQuadratic(const bool theForce3d, const bool theToBiQuad);
595   void ConvertToQuadratic(const bool theForce3d,
596                           TIDSortedElemSet& theElements, const bool theToBiQuad);
597   // Converts all mesh to quadratic or bi-quadratic one, deletes old elements, 
598   // replacing them with quadratic or bi-quadratic ones with the same id.
599   // If theForce3d = 1; this results in the medium node lying at the 
600   // middle of the line segments connecting start and end node of a mesh element.
601   // If theForce3d = 0; this results in the medium node lying at the 
602   // geometrical edge from which the mesh element is built.
603
604   bool ConvertFromQuadratic();
605   void ConvertFromQuadratic(TIDSortedElemSet& theElements);
606   // Converts all mesh from quadratic to ordinary ones, deletes old quadratic elements, replacing 
607   // them with ordinary mesh elements with the same id.
608   // Returns true in case of success, false otherwise.
609
610   static void AddToSameGroups (const SMDS_MeshElement* elemToAdd,
611                                const SMDS_MeshElement* elemInGroups,
612                                SMESHDS_Mesh *          aMesh);
613   // Add elemToAdd to the all groups the elemInGroups belongs to
614
615   static void RemoveElemFromGroups (const SMDS_MeshElement* element,
616                                     SMESHDS_Mesh *          aMesh);
617   // remove element from the all groups
618
619   static void ReplaceElemInGroups (const SMDS_MeshElement* elemToRm,
620                                    const SMDS_MeshElement* elemToAdd,
621                                    SMESHDS_Mesh *          aMesh);
622   // replace elemToRm by elemToAdd in the all groups
623
624   static void ReplaceElemInGroups (const SMDS_MeshElement*                     elemToRm,
625                                    const std::vector<const SMDS_MeshElement*>& elemToAdd,
626                                    SMESHDS_Mesh *                              aMesh);
627   // replace elemToRm by elemToAdd in the all groups
628
629   /*!
630    * \brief Return nodes linked to the given one in elements of the type
631    */
632   static void GetLinkedNodes( const SMDS_MeshNode* node,
633                               TIDSortedElemSet &   linkedNodes,
634                               SMDSAbs_ElementType  type = SMDSAbs_All );
635
636   /*!
637    * \brief Find corresponding nodes in two sets of faces 
638     * \param theSide1 - first face set
639     * \param theSide2 - second first face
640     * \param theFirstNode1 - a boundary node of set 1
641     * \param theFirstNode2 - a node of set 2 corresponding to theFirstNode1
642     * \param theSecondNode1 - a boundary node of set 1 linked with theFirstNode1
643     * \param theSecondNode2 - a node of set 2 corresponding to theSecondNode1
644     * \param nReplaceMap - output map of corresponding nodes
645     * \return Sew_Error  - is a success or not
646    */
647   static Sew_Error FindMatchingNodes(std::set<const SMDS_MeshElement*>& theSide1,
648                                      std::set<const SMDS_MeshElement*>& theSide2,
649                                      const SMDS_MeshNode*               theFirstNode1,
650                                      const SMDS_MeshNode*               theFirstNode2,
651                                      const SMDS_MeshNode*               theSecondNode1,
652                                      const SMDS_MeshNode*               theSecondNode2,
653                                      TNodeNodeMap &                     theNodeReplaceMap);
654
655   /*!
656    * \brief Returns true if given node is medium
657     * \param n - node to check
658     * \param typeToCheck - type of elements containing the node to ask about node status
659     * \return bool - check result
660    */
661   static bool IsMedium(const SMDS_MeshNode*      node,
662                        const SMDSAbs_ElementType typeToCheck = SMDSAbs_All);
663
664   int FindShape (const SMDS_MeshElement * theElem);
665   // Return an index of the shape theElem is on
666   // or zero if a shape not found
667
668   void DoubleElements( const TIDSortedElemSet& theElements );
669
670   bool DoubleNodes( const std::list< int >& theListOfNodes, 
671                     const std::list< int >& theListOfModifiedElems );
672   
673   bool DoubleNodes( const TIDSortedElemSet& theElems, 
674                     const TIDSortedElemSet& theNodesNot,
675                     const TIDSortedElemSet& theAffectedElems );
676
677   bool AffectedElemGroupsInRegion( const TIDSortedElemSet& theElems,
678                                    const TIDSortedElemSet& theNodesNot,
679                                    const TopoDS_Shape&     theShape,
680                                    TIDSortedElemSet& theAffectedElems);
681
682   bool DoubleNodesInRegion( const TIDSortedElemSet& theElems, 
683                             const TIDSortedElemSet& theNodesNot,
684                             const TopoDS_Shape&     theShape );
685   
686   double OrientedAngle(const gp_Pnt& p0, const gp_Pnt& p1, const gp_Pnt& g1, const gp_Pnt& g2);
687
688   bool DoubleNodesOnGroupBoundaries( const std::vector<TIDSortedElemSet>& theElems,
689                                      bool                                 createJointElems,
690                                      bool                                 onAllBoundaries);
691
692   bool CreateFlatElementsOnFacesGroups( const std::vector<TIDSortedElemSet>& theElems );
693
694   void CreateHoleSkin(double radius,
695                       const TopoDS_Shape& theShape,
696                       SMESH_NodeSearcher* theNodeSearcher,
697                       const char* groupName,
698                       std::vector<double>&   nodesCoords,
699                       std::vector<std::vector<int> >& listOfListOfNodes);
700
701   /*!
702    * \brief Generated skin mesh (containing 2D cells) from 3D mesh
703    * The created 2D mesh elements based on nodes of free faces of boundary volumes
704    * \return TRUE if operation has been completed successfully, FALSE otherwise
705    */
706   bool Make2DMeshFrom3D();
707
708   enum Bnd_Dimension { BND_2DFROM3D, BND_1DFROM3D, BND_1DFROM2D };
709
710   int MakeBoundaryMesh(const TIDSortedElemSet& elements,
711                        Bnd_Dimension           dimension,
712                        SMESH_Group*            group = 0,
713                        SMESH_Mesh*             targetMesh = 0,
714                        bool                    toCopyElements = false,
715                        bool                    toCopyExistingBondary = false,
716                        bool                    toAddExistingBondary = false,
717                        bool                    aroundElements = false);
718
719
720   // structure used in MakePolyLine() to define a cutting plane
721   struct PolySegment
722   {
723     // 2 points: if myNode2 != 0, then the point is the middle of a face edge defined
724     //           by two nodes, else it is at myNode1
725     const SMDS_MeshNode* myNode1[2];
726     const SMDS_MeshNode* myNode2[2];
727
728     gp_Vec myVector; // vector on the plane; to use a default plane set vector = (0,0,0)
729
730     // point to return coordinates of a middle of the two points, projected to mesh
731     gp_Pnt myMidProjPoint;
732   };
733   typedef std::vector<PolySegment> TListOfPolySegments;
734
735   /*!
736    * \brief Create a polyline consisting of 1D mesh elements each lying on a 2D element of
737    *        the initial mesh. Positions of new nodes are found by cutting the mesh by the
738    *        plane passing through pairs of points specified by each PolySegment structure.
739    *        If there are several paths connecting a pair of points, the shortest path is
740    *        selected by the module. Position of the cutting plane is defined by the two
741    *        points and an optional vector lying on the plane specified by a PolySegment.
742    *        By default the vector is defined by Mesh module as following. A middle point
743    *        of the two given points is computed. The middle point is projected to the mesh.
744    *        The vector goes from the middle point to the projection point. In case of planar
745    *        mesh, the vector is normal to the mesh.
746    *  \param [inout] segments - PolySegment's defining positions of cutting planes.
747    *        Return the used vector and position of the middle point.
748    *  \param [in] group - an optional group where created mesh segments will
749    *        be added.
750    */
751   void MakePolyLine( TListOfPolySegments&   segments,
752                      SMESHDS_Group*         group=0,
753                      SMESH_ElementSearcher* searcher=0);
754
755  private:
756
757   /*!
758    * \brief Convert elements contained in a submesh to quadratic
759    * \return int - nb of checked elements
760    */
761   int convertElemToQuadratic(SMESHDS_SubMesh *   theSm,
762                              SMESH_MesherHelper& theHelper,
763                              const bool          theForce3d);
764
765   /*!
766    * \brief Convert quadratic elements to linear ones and remove quadratic nodes
767    * \return nb of checked elements
768    */
769   int removeQuadElem( SMESHDS_SubMesh *    theSm,
770                       SMDS_ElemIteratorPtr theItr,
771                       const int            theShapeID);
772   /*!
773    * \brief Create groups of elements made during transformation
774    * \param nodeGens - nodes making corresponding myLastCreatedNodes
775    * \param elemGens - elements making corresponding myLastCreatedElems
776    * \param postfix - to append to names of new groups
777    * \param targetMesh - mesh to create groups in
778    * \param topPresent - is there "top" elements that are created by sweeping
779    */
780   PGroupIDs generateGroups(const SMESH_SequenceOfElemPtr& nodeGens,
781                            const SMESH_SequenceOfElemPtr& elemGens,
782                            const std::string&             postfix,
783                            SMESH_Mesh*                    targetMesh=0,
784                            const bool                     topPresent=true);
785   /*!
786    * \brief Create elements by sweeping an element
787    * \param elem - element to sweep
788    * \param newNodesItVec - nodes generated from each node of the element
789    * \param newElems - generated elements
790    * \param nbSteps - number of sweeping steps
791    * \param srcElements - to append elem for each generated element
792    */
793   void sweepElement(const SMDS_MeshElement*                    elem,
794                     const std::vector<TNodeOfNodeListMapItr> & newNodesItVec,
795                     std::list<const SMDS_MeshElement*>&        newElems,
796                     const size_t                               nbSteps,
797                     SMESH_SequenceOfElemPtr&                   srcElements);
798
799   /*!
800    * \brief Computes new connectivity of an element after merging nodes
801    *  \param [in] elems - the element
802    *  \param [out] newElemDefs - definition(s) of result element(s)
803    *  \param [inout] nodeNodeMap - nodes to merge
804    *  \param [in] avoidMakingHoles - if true and and the element becomes invalid
805    *             after merging (but not degenerated), removes nodes causing
806    *             the invalidity from \a nodeNodeMap.
807    *  \return bool - true if the element should be removed
808    */
809   bool applyMerge( const SMDS_MeshElement*      elems,
810                    std::vector< ElemFeatures >& newElemDefs,
811                    TNodeNodeMap&                nodeNodeMap,
812                    const bool                   avoidMakingHoles );
813   /*!
814    * \brief Create 1D and 2D elements around swept elements
815    * \param mapNewNodes - source nodes and ones generated from them
816    * \param newElemsMap - source elements and ones generated from them
817    * \param elemNewNodesMap - nodes generated from each node of each element
818    * \param elemSet - all swept elements
819    * \param nbSteps - number of sweeping steps
820    * \param srcElements - to append elem for each generated element
821    */
822   void makeWalls (TNodeOfNodeListMap &     mapNewNodes,
823                   TTElemOfElemListMap &    newElemsMap,
824                   TElemOfVecOfNnlmiMap &   elemNewNodesMap,
825                   TIDSortedElemSet&        elemSet,
826                   const int                nbSteps,
827                   SMESH_SequenceOfElemPtr& srcElements);
828
829   struct SMESH_MeshEditor_PathPoint
830   {
831     gp_Pnt myPnt;
832     gp_Dir myTgt;
833     double myAngle, myPrm;
834
835     SMESH_MeshEditor_PathPoint(): myPnt(99., 99., 99.), myTgt(1.,0.,0.), myAngle(0), myPrm(0) {}
836     void          SetPnt      (const gp_Pnt& aP3D)  { myPnt  =aP3D; }
837     void          SetTangent  (const gp_Dir& aTgt)  { myTgt  =aTgt; }
838     void          SetAngle    (const double& aBeta) { myAngle=aBeta; }
839     void          SetParameter(const double& aPrm)  { myPrm  =aPrm; }
840     const gp_Pnt& Pnt         ()const               { return myPnt; }
841     const gp_Dir& Tangent     ()const               { return myTgt; }
842     double        Angle       ()const               { return myAngle; }
843     double        Parameter   ()const               { return myPrm; }
844   };
845   Extrusion_Error makeEdgePathPoints(std::list<double>&                     aPrms,
846                                      const TopoDS_Edge&                     aTrackEdge,
847                                      bool                                   aFirstIsStart,
848                                      std::list<SMESH_MeshEditor_PathPoint>& aLPP);
849   Extrusion_Error makeExtrElements(TIDSortedElemSet                       theElements[2],
850                                    std::list<SMESH_MeshEditor_PathPoint>& theFullList,
851                                    const bool                             theHasAngles,
852                                    std::list<double>&                     theAngles,
853                                    const bool                             theLinearVariation,
854                                    const bool                             theHasRefPoint,
855                                    const gp_Pnt&                          theRefPoint,
856                                    const bool                             theMakeGroups);
857   static void linearAngleVariation(const int          NbSteps,
858                                    std::list<double>& theAngles);
859
860   bool doubleNodes( SMESHDS_Mesh*           theMeshDS,
861                     const TIDSortedElemSet& theElems,
862                     const TIDSortedElemSet& theNodesNot,
863                     TNodeNodeMap&           theNodeNodeMap,
864                     const bool              theIsDoubleElem );
865
866   void copyPosition( const SMDS_MeshNode* from,
867                      const SMDS_MeshNode* to );
868
869 private:
870
871   SMESH_Mesh *            myMesh;
872
873   // Nodes and elements created during last operation
874   SMESH_SequenceOfElemPtr myLastCreatedNodes, myLastCreatedElems;
875
876   // Description of error/warning occurred during last operation
877   SMESH_ComputeErrorPtr   myError;
878 };
879
880 #endif