Salome HOME
NPAL16631: EDF281: Crash on update mesh if computation failed because of memory lack.
[modules/smesh.git] / src / SMESH / SMESH_MeshEditor.hxx
1 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 // File      : SMESH_MeshEditor.hxx
25 // Created   : Mon Apr 12 14:56:19 2004
26 // Author    : Edward AGAPOV (eap)
27 // Module    : SMESH
28
29
30 #ifndef SMESH_MeshEditor_HeaderFile
31 #define SMESH_MeshEditor_HeaderFile
32
33 #include "SMESH_Mesh.hxx"
34 #include "SMESH_Controls.hxx"
35 #include "SMESH_SequenceOfNode.hxx"
36 #include "SMESH_SequenceOfElemPtr.hxx"
37 #include "TColStd_HSequenceOfReal.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMDS_MeshElement.hxx"
40
41 #include <gp_Dir.hxx>
42
43 #include <list>
44 #include <map>
45
46 typedef std::map<const SMDS_MeshElement*,
47                  std::list<const SMDS_MeshElement*> >        TElemOfElemListMap;
48 typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*> TNodeNodeMap;
49
50 class SMDS_MeshFace;
51 class SMDS_MeshNode;
52 class gp_Ax1;
53 class gp_Vec;
54 class gp_Pnt;
55
56 // ============================================================
57 /*!
58  * \brief Set of elements sorted by ID, to be used to assure
59  *  predictability of edition
60  */
61 // ============================================================
62
63 template < class TMeshElem = SMDS_MeshElement>
64 struct TIDCompare {
65   bool operator () (const TMeshElem* e1, const TMeshElem* e2) const
66   { return e1->GetID() < e2->GetID(); }
67 };
68 typedef std::set< const SMDS_MeshElement*, TIDCompare< SMDS_MeshElement> > TIDSortedElemSet;
69
70 // ============================================================
71 /*!
72  * \brief Searcher for the node closest to point
73  */
74 // ============================================================
75
76 struct SMESH_NodeSearcher
77 {
78   virtual const SMDS_MeshNode* FindClosestTo( const gp_Pnt& pnt ) = 0;
79 };
80
81 // ============================================================
82 /*!
83  * \brief Editor of a mesh
84  */
85 // ============================================================
86
87 class SMESH_MeshEditor {
88
89 public:
90
91   SMESH_MeshEditor( SMESH_Mesh* theMesh );
92
93   /*!
94    * \brief Add element
95    */
96   SMDS_MeshElement* AddElement(const std::vector<const SMDS_MeshNode*> & nodes,
97                                const SMDSAbs_ElementType                 type,
98                                const bool                                isPoly,
99                                const int                                 ID = 0);
100   /*!
101    * \brief Add element
102    */
103   SMDS_MeshElement* AddElement(const std::vector<int>  & nodeIDs,
104                                const SMDSAbs_ElementType type,
105                                const bool                isPoly,
106                                const int                 ID = 0);
107
108   bool Remove (const std::list< int >& theElemIDs, const bool isNodes);
109   // Remove a node or an element.
110   // Modify a compute state of sub-meshes which become empty
111
112   bool InverseDiag (const SMDS_MeshElement * theTria1,
113                     const SMDS_MeshElement * theTria2 );
114   // Replace two neighbour triangles with ones built on the same 4 nodes
115   // but having other common link.
116   // Return False if args are improper
117
118   bool InverseDiag (const SMDS_MeshNode * theNode1,
119                     const SMDS_MeshNode * theNode2 );
120   // Replace two neighbour triangles sharing theNode1-theNode2 link
121   // with ones built on the same 4 nodes but having other common link.
122   // Return false if proper faces not found
123
124   bool DeleteDiag (const SMDS_MeshNode * theNode1,
125                    const SMDS_MeshNode * theNode2 );
126   // Replace two neighbour triangles sharing theNode1-theNode2 link
127   // with a quadrangle built on the same 4 nodes.
128   // Return false if proper faces not found
129
130   bool Reorient (const SMDS_MeshElement * theElement);
131   // Reverse theElement orientation
132
133
134   /*!
135    * \brief Fuse neighbour triangles into quadrangles.
136    * \param theElems     - The triangles to be fused.
137    * \param theCriterion - Is used to choose a neighbour to fuse with.
138    * \param theMaxAngle  - Is a max angle between element normals at which fusion
139    *                       is still performed; theMaxAngle is mesured in radians.
140    * \retval bool - Success or not.
141    */
142   bool TriToQuad (TIDSortedElemSet &                   theElems,
143                   SMESH::Controls::NumericalFunctorPtr theCriterion,
144                   const double                         theMaxAngle);
145
146   /*!
147    * \brief Split quadrangles into triangles.
148    * \param theElems     - The faces to be splitted.
149    * \param theCriterion - Is used to choose a diagonal for splitting.
150    * \retval bool - Success or not.
151    */
152   bool QuadToTri (TIDSortedElemSet &                   theElems,
153                   SMESH::Controls::NumericalFunctorPtr theCriterion);
154
155   /*!
156    * \brief Split quadrangles into triangles.
157    * \param theElems  - The faces to be splitted.
158    * \param the13Diag - Is used to choose a diagonal for splitting.
159    * \retval bool - Success or not.
160    */
161   bool QuadToTri (TIDSortedElemSet & theElems,
162                   const bool         the13Diag);
163
164   /*!
165    * \brief Find better diagonal for splitting.
166    * \param theQuad      - The face to find better splitting of.
167    * \param theCriterion - Is used to choose a diagonal for splitting.
168    * \retval int - 1 for 1-3 diagonal, 2 for 2-4, -1 - for errors.
169    */
170   int BestSplit (const SMDS_MeshElement*              theQuad,
171                  SMESH::Controls::NumericalFunctorPtr theCriterion);
172
173
174   enum SmoothMethod { LAPLACIAN = 0, CENTROIDAL };
175
176   void Smooth (TIDSortedElemSet &               theElements,
177                std::set<const SMDS_MeshNode*> & theFixedNodes,
178                const SmoothMethod               theSmoothMethod,
179                const int                        theNbIterations,
180                double                           theTgtAspectRatio = 1.0,
181                const bool                       the2D = true);
182   // Smooth theElements using theSmoothMethod during theNbIterations
183   // or until a worst element has aspect ratio <= theTgtAspectRatio.
184   // Aspect Ratio varies in range [1.0, inf].
185   // If theElements is empty, the whole mesh is smoothed.
186   // theFixedNodes contains additionally fixed nodes. Nodes built
187   // on edges and boundary nodes are always fixed.
188   // If the2D, smoothing is performed using UV parameters of nodes
189   // on geometrical faces
190
191
192   void RotationSweep (TIDSortedElemSet & theElements,
193                       const gp_Ax1&      theAxis,
194                       const double       theAngle,
195                       const int          theNbSteps,
196                       const double       theToler,
197                       const bool         theMakeWalls=true);
198   // Generate new elements by rotation of theElements around theAxis
199   // by theAngle by theNbSteps
200
201   /*!
202    * Auxilary flag for advanced extrusion.
203    * BOUNDARY: create or not boundary for result of extrusion
204    * SEW:      try to use existing nodes or create new nodes in any case
205    */
206   enum ExtrusionFlags {
207     EXTRUSION_FLAG_BOUNDARY = 0x01,
208     EXTRUSION_FLAG_SEW = 0x02
209   };
210   
211   /*!
212    * special structire for control of extrusion functionality
213    */
214   struct ExtrusParam {
215     gp_Dir myDir; // direction of extrusion
216     Handle(TColStd_HSequenceOfReal) mySteps; // magnitudes for each step
217     SMESH_SequenceOfNode myNodes; // nodes for using in sewing
218   };
219
220   /*!
221    * Create new node in the mesh with given coordinates
222    * (auxilary for advanced extrusion)
223    */
224   const SMDS_MeshNode* CreateNode(const double x,
225                                   const double y,
226                                   const double z,
227                                   const double tolnode,
228                                   SMESH_SequenceOfNode& aNodes);
229
230   /*!
231    * Generate new elements by extrusion of theElements
232    * It is a method used in .idl file. All functionality
233    * is implemented in the next method (see below) which
234    * is used in the cuurent method.
235    * param theElems - list of elements for extrusion
236    * param newElemsMap returns history of extrusion
237    * param theFlags set flags for performing extrusion (see description
238    *   of enum ExtrusionFlags for additional information)
239    * param theTolerance - uses for comparing locations of nodes if flag
240    *   EXTRUSION_FLAG_SEW is set
241    */
242   void ExtrusionSweep
243            (TIDSortedElemSet &  theElems,
244             const gp_Vec&       theStep,
245             const int           theNbSteps,
246             TElemOfElemListMap& newElemsMap,
247             const int           theFlags = EXTRUSION_FLAG_BOUNDARY,
248             const double        theTolerance = 1.e-6);
249   
250   /*!
251    * Generate new elements by extrusion of theElements
252    * param theElems - list of elements for extrusion
253    * param newElemsMap returns history of extrusion
254    * param theFlags set flags for performing extrusion (see description
255    *   of enum ExtrusionFlags for additional information)
256    * param theTolerance - uses for comparing locations of nodes if flag
257    *   EXTRUSION_FLAG_SEW is set
258    * param theParams - special structure for manage of extrusion
259    */
260   void ExtrusionSweep (TIDSortedElemSet &  theElems,
261                        ExtrusParam&        theParams,
262                        TElemOfElemListMap& newElemsMap,
263                        const int           theFlags,
264                        const double        theTolerance);
265
266
267   // Generate new elements by extrusion of theElements 
268   // by theStep by theNbSteps
269
270   enum Extrusion_Error {
271     EXTR_OK,
272     EXTR_NO_ELEMENTS, 
273     EXTR_PATH_NOT_EDGE,
274     EXTR_BAD_PATH_SHAPE,
275     EXTR_BAD_STARTING_NODE,
276     EXTR_BAD_ANGLES_NUMBER,
277     EXTR_CANT_GET_TANGENT
278     };
279   
280   Extrusion_Error ExtrusionAlongTrack (TIDSortedElemSet &   theElements,
281                                        SMESH_subMesh*       theTrackPattern,
282                                        const SMDS_MeshNode* theNodeStart,
283                                        const bool           theHasAngles,
284                                        std::list<double>&   theAngles,
285                                        const bool           theHasRefPoint,
286                                        const gp_Pnt&        theRefPoint);
287   // Generate new elements by extrusion of theElements along path given by theTrackPattern,
288   // theHasAngles are the rotation angles, base point can be given by theRefPoint
289
290   void Transform (TIDSortedElemSet & theElements,
291                   const gp_Trsf&     theTrsf,
292                   const bool         theCopy);
293   // Move or copy theElements applying theTrsf to their nodes
294
295   typedef std::list< std::list< const SMDS_MeshNode* > > TListOfListOfNodes;
296
297   void FindCoincidentNodes (std::set<const SMDS_MeshNode*> & theNodes,
298                             const double                     theTolerance,
299                             TListOfListOfNodes &             theGroupsOfNodes);
300   // Return list of group of nodes close to each other within theTolerance.
301   // Search among theNodes or in the whole mesh if theNodes is empty.
302
303   /*!
304    * \brief Return SMESH_NodeSearcher
305    */
306   SMESH_NodeSearcher* GetNodeSearcher();
307
308   int SimplifyFace (const vector<const SMDS_MeshNode *> faceNodes,
309                     vector<const SMDS_MeshNode *>&      poly_nodes,
310                     vector<int>&                        quantities) const;
311   // Split face, defined by <faceNodes>, into several faces by repeating nodes.
312   // Is used by MergeNodes()
313
314   void MergeNodes (TListOfListOfNodes & theNodeGroups);
315   // In each group, the cdr of nodes are substituted by the first one
316   // in all elements.
317
318   typedef std::list< std::list< int > > TListOfListOfElementsID;
319
320   void FindEqualElements(std::set<const SMDS_MeshElement*> & theElements,
321                          TListOfListOfElementsID &           theGroupsOfElementsID);
322   // Return list of group of elements build on the same nodes.
323   // Search among theElements or in the whole mesh if theElements is empty.
324
325   void MergeElements(TListOfListOfElementsID & theGroupsOfElementsID);
326   // In each group remove all but first of elements.
327
328   void MergeEqualElements();
329   // Remove all but one of elements built on the same nodes.
330   // Return nb of successfully merged groups.
331
332   static bool CheckFreeBorderNodes(const SMDS_MeshNode* theNode1,
333                                    const SMDS_MeshNode* theNode2,
334                                    const SMDS_MeshNode* theNode3 = 0);
335   // Return true if the three nodes are on a free border
336
337   static bool FindFreeBorder (const SMDS_MeshNode*                  theFirstNode,
338                               const SMDS_MeshNode*                  theSecondNode,
339                               const SMDS_MeshNode*                  theLastNode,
340                               std::list< const SMDS_MeshNode* > &   theNodes,
341                               std::list< const SMDS_MeshElement* >& theFaces);
342   // Return nodes and faces of a free border if found 
343
344   enum Sew_Error {
345     SEW_OK,
346     // for SewFreeBorder()
347     SEW_BORDER1_NOT_FOUND,
348     SEW_BORDER2_NOT_FOUND,
349     SEW_BOTH_BORDERS_NOT_FOUND,
350     SEW_BAD_SIDE_NODES,
351     SEW_VOLUMES_TO_SPLIT,
352     // for SewSideElements()
353     SEW_DIFF_NB_OF_ELEMENTS,
354     SEW_TOPO_DIFF_SETS_OF_ELEMENTS,
355     SEW_BAD_SIDE1_NODES,
356     SEW_BAD_SIDE2_NODES,
357     SEW_INTERNAL_ERROR
358     };
359     
360
361   Sew_Error SewFreeBorder (const SMDS_MeshNode* theBorderFirstNode,
362                            const SMDS_MeshNode* theBorderSecondNode,
363                            const SMDS_MeshNode* theBorderLastNode,
364                            const SMDS_MeshNode* theSide2FirstNode,
365                            const SMDS_MeshNode* theSide2SecondNode,
366                            const SMDS_MeshNode* theSide2ThirdNode = 0,
367                            const bool           theSide2IsFreeBorder = true,
368                            const bool           toCreatePolygons = false,
369                            const bool           toCreatePolyedrs = false);
370   // Sew the free border to the side2 by replacing nodes in
371   // elements on the free border with nodes of the elements
372   // of the side 2. If nb of links in the free border and
373   // between theSide2FirstNode and theSide2LastNode are different,
374   // additional nodes are inserted on a link provided that no
375   // volume elements share the splitted link.
376   // The side 2 is a free border if theSide2IsFreeBorder == true.
377   // Sewing is peformed between the given first, second and last
378   // nodes on the sides.
379   // theBorderFirstNode is merged with theSide2FirstNode.
380   // if (!theSide2IsFreeBorder) then theSide2SecondNode gives
381   // the last node on the side 2, which will be merged with
382   // theBorderLastNode.
383   // if (theSide2IsFreeBorder) then theSide2SecondNode will
384   // be merged with theBorderSecondNode.
385   // if (theSide2IsFreeBorder && theSide2ThirdNode == 0) then
386   // the 2 free borders are sewn link by link and no additional
387   // nodes are inserted.
388   // Return false, if sewing failed.
389
390   Sew_Error SewSideElements (TIDSortedElemSet&    theSide1,
391                              TIDSortedElemSet&    theSide2,
392                              const SMDS_MeshNode* theFirstNode1ToMerge,
393                              const SMDS_MeshNode* theFirstNode2ToMerge,
394                              const SMDS_MeshNode* theSecondNode1ToMerge,
395                              const SMDS_MeshNode* theSecondNode2ToMerge);
396   // Sew two sides of a mesh. Nodes belonging to theSide1 are
397   // merged with nodes of elements of theSide2.
398   // Number of elements in theSide1 and in theSide2 must be
399   // equal and they should have similar node connectivity.
400   // The nodes to merge should belong to side s borders and
401   // the first node should be linked to the second.
402
403   void InsertNodesIntoLink(const SMDS_MeshElement*          theFace,
404                            const SMDS_MeshNode*             theBetweenNode1,
405                            const SMDS_MeshNode*             theBetweenNode2,
406                            std::list<const SMDS_MeshNode*>& theNodesToInsert,
407                            const bool                       toCreatePoly = false);
408   // insert theNodesToInsert into theFace between theBetweenNode1 and theBetweenNode2.
409   // If toCreatePoly is true, replace theFace by polygon, else split theFace.
410
411   void UpdateVolumes (const SMDS_MeshNode*             theBetweenNode1,
412                       const SMDS_MeshNode*             theBetweenNode2,
413                       std::list<const SMDS_MeshNode*>& theNodesToInsert);
414   // insert theNodesToInsert into all volumes, containing link
415   // theBetweenNode1 - theBetweenNode2, between theBetweenNode1 and theBetweenNode2.
416
417   void ConvertToQuadratic(const bool theForce3d);
418   //converts all mesh to quadratic one, deletes old elements, replacing 
419   //them with quadratic ones with the same id.
420
421   bool ConvertFromQuadratic();
422   //converts all mesh from quadratic to ordinary ones, deletes old quadratic elements, replacing 
423   //them with ordinary mesh elements with the same id.
424
425
426 //  static int SortQuadNodes (const SMDS_Mesh * theMesh,
427 //                            int               theNodeIds[] );
428 //  // Set 4 nodes of a quadrangle face in a good order.
429 //  // Swap 1<->2 or 2<->3 nodes and correspondingly return
430 //  // 1 or 2 else 0.
431 //
432 //  static bool SortHexaNodes (const SMDS_Mesh * theMesh,
433 //                             int               theNodeIds[] );
434 //  // Set 8 nodes of a hexahedron in a good order.
435 //  // Return success status
436
437   static void AddToSameGroups (const SMDS_MeshElement* elemToAdd,
438                                const SMDS_MeshElement* elemInGroups,
439                                SMESHDS_Mesh *          aMesh);
440   // Add elemToAdd to the groups the elemInGroups belongs to
441
442   static void RemoveElemFromGroups (const SMDS_MeshElement* removeelem,
443                                     SMESHDS_Mesh *          aMesh);
444   // remove elemToAdd from the groups
445
446   /*!
447    * \brief Return nodes linked to the given one in elements of the type
448    */
449   static void GetLinkedNodes( const SMDS_MeshNode* node,
450                               TIDSortedElemSet &   linkedNodes,
451                               SMDSAbs_ElementType  type = SMDSAbs_All );
452
453   static const SMDS_MeshElement*
454     FindFaceInSet(const SMDS_MeshNode*    n1,
455                   const SMDS_MeshNode*    n2,
456                   const TIDSortedElemSet& elemSet,
457                   const TIDSortedElemSet& avoidSet);
458   // Return a face having linked nodes n1 and n2 and which is
459   // - not in avoidSet,
460   // - in elemSet provided that !elemSet.empty()
461
462   /*!
463    * \brief Find corresponding nodes in two sets of faces 
464     * \param theSide1 - first face set
465     * \param theSide2 - second first face
466     * \param theFirstNode1 - a boundary node of set 1
467     * \param theFirstNode2 - a node of set 2 corresponding to theFirstNode1
468     * \param theSecondNode1 - a boundary node of set 1 linked with theFirstNode1
469     * \param theSecondNode2 - a node of set 2 corresponding to theSecondNode1
470     * \param nReplaceMap - output map of corresponding nodes
471     * \retval Sew_Error  - is a success or not
472    */
473   static Sew_Error FindMatchingNodes(set<const SMDS_MeshElement*>& theSide1,
474                                      set<const SMDS_MeshElement*>& theSide2,
475                                      const SMDS_MeshNode*          theFirstNode1,
476                                      const SMDS_MeshNode*          theFirstNode2,
477                                      const SMDS_MeshNode*          theSecondNode1,
478                                      const SMDS_MeshNode*          theSecondNode2,
479                                      TNodeNodeMap &                nReplaceMap);
480
481   /*!
482    * \brief Returns true if given node is medium
483     * \param n - node to check
484     * \param typeToCheck - type of elements containing the node to ask about node status
485     * \retval bool - check result
486    */
487   static bool IsMedium(const SMDS_MeshNode*      node,
488                        const SMDSAbs_ElementType typeToCheck = SMDSAbs_All);
489
490   int FindShape (const SMDS_MeshElement * theElem);
491   // Return an index of the shape theElem is on
492   // or zero if a shape not found
493
494   SMESH_Mesh * GetMesh() { return myMesh; }
495
496   SMESHDS_Mesh * GetMeshDS() { return myMesh->GetMeshDS(); }
497
498   const SMESH_SequenceOfElemPtr& GetLastCreatedNodes() const { return myLastCreatedNodes; }
499
500   const SMESH_SequenceOfElemPtr& GetLastCreatedElems() const { return myLastCreatedElems; }
501
502 private:
503
504   /*!
505    * \brief Convert elements contained in a submesh to quadratic
506     * \retval int - nb of checked elements
507    */
508   int ConvertElemToQuadratic(SMESHDS_SubMesh *   theSm,
509                              SMESH_MesherHelper& theHelper,
510                              const bool          theForce3d);
511
512   /*!
513    * \brief Convert quadratic elements to linear ones and remove quadratic nodes
514     * \retval int - nb of checked elements
515    */
516   int RemoveQuadElem( SMESHDS_SubMesh *    theSm,
517                       SMDS_ElemIteratorPtr theItr,
518                       const int            theShapeID);
519   //Auxiliary function for "ConvertFromQuadratic" is intended to 
520
521 private:
522
523   SMESH_Mesh * myMesh;
524
525   /*!
526    * Sequence for keeping nodes created during last operation
527    */
528   SMESH_SequenceOfElemPtr myLastCreatedNodes;
529
530   /*!
531    * Sequence for keeping elements created during last operation
532    */
533   SMESH_SequenceOfElemPtr myLastCreatedElems;
534
535 };
536
537 #endif