Salome HOME
bos #20256: [CEA 18523] Porting SMESH to int 64 bits
[modules/smesh.git] / src / SMESH / SMESH_MeshEditor.hxx
1 // Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
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   smIdType Remove (const std::list< smIdType >& 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::unique_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    * ANGLE_LINEAR_VARIATION: to make linear variation of angles
301    */
302   enum ExtrusionFlags {
303     EXTRUSION_FLAG_BOUNDARY = 0x01,
304     EXTRUSION_FLAG_SEW = 0x02,
305     EXTRUSION_FLAG_GROUPS = 0x04,
306     EXTRUSION_FLAG_BY_AVG_NORMAL = 0x08,
307     EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY = 0x10,
308     EXTRUSION_FLAG_SCALE_LINEAR_VARIATION = 0x20,
309     EXTRUSION_FLAG_ANGLE_LINEAR_VARIATION = 0x40
310   };
311
312   /*!
313    * Generator of nodes for extrusion functionality
314    */
315   class SMESH_EXPORT ExtrusParam
316   {
317   public:
318     //! Point on extrusion path
319     struct PathPoint
320     {
321       gp_Pnt myPnt;
322       gp_Dir myTgt;
323       double myAngle, myScale;
324       PathPoint(): myPnt(99., 99., 99.), myTgt(1.,0.,0.), myAngle(0), myScale(0) {}
325     };
326
327     ExtrusParam( const gp_Vec&                   theStep,
328                  const int                       theNbSteps,
329                  const std::list<double>&        theScales,
330                  const std::list<double>&        theAngles,
331                  const gp_XYZ*                   theBaseP,
332                  const int                       theFlags = 0,
333                  const double                    theTolerance = 1e-6);
334     ExtrusParam( const gp_Dir&                   theDir,
335                  Handle(TColStd_HSequenceOfReal) theSteps,
336                  const int                       theFlags = 0,
337                  const double                    theTolerance = 1e-6);
338     ExtrusParam( const double                    theStep,
339                  const int                       theNbSteps,
340                  const int                       theFlags,
341                  const int                       theDim); // for extrusion by normal
342     ExtrusParam( const std::vector< PathPoint >& thePoints,
343                  const gp_Pnt*                   theBaseP,
344                  const std::list<double>&        theScales,
345                  const bool                      theMakeGroups); // for extrusion along path
346
347     SMESH_SequenceOfNode& ChangeNodes() { return myNodes; }
348     int& Flags()                   { return myFlags; }
349     bool ToMakeBoundary()    const { return myFlags & EXTRUSION_FLAG_BOUNDARY; }
350     bool ToMakeGroups()      const { return myFlags & EXTRUSION_FLAG_GROUPS; }
351     bool ToUseInpElemsOnly() const { return myFlags & EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY; }
352     bool IsScaleVariation()  const { return myFlags & EXTRUSION_FLAG_SCALE_LINEAR_VARIATION; }
353     bool IsAngleVariation()  const { return myFlags & EXTRUSION_FLAG_ANGLE_LINEAR_VARIATION; }
354     int  NbSteps()           const {
355       return mySteps.IsNull() ? (int)myPathPoints.size() - 1: mySteps->Length();
356     }
357     // stores elements to use for extrusion by normal, depending on
358     // state of EXTRUSION_FLAG_USE_INPUT_ELEMS_ONLY flag;
359     // define myBaseP for scaling
360     void SetElementsToUse( const TIDSortedElemSet& elems, const TIDSortedElemSet& nodes );
361
362     // creates nodes and returns number of nodes added in \a newNodes
363     int MakeNodes( SMESHDS_Mesh*                     mesh,
364                    const SMDS_MeshNode*              srcNode,
365                    std::list<const SMDS_MeshNode*> & newNodes,
366                    const bool                        makeMediumNodes)
367     {
368       return (this->*myMakeNodesFun)( mesh, srcNode, newNodes, makeMediumNodes );
369     }
370   private:
371
372     gp_Dir                          myDir;   // direction of extrusion
373     Handle(TColStd_HSequenceOfReal) mySteps; // magnitudes for each step
374     std::vector<double>             myScales;// scale factors
375     std::vector<double>             myAngles;// angles
376     gp_XYZ                          myBaseP; // scaling/rotation center
377     SMESH_SequenceOfNode            myNodes; // nodes for using in sewing
378     int                             myFlags; // see ExtrusionFlags
379     double                          myTolerance; // tolerance for sewing nodes
380     const TIDSortedElemSet*         myElemsToUse; // elements to use for extrusion by normal
381     std::vector< PathPoint >        myPathPoints; // points along a path
382     int (ExtrusParam::*             myMakeNodesFun)(SMESHDS_Mesh*, // function of extrusion method
383                                                     const SMDS_MeshNode*,
384                                                     std::list<const SMDS_MeshNode*> &,
385                                                     const bool);
386     int makeNodesByDir( SMESHDS_Mesh*                     mesh,
387                         const SMDS_MeshNode*              srcNode,
388                         std::list<const SMDS_MeshNode*> & newNodes,
389                         const bool                        makeMediumNodes);
390     int makeNodesByDirAndSew( SMESHDS_Mesh*                     mesh,
391                               const SMDS_MeshNode*              srcNode,
392                               std::list<const SMDS_MeshNode*> & newNodes,
393                               const bool                        makeMediumNodes);
394     int makeNodesByNormal2D( SMESHDS_Mesh*                     mesh,
395                              const SMDS_MeshNode*              srcNode,
396                              std::list<const SMDS_MeshNode*> & newNodes,
397                              const bool                        makeMediumNodes);
398     int makeNodesByNormal1D( SMESHDS_Mesh*                     mesh,
399                              const SMDS_MeshNode*              srcNode,
400                              std::list<const SMDS_MeshNode*> & newNodes,
401                              const bool                        makeMediumNodes);
402     int makeNodesAlongTrack( SMESHDS_Mesh*                     mesh,
403                              const SMDS_MeshNode*              srcNode,
404                              std::list<const SMDS_MeshNode*> & newNodes,
405                              const bool                        makeMediumNodes);
406     // step iteration
407     void   beginStepIter( bool withMediumNodes );
408     bool   moreSteps();
409     double nextStep();
410     std::vector< double > myCurSteps;
411     bool                  myWithMediumNodes;
412     int                   myNextStep;
413   };
414
415   /*!
416    * Generate new elements by extrusion of theElements
417    * It is a method used in .idl file. All functionality
418    * is implemented in the next method (see below) which
419    * is used in the current method.
420    * @param theElems - list of elements for extrusion
421    * @param newElemsMap returns history of extrusion
422    * @param theFlags set flags for performing extrusion (see description
423    *   of enum ExtrusionFlags for additional information)
424    * @param theTolerance - uses for comparing locations of nodes if flag
425    *   EXTRUSION_FLAG_SEW is set
426    */
427   PGroupIDs ExtrusionSweep (TIDSortedElemSet     theElems[2],
428                             const gp_Vec&        theStep,
429                             const int            theNbSteps,
430                             TTElemOfElemListMap& newElemsMap,
431                             const int            theFlags,
432                             const double         theTolerance = 1.e-6);
433   
434   /*!
435    * Generate new elements by extrusion of theElements
436    * @param theElems - list of elements for extrusion
437    * @param newElemsMap returns history of extrusion
438    * @param theFlags set flags for performing extrusion (see description
439    *   of enum ExtrusionFlags for additional information)
440    * @param theTolerance - uses for comparing locations of nodes if flag
441    *   EXTRUSION_FLAG_SEW is set
442    * @param theParams - special structure for manage of extrusion
443    */
444   PGroupIDs ExtrusionSweep (TIDSortedElemSet     theElems[2],
445                             ExtrusParam&         theParams,
446                             TTElemOfElemListMap& newElemsMap);
447
448
449   // Generate new elements by extrusion of theElements 
450   // by theStep by theNbSteps
451
452   enum Extrusion_Error {
453     EXTR_OK,
454     EXTR_NO_ELEMENTS, 
455     EXTR_PATH_NOT_EDGE,
456     EXTR_BAD_PATH_SHAPE,
457     EXTR_BAD_STARTING_NODE,
458     EXTR_BAD_ANGLES_NUMBER,
459     EXTR_CANT_GET_TANGENT
460     };
461   
462   Extrusion_Error ExtrusionAlongTrack (TIDSortedElemSet     theElements[2],
463                                        SMESH_Mesh*          theTrackMesh,
464                                        SMDS_ElemIteratorPtr theTrackIterator,
465                                        const SMDS_MeshNode* theNodeStart,
466                                        std::list<double>&   theAngles,
467                                        const bool           theAngleVariation,
468                                        std::list<double>&   theScales,
469                                        const bool           theScaleVariation,
470                                        const gp_Pnt*        theRefPoint,
471                                        const bool           theMakeGroups);
472   // Generate new elements by extrusion of theElements along path given by theTrackIterator,
473   // theHasAngles are the rotation angles, base point can be given by theRefPoint
474
475   PGroupIDs Transform (TIDSortedElemSet & theElements,
476                        const gp_Trsf&     theTrsf,
477                        const bool         theCopy,
478                        const bool         theMakeGroups,
479                        SMESH_Mesh*        theTargetMesh=0);
480   // Move or copy theElements applying theTrsf to their nodes
481
482   PGroupIDs Offset( TIDSortedElemSet & theElements,
483                     const double       theValue,
484                     SMESH_Mesh*        theTgtMesh,
485                     const bool         theMakeGroups,
486                     const bool         theCopyElements,
487                     const bool         theFixSelfIntersection);
488   // Make an offset mesh from a source 2D mesh
489
490   typedef std::list< std::list< const SMDS_MeshNode* > > TListOfListOfNodes;
491
492   void FindCoincidentNodes (TIDSortedNodeSet &   theNodes,
493                             const double         theTolerance,
494                             TListOfListOfNodes & theGroupsOfNodes,
495                             bool                 theSeparateCornersAndMedium);
496   // Return list of group of nodes close to each other within theTolerance.
497   // Search among theNodes or in the whole mesh if theNodes is empty.
498
499   void MergeNodes (TListOfListOfNodes & theNodeGroups,
500                    const bool           theAvoidMakingHoles = false);
501   // In each group, the cdr of nodes are substituted by the first one
502   // in all elements.
503
504   typedef std::list< std::list< smIdType > > TListOfListOfElementsID;
505
506   void FindEqualElements(TIDSortedElemSet &        theElements,
507                          TListOfListOfElementsID & theGroupsOfElementsID);
508   // Return list of group of elements build on the same nodes.
509   // Search among theElements or in the whole mesh if theElements is empty.
510
511   void MergeElements(TListOfListOfElementsID & theGroupsOfElementsID);
512   // In each group remove all but first of elements.
513
514   void MergeEqualElements();
515   // Remove all but one of elements built on the same nodes.
516   // Return nb of successfully merged groups.
517
518   int SimplifyFace (const std::vector<const SMDS_MeshNode *>& faceNodes,
519                     std::vector<const SMDS_MeshNode *>&       poly_nodes,
520                     std::vector<int>&                         quantities) const;
521   // Split face, defined by <faceNodes>, into several faces by repeating nodes.
522   // Is used by MergeNodes()
523
524   static bool CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
525                                    const SMDS_MeshNode* theNode2,
526                                    const SMDS_MeshNode* theNode3 = 0);
527   // Return true if the three nodes are on a free border
528
529   static bool FindFreeBorder (const SMDS_MeshNode*                  theFirstNode,
530                               const SMDS_MeshNode*                  theSecondNode,
531                               const SMDS_MeshNode*                  theLastNode,
532                               std::list< const SMDS_MeshNode* > &   theNodes,
533                               std::list< const SMDS_MeshElement* >& theFaces);
534   // Return nodes and faces of a free border if found 
535
536   enum Sew_Error {
537     SEW_OK,
538     // for SewFreeBorder()
539     SEW_BORDER1_NOT_FOUND,
540     SEW_BORDER2_NOT_FOUND,
541     SEW_BOTH_BORDERS_NOT_FOUND,
542     SEW_BAD_SIDE_NODES,
543     SEW_VOLUMES_TO_SPLIT,
544     // for SewSideElements()
545     SEW_DIFF_NB_OF_ELEMENTS,
546     SEW_TOPO_DIFF_SETS_OF_ELEMENTS,
547     SEW_BAD_SIDE1_NODES,
548     SEW_BAD_SIDE2_NODES,
549     SEW_INTERNAL_ERROR
550     };
551     
552
553   Sew_Error SewFreeBorder (const SMDS_MeshNode* theBorderFirstNode,
554                            const SMDS_MeshNode* theBorderSecondNode,
555                            const SMDS_MeshNode* theBorderLastNode,
556                            const SMDS_MeshNode* theSide2FirstNode,
557                            const SMDS_MeshNode* theSide2SecondNode,
558                            const SMDS_MeshNode* theSide2ThirdNode = 0,
559                            const bool           theSide2IsFreeBorder = true,
560                            const bool           toCreatePolygons = false,
561                            const bool           toCreatePolyedrs = false);
562   // Sew the free border to the side2 by replacing nodes in
563   // elements on the free border with nodes of the elements
564   // of the side 2. If nb of links in the free border and
565   // between theSide2FirstNode and theSide2LastNode are different,
566   // additional nodes are inserted on a link provided that no
567   // volume elements share the split link.
568   // The side 2 is a free border if theSide2IsFreeBorder == true.
569   // Sewing is performed between the given first, second and last
570   // nodes on the sides.
571   // theBorderFirstNode is merged with theSide2FirstNode.
572   // if (!theSide2IsFreeBorder) then theSide2SecondNode gives
573   // the last node on the side 2, which will be merged with
574   // theBorderLastNode.
575   // if (theSide2IsFreeBorder) then theSide2SecondNode will
576   // be merged with theBorderSecondNode.
577   // if (theSide2IsFreeBorder && theSide2ThirdNode == 0) then
578   // the 2 free borders are sewn link by link and no additional
579   // nodes are inserted.
580   // Return false, if sewing failed.
581
582   Sew_Error SewSideElements (TIDSortedElemSet&    theSide1,
583                              TIDSortedElemSet&    theSide2,
584                              const SMDS_MeshNode* theFirstNode1ToMerge,
585                              const SMDS_MeshNode* theFirstNode2ToMerge,
586                              const SMDS_MeshNode* theSecondNode1ToMerge,
587                              const SMDS_MeshNode* theSecondNode2ToMerge);
588   // Sew two sides of a mesh. Nodes belonging to theSide1 are
589   // merged with nodes of elements of theSide2.
590   // Number of elements in theSide1 and in theSide2 must be
591   // equal and they should have similar node connectivity.
592   // The nodes to merge should belong to side s borders and
593   // the first node should be linked to the second.
594
595   void InsertNodesIntoLink(const SMDS_MeshElement*          theFace,
596                            const SMDS_MeshNode*             theBetweenNode1,
597                            const SMDS_MeshNode*             theBetweenNode2,
598                            std::list<const SMDS_MeshNode*>& theNodesToInsert,
599                            const bool                       toCreatePoly = false);
600   // insert theNodesToInsert into theFace between theBetweenNode1 and theBetweenNode2.
601   // If toCreatePoly is true, replace theFace by polygon, else split theFace.
602
603   void UpdateVolumes (const SMDS_MeshNode*             theBetweenNode1,
604                       const SMDS_MeshNode*             theBetweenNode2,
605                       std::list<const SMDS_MeshNode*>& theNodesToInsert);
606   // insert theNodesToInsert into all volumes, containing link
607   // theBetweenNode1 - theBetweenNode2, between theBetweenNode1 and theBetweenNode2.
608
609   void ConvertToQuadratic(const bool theForce3d, const bool theToBiQuad);
610   void ConvertToQuadratic(const bool theForce3d,
611                           TIDSortedElemSet& theElements, const bool theToBiQuad);
612   // Converts all mesh to quadratic or bi-quadratic one, deletes old elements, 
613   // replacing them with quadratic or bi-quadratic ones with the same id.
614   // If theForce3d = 1; this results in the medium node lying at the 
615   // middle of the line segments connecting start and end node of a mesh element.
616   // If theForce3d = 0; this results in the medium node lying at the 
617   // geometrical edge from which the mesh element is built.
618
619   bool ConvertFromQuadratic();
620   void ConvertFromQuadratic(TIDSortedElemSet& theElements);
621   // Converts all mesh from quadratic to ordinary ones, deletes old quadratic elements, replacing 
622   // them with ordinary mesh elements with the same id.
623   // Returns true in case of success, false otherwise.
624
625   static void AddToSameGroups (const SMDS_MeshElement* elemToAdd,
626                                const SMDS_MeshElement* elemInGroups,
627                                SMESHDS_Mesh *          aMesh);
628   // Add elemToAdd to the all groups the elemInGroups belongs to
629
630   static void RemoveElemFromGroups (const SMDS_MeshElement* element,
631                                     SMESHDS_Mesh *          aMesh);
632   // remove element from the all groups
633
634   static void ReplaceElemInGroups (const SMDS_MeshElement* elemToRm,
635                                    const SMDS_MeshElement* elemToAdd,
636                                    SMESHDS_Mesh *          aMesh);
637   // replace elemToRm by elemToAdd in the all groups
638
639   static void ReplaceElemInGroups (const SMDS_MeshElement*                     elemToRm,
640                                    const std::vector<const SMDS_MeshElement*>& elemToAdd,
641                                    SMESHDS_Mesh *                              aMesh);
642   // replace elemToRm by elemToAdd in the all groups
643
644   /*!
645    * \brief Return nodes linked to the given one in elements of the type
646    */
647   static void GetLinkedNodes( const SMDS_MeshNode* node,
648                               TIDSortedElemSet &   linkedNodes,
649                               SMDSAbs_ElementType  type = SMDSAbs_All );
650
651   /*!
652    * \brief Find corresponding nodes in two sets of faces 
653     * \param theSide1 - first face set
654     * \param theSide2 - second first face
655     * \param theFirstNode1 - a boundary node of set 1
656     * \param theFirstNode2 - a node of set 2 corresponding to theFirstNode1
657     * \param theSecondNode1 - a boundary node of set 1 linked with theFirstNode1
658     * \param theSecondNode2 - a node of set 2 corresponding to theSecondNode1
659     * \param nReplaceMap - output map of corresponding nodes
660     * \return Sew_Error  - is a success or not
661    */
662   static Sew_Error FindMatchingNodes(std::set<const SMDS_MeshElement*>& theSide1,
663                                      std::set<const SMDS_MeshElement*>& theSide2,
664                                      const SMDS_MeshNode*               theFirstNode1,
665                                      const SMDS_MeshNode*               theFirstNode2,
666                                      const SMDS_MeshNode*               theSecondNode1,
667                                      const SMDS_MeshNode*               theSecondNode2,
668                                      TNodeNodeMap &                     theNodeReplaceMap);
669
670   /*!
671    * \brief Returns true if given node is medium
672     * \param n - node to check
673     * \param typeToCheck - type of elements containing the node to ask about node status
674     * \return bool - check result
675    */
676   static bool IsMedium(const SMDS_MeshNode*      node,
677                        const SMDSAbs_ElementType typeToCheck = SMDSAbs_All);
678
679   int FindShape (const SMDS_MeshElement * theElem);
680   // Return an index of the shape theElem is on
681   // or zero if a shape not found
682
683   void DoubleElements( const TIDSortedElemSet& theElements );
684
685   bool DoubleNodes( const std::list< int >& theListOfNodes, 
686                     const std::list< int >& theListOfModifiedElems );
687   
688   bool DoubleNodes( const TIDSortedElemSet& theElems, 
689                     const TIDSortedElemSet& theNodesNot,
690                     const TIDSortedElemSet& theAffectedElems );
691
692   bool AffectedElemGroupsInRegion( const TIDSortedElemSet& theElems,
693                                    const TIDSortedElemSet& theNodesNot,
694                                    const TopoDS_Shape&     theShape,
695                                    TIDSortedElemSet& theAffectedElems);
696
697   bool DoubleNodesInRegion( const TIDSortedElemSet& theElems, 
698                             const TIDSortedElemSet& theNodesNot,
699                             const TopoDS_Shape&     theShape );
700   
701   double OrientedAngle(const gp_Pnt& p0, const gp_Pnt& p1, const gp_Pnt& g1, const gp_Pnt& g2);
702
703   bool DoubleNodesOnGroupBoundaries( const std::vector<TIDSortedElemSet>& theElems,
704                                      bool                                 createJointElems,
705                                      bool                                 onAllBoundaries);
706
707   bool CreateFlatElementsOnFacesGroups( const std::vector<TIDSortedElemSet>& theElems );
708
709   void CreateHoleSkin(double radius,
710                       const TopoDS_Shape& theShape,
711                       SMESH_NodeSearcher* theNodeSearcher,
712                       const char* groupName,
713                       std::vector<double>&   nodesCoords,
714                       std::vector<std::vector<int> >& listOfListOfNodes);
715
716   /*!
717    * \brief Generated skin mesh (containing 2D cells) from 3D mesh
718    * The created 2D mesh elements based on nodes of free faces of boundary volumes
719    * \return TRUE if operation has been completed successfully, FALSE otherwise
720    */
721   bool Make2DMeshFrom3D();
722
723   enum Bnd_Dimension { BND_2DFROM3D, BND_1DFROM3D, BND_1DFROM2D };
724
725   int MakeBoundaryMesh(const TIDSortedElemSet& elements,
726                        Bnd_Dimension           dimension,
727                        SMESH_Group*            group = 0,
728                        SMESH_Mesh*             targetMesh = 0,
729                        bool                    toCopyElements = false,
730                        bool                    toCopyExistingBondary = false,
731                        bool                    toAddExistingBondary = false,
732                        bool                    aroundElements = false);
733
734  private:
735
736   /*!
737    * \brief Convert elements contained in a submesh to quadratic
738    * \return smIdType - nb of checked elements
739    */
740   smIdType convertElemToQuadratic(SMESHDS_SubMesh *   theSm,
741                                   SMESH_MesherHelper& theHelper,
742                                   const bool          theForce3d);
743
744   /*!
745    * \brief Convert quadratic elements to linear ones and remove quadratic nodes
746    * \return nb of checked elements
747    */
748   smIdType removeQuadElem( SMESHDS_SubMesh *    theSm,
749                            SMDS_ElemIteratorPtr theItr,
750                            const int            theShapeID);
751   /*!
752    * \brief Create groups of elements made during transformation
753    * \param nodeGens - nodes making corresponding myLastCreatedNodes
754    * \param elemGens - elements making corresponding myLastCreatedElems
755    * \param postfix - to append to names of new groups
756    * \param targetMesh - mesh to create groups in
757    * \param topPresent - is there "top" elements that are created by sweeping
758    */
759   PGroupIDs generateGroups(const SMESH_SequenceOfElemPtr& nodeGens,
760                            const SMESH_SequenceOfElemPtr& elemGens,
761                            const std::string&             postfix,
762                            SMESH_Mesh*                    targetMesh=0,
763                            const bool                     topPresent=true);
764   /*!
765    * \brief Create elements by sweeping an element
766    * \param elem - element to sweep
767    * \param newNodesItVec - nodes generated from each node of the element
768    * \param newElems - generated elements
769    * \param nbSteps - number of sweeping steps
770    * \param srcElements - to append elem for each generated element
771    */
772   void sweepElement(const SMDS_MeshElement*                    elem,
773                     const std::vector<TNodeOfNodeListMapItr> & newNodesItVec,
774                     std::list<const SMDS_MeshElement*>&        newElems,
775                     const size_t                               nbSteps,
776                     SMESH_SequenceOfElemPtr&                   srcElements);
777
778   /*!
779    * \brief Computes new connectivity of an element after merging nodes
780    *  \param [in] elems - the element
781    *  \param [out] newElemDefs - definition(s) of result element(s)
782    *  \param [inout] nodeNodeMap - nodes to merge
783    *  \param [in] avoidMakingHoles - if true and and the element becomes invalid
784    *             after merging (but not degenerated), removes nodes causing
785    *             the invalidity from \a nodeNodeMap.
786    *  \return bool - true if the element should be removed
787    */
788   bool applyMerge( const SMDS_MeshElement*      elems,
789                    std::vector< ElemFeatures >& newElemDefs,
790                    TNodeNodeMap&                nodeNodeMap,
791                    const bool                   avoidMakingHoles );
792   /*!
793    * \brief Create 1D and 2D elements around swept elements
794    * \param mapNewNodes - source nodes and ones generated from them
795    * \param newElemsMap - source elements and ones generated from them
796    * \param elemNewNodesMap - nodes generated from each node of each element
797    * \param elemSet - all swept elements
798    * \param nbSteps - number of sweeping steps
799    * \param srcElements - to append elem for each generated element
800    */
801   void makeWalls (TNodeOfNodeListMap &     mapNewNodes,
802                   TTElemOfElemListMap &    newElemsMap,
803                   TElemOfVecOfNnlmiMap &   elemNewNodesMap,
804                   TIDSortedElemSet&        elemSet,
805                   const int                nbSteps,
806                   SMESH_SequenceOfElemPtr& srcElements);
807
808   static void linearAngleVariation(const int          NbSteps,
809                                    std::list<double>& theAngles);
810   static void linearScaleVariation(const int          NbSteps,
811                                    std::list<double>& theScales);
812
813   bool doubleNodes( SMESHDS_Mesh*           theMeshDS,
814                     const TIDSortedElemSet& theElems,
815                     const TIDSortedElemSet& theNodesNot,
816                     TNodeNodeMap&           theNodeNodeMap,
817                     const bool              theIsDoubleElem );
818
819   void copyPosition( const SMDS_MeshNode* from,
820                      const SMDS_MeshNode* to );
821
822 private:
823
824   SMESH_Mesh *            myMesh;
825
826   // Nodes and elements created during last operation
827   SMESH_SequenceOfElemPtr myLastCreatedNodes, myLastCreatedElems;
828
829   // Description of error/warning occurred during last operation
830   SMESH_ComputeErrorPtr   myError;
831 };
832
833 #endif