Salome HOME
40016a4884233f2ea779157a3c6398107a8dd337
[modules/smesh.git] / src / SMESH / SMESH_MesherHelper.cxx
1 // Copyright (C) 2007-2015  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_MesherHelper.cxx
24 // Created:   15.02.06 15:22:41
25 // Author:    Sergey KUUL
26 //
27 #include "SMESH_MesherHelper.hxx"
28
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FaceOfNodes.hxx"
31 #include "SMDS_FacePosition.hxx" 
32 #include "SMDS_IteratorOnIterators.hxx"
33 #include "SMDS_VolumeTool.hxx"
34 #include "SMESH_Block.hxx"
35 #include "SMESH_HypoFilter.hxx"
36 #include "SMESH_MeshAlgos.hxx"
37 #include "SMESH_ProxyMesh.hxx"
38 #include "SMESH_subMesh.hxx"
39
40 #include <BRepAdaptor_Curve.hxx>
41 #include <BRepAdaptor_Surface.hxx>
42 #include <BRepTools.hxx>
43 #include <BRep_Tool.hxx>
44 #include <Geom2d_Curve.hxx>
45 #include <GeomAPI_ProjectPointOnCurve.hxx>
46 #include <GeomAPI_ProjectPointOnSurf.hxx>
47 #include <Geom_Curve.hxx>
48 #include <Geom_RectangularTrimmedSurface.hxx>
49 #include <Geom_Surface.hxx>
50 #include <ShapeAnalysis.hxx>
51 #include <TopExp.hxx>
52 #include <TopExp_Explorer.hxx>
53 #include <TopTools_ListIteratorOfListOfShape.hxx>
54 #include <TopTools_MapIteratorOfMapOfShape.hxx>
55 #include <TopTools_MapOfShape.hxx>
56 #include <TopoDS.hxx>
57 #include <gp_Ax3.hxx>
58 #include <gp_Pnt2d.hxx>
59 #include <gp_Trsf.hxx>
60
61 #include <Standard_Failure.hxx>
62 #include <Standard_ErrorHandler.hxx>
63
64 #include <utilities.h>
65
66 #include <limits>
67
68 using namespace std;
69
70 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
71
72 namespace {
73
74   inline SMESH_TNodeXYZ XYZ(const SMDS_MeshNode* n) { return SMESH_TNodeXYZ(n); }
75
76   enum { U_periodic = 1, V_periodic = 2 };
77 }
78
79 //================================================================================
80 /*!
81  * \brief Constructor
82  */
83 //================================================================================
84
85 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
86   : myParIndex(0),
87     myMesh(&theMesh),
88     myShapeID(0),
89     myCreateQuadratic(false),
90     myCreateBiQuadratic(false),
91     myFixNodeParameters(false)
92 {
93   myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
94   mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
95 }
96
97 //=======================================================================
98 //function : ~SMESH_MesherHelper
99 //purpose  : 
100 //=======================================================================
101
102 SMESH_MesherHelper::~SMESH_MesherHelper()
103 {
104   {
105     TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
106     for ( ; i_proj != myFace2Projector.end(); ++i_proj )
107       delete i_proj->second;
108   }
109   {
110     TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
111     for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
112       delete i_proj->second;
113   }
114 }
115
116 //=======================================================================
117 //function : IsQuadraticSubMesh
118 //purpose  : Check submesh for given shape: if all elements on this shape 
119 //           are quadratic, quadratic elements will be created.
120 //           Also fill myTLinkNodeMap
121 //=======================================================================
122
123 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
124 {
125   SMESHDS_Mesh* meshDS = GetMeshDS();
126   // we can create quadratic elements only if all elements
127   // created on sub-shapes of given shape are quadratic
128   // also we have to fill myTLinkNodeMap
129   myCreateQuadratic = true;
130   mySeamShapeIds.clear();
131   myDegenShapeIds.clear();
132   TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
133   if ( aSh.ShapeType()==TopAbs_COMPOUND )
134   {
135     TopoDS_Iterator subIt( aSh );
136     if ( subIt.More() )
137       subType = ( subIt.Value().ShapeType()==TopAbs_FACE ) ? TopAbs_EDGE : TopAbs_FACE;
138   }
139   SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
140
141
142   //int nbOldLinks = myTLinkNodeMap.size();
143
144   if ( !myMesh->HasShapeToMesh() )
145   {
146     if (( myCreateQuadratic = myMesh->NbFaces( ORDER_QUADRATIC )))
147     {
148       SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
149       while ( fIt->more() )
150         AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
151     }
152   }
153   else
154   {
155     TopExp_Explorer exp( aSh, subType );
156     TopTools_MapOfShape checkedSubShapes;
157     for (; exp.More() && myCreateQuadratic; exp.Next()) {
158       if ( !checkedSubShapes.Add( exp.Current() ))
159         continue; // needed if aSh is compound of solids
160       if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
161         if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
162           while(it->more()) {
163             const SMDS_MeshElement* e = it->next();
164             if ( e->GetType() != elemType || !e->IsQuadratic() ) {
165               myCreateQuadratic = false;
166               break;
167             }
168             else {
169               // fill TLinkNodeMap
170               switch ( e->NbCornerNodes() ) {
171               case 2:
172                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
173               case 3:
174                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
175                 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
176                 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
177               case 4:
178                 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
179                 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
180                 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
181                 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
182                 break;
183               default:
184                 myCreateQuadratic = false;
185                 break;
186               }
187             }
188           }
189         }
190       }
191     }
192   }
193
194   // if ( nbOldLinks == myTLinkNodeMap.size() ) -- 0023068
195   if ( myTLinkNodeMap.empty() )
196     myCreateQuadratic = false;
197
198   if ( !myCreateQuadratic )
199     myTLinkNodeMap.clear();
200
201   SetSubShape( aSh );
202
203   return myCreateQuadratic;
204 }
205
206 //=======================================================================
207 //function : SetSubShape
208 //purpose  : Set geometry to make elements on
209 //=======================================================================
210
211 void SMESH_MesherHelper::SetSubShape(const int aShID)
212 {
213   if ( aShID == myShapeID )
214     return;
215   if ( aShID > 0 )
216     SetSubShape( GetMeshDS()->IndexToShape( aShID ));
217   else
218     SetSubShape( TopoDS_Shape() );
219 }
220
221 //=======================================================================
222 //function : SetSubShape
223 //purpose  : Set geometry to create elements on
224 //=======================================================================
225
226 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
227 {
228   if ( myShape.IsSame( aSh ))
229     return;
230
231   myShape = aSh;
232   mySeamShapeIds.clear();
233   myDegenShapeIds.clear();
234
235   if ( myShape.IsNull() ) {
236     myShapeID  = 0;
237     return;
238   }
239   SMESHDS_Mesh* meshDS = GetMeshDS();
240   myShapeID = meshDS->ShapeToIndex(aSh);
241   myParIndex = 0;
242
243   // treatment of periodic faces
244   for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
245   {
246     const TopoDS_Face& face = TopoDS::Face( eF.Current() );
247     BRepAdaptor_Surface surf( face, false );
248     if ( surf.IsUPeriodic() || surf.IsUClosed() ) {
249       myParIndex |= U_periodic;
250       myPar1[0] = surf.FirstUParameter();
251       myPar2[0] = surf.LastUParameter();
252     }
253     if ( surf.IsVPeriodic() || surf.IsVClosed() ) {
254       myParIndex |= V_periodic;
255       myPar1[1] = surf.FirstVParameter();
256       myPar2[1] = surf.LastVParameter();
257     }
258
259     gp_Pnt2d uv1, uv2;
260     for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
261     {
262       // look for a "seam" edge, a real seam or an edge on period boundary
263       TopoDS_Edge edge = TopoDS::Edge( exp.Current() );
264       const int edgeID = meshDS->ShapeToIndex( edge );
265       if ( myParIndex )
266       {
267         BRep_Tool::UVPoints( edge, face, uv1, uv2 );
268         const double du = Abs( uv1.Coord(1) - uv2.Coord(1) );
269         const double dv = Abs( uv1.Coord(2) - uv2.Coord(2) );
270
271         bool isSeam = BRep_Tool::IsClosed( edge, face );
272         if ( isSeam ) // real seam - having two pcurves on face
273         {
274           // pcurve can lie not on pediod boundary (22582, mesh_Quadratic_01/C9)
275           if ( du < dv )
276           {
277             double u1 = uv1.Coord(1);
278             edge.Reverse();
279             BRep_Tool::UVPoints( edge, face, uv1, uv2 );
280             double u2 = uv1.Coord(1);
281             myPar1[0] = Min( u1, u2 );
282             myPar2[0] = Max( u1, u2 );
283           }
284           else
285           {
286             double v1 = uv1.Coord(2);
287             edge.Reverse();
288             BRep_Tool::UVPoints( edge, face, uv1, uv2 );
289             double v2 = uv1.Coord(2);
290             myPar1[1] = Min( v1, v2 );
291             myPar2[1] = Max( v1, v2 );
292           }
293         }
294         else //if ( !isSeam )
295         {
296           // one pcurve but on period boundary (22772, mesh_Quadratic_01/D1)
297           if      (( myParIndex & U_periodic ) && du < Precision::PConfusion() )
298           {
299             isSeam = ( Abs( uv1.Coord(1) - myPar1[0] ) < Precision::PConfusion() ||
300                        Abs( uv1.Coord(1) - myPar2[0] ) < Precision::PConfusion() );
301           }
302           else if (( myParIndex & V_periodic ) && dv < Precision::PConfusion() )
303           {
304             isSeam = ( Abs( uv1.Coord(2) - myPar1[1] ) < Precision::PConfusion() ||
305                        Abs( uv1.Coord(2) - myPar2[1] ) < Precision::PConfusion() );
306           }
307           if ( isSeam ) // vertices are on period boundary, check a middle point (23032)
308           {
309             double f,l, r = 0.2345;
310             Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
311             uv2 = C2d->Value( f * r + l * ( 1.-r ));
312             if ( du < Precision::PConfusion() )
313               isSeam = ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Precision::PConfusion() );
314             else
315               isSeam = ( Abs( uv1.Coord(2) - uv2.Coord(2) ) < Precision::PConfusion() );
316           }
317         }
318         if ( isSeam )
319         {
320           // store seam shape indices, negative if shape encounters twice ('real seam')
321           mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
322           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
323             int vertexID = meshDS->ShapeToIndex( v.Current() );
324             mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
325           }
326         }
327       }
328       // look for a degenerated edge
329       if ( SMESH_Algo::isDegenerated( edge )) {
330         myDegenShapeIds.insert( edgeID );
331         for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
332           myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
333       }
334       if ( !BRep_Tool::SameParameter( edge ) ||
335            !BRep_Tool::SameRange( edge ))
336       {
337         setPosOnShapeValidity( edgeID, false );
338       }
339     }
340   }
341 }
342
343 //=======================================================================
344 //function : GetNodeUVneedInFaceNode
345 //purpose  : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
346 //           Return true if the face is periodic.
347 //           If F is Null, answer about sub-shape set through IsQuadraticSubMesh() or
348 //           * SetSubShape()
349 //=======================================================================
350
351 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
352 {
353   if ( F.IsNull() ) return !mySeamShapeIds.empty();
354
355   if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
356     return !mySeamShapeIds.empty();
357
358   TopLoc_Location loc;
359   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
360   if ( !aSurface.IsNull() )
361     return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
362
363   return false;
364 }
365
366 //=======================================================================
367 //function : IsMedium
368 //purpose  : 
369 //=======================================================================
370
371 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode*      node,
372                                   const SMDSAbs_ElementType typeToCheck)
373 {
374   return SMESH_MeshEditor::IsMedium( node, typeToCheck );
375 }
376
377 //=======================================================================
378 //function : GetSubShapeByNode
379 //purpose  : Return support shape of a node
380 //=======================================================================
381
382 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
383                                                    const SMESHDS_Mesh*  meshDS)
384 {
385   int shapeID = node ? node->getshapeId() : 0;
386   if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
387     return meshDS->IndexToShape( shapeID );
388   else
389     return TopoDS_Shape();
390 }
391
392
393 //=======================================================================
394 //function : AddTLinkNode
395 //purpose  : add a link in my data structure
396 //=======================================================================
397
398 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
399                                       const SMDS_MeshNode* n2,
400                                       const SMDS_MeshNode* n12)
401 {
402   // add new record to map
403   SMESH_TLink link( n1, n2 );
404   myTLinkNodeMap.insert( make_pair(link,n12));
405 }
406
407 //================================================================================
408 /*!
409  * \brief Add quadratic links of edge to own data structure
410  */
411 //================================================================================
412
413 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
414 {
415   if ( edge && edge->IsQuadratic() )
416     AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
417   else
418     return false;
419   return true;
420 }
421
422 //================================================================================
423 /*!
424  * \brief Add quadratic links of face to own data structure
425  */
426 //================================================================================
427
428 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* f)
429 {
430   bool isQuad = true;
431   if ( !f->IsPoly() )
432     switch ( f->NbNodes() ) {
433     case 7:
434       // myMapWithCentralNode.insert
435       //   ( make_pair( TBiQuad( f->GetNode(0),f->GetNode(1),f->GetNode(2) ),
436       //                f->GetNode(6)));
437       // break; -- add medium nodes as well
438     case 6:
439       AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(3));
440       AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(4));
441       AddTLinkNode(f->GetNode(2),f->GetNode(0),f->GetNode(5)); break;
442
443     case 9:
444       // myMapWithCentralNode.insert
445       //   ( make_pair( TBiQuad( f->GetNode(0),f->GetNode(1),f->GetNode(2),f->GetNode(3) ),
446       //                f->GetNode(8)));
447       // break; -- add medium nodes as well
448     case 8:
449       AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(4));
450       AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(5));
451       AddTLinkNode(f->GetNode(2),f->GetNode(3),f->GetNode(6));
452       AddTLinkNode(f->GetNode(3),f->GetNode(0),f->GetNode(7)); break;
453     default:;
454       isQuad = false;
455     }
456   return isQuad;
457 }
458
459 //================================================================================
460 /*!
461  * \brief Add quadratic links of volume to own data structure
462  */
463 //================================================================================
464
465 bool SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
466 {
467   if ( volume->IsQuadratic() )
468   {
469     SMDS_VolumeTool vTool( volume );
470     const SMDS_MeshNode** nodes = vTool.GetNodes();
471     set<int> addedLinks;
472     for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
473     {
474       const int nbN = vTool.NbFaceNodes( iF );
475       const int* iNodes = vTool.GetFaceNodesIndices( iF );
476       for ( int i = 0; i < nbN; )
477       {
478         int iN1  = iNodes[i++];
479         int iN12 = iNodes[i++];
480         int iN2  = iNodes[i];
481         if ( iN1 > iN2 ) std::swap( iN1, iN2 );
482         int linkID = iN1 * vTool.NbNodes() + iN2;
483         pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
484         if ( it_isNew.second )
485           AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
486         else
487           addedLinks.erase( it_isNew.first ); // each link encounters only twice
488       }
489       if ( vTool.NbNodes() == 27 )
490       {
491         const SMDS_MeshNode* nFCenter = nodes[ vTool.GetCenterNodeIndex( iF )];
492         if ( nFCenter->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
493           myMapWithCentralNode.insert
494             ( make_pair( TBiQuad( nodes[ iNodes[0]], nodes[ iNodes[1]],
495                                   nodes[ iNodes[2]], nodes[ iNodes[3]] ),
496                          nFCenter ));
497       }
498     }
499     return true;
500   }
501   return false;
502 }
503
504 //================================================================================
505 /*!
506  * \brief Return true if position of nodes on the shape hasn't yet been checked or
507  * the positions proved to be invalid
508  */
509 //================================================================================
510
511 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
512 {
513   map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
514   return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
515 }
516
517 //================================================================================
518 /*!
519  * \brief Set validity of positions of nodes on the shape.
520  * Once set, validity is not changed
521  */
522 //================================================================================
523
524 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
525 {
526   std::map< int,bool >::iterator sh_ok = 
527     ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok)).first;
528   if ( !ok )
529     sh_ok->second = ok;
530 }
531
532 //=======================================================================
533 //function : ToFixNodeParameters
534 //purpose  : Enables fixing node parameters on EDGEs and FACEs in 
535 //           GetNodeU(...,check=true), GetNodeUV(...,check=true), CheckNodeUV() and
536 //           CheckNodeU() in case if a node lies on a shape set via SetSubShape().
537 //           Default is False
538 //=======================================================================
539
540 void SMESH_MesherHelper::ToFixNodeParameters(bool toFix)
541 {
542   myFixNodeParameters = toFix;
543 }
544
545
546 //=======================================================================
547 //function : getUVOnSeam
548 //purpose  : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
549 //=======================================================================
550
551 gp_Pnt2d SMESH_MesherHelper::getUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
552 {
553   gp_Pnt2d result = uv1;
554   for ( int i = U_periodic; i <= V_periodic ; ++i )
555   {
556     if ( myParIndex & i )
557     {
558       double p1 = uv1.Coord( i );
559       double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
560       if ( myParIndex == i ||
561            dp1 < ( myPar2[i-1] - myPar1[i-1] ) / 100. ||
562            dp2 < ( myPar2[i-1] - myPar1[i-1] ) / 100. )
563       {
564         double p2 = uv2.Coord( i );
565         double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
566         if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
567           result.SetCoord( i, p1Alt );
568       }
569     }
570   }
571   return result;
572 }
573
574 //=======================================================================
575 //function : GetNodeUV
576 //purpose  : Return node UV on face
577 //=======================================================================
578
579 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face&   F,
580                                     const SMDS_MeshNode* n,
581                                     const SMDS_MeshNode* n2,
582                                     bool*                check) const
583 {
584   gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
585
586   const SMDS_PositionPtr Pos = n->GetPosition();
587   bool uvOK = false;
588   if ( Pos->GetTypeOfPosition() == SMDS_TOP_FACE )
589   {
590     // node has position on face
591     const SMDS_FacePosition* fpos = static_cast<const SMDS_FacePosition*>( Pos );
592     uv.SetCoord( fpos->GetUParameter(), fpos->GetVParameter() );
593     if ( check )
594       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F )); // 2. from 22830
595   }
596   else if ( Pos->GetTypeOfPosition() == SMDS_TOP_EDGE )
597   {
598     // node has position on EDGE => it is needed to find
599     // corresponding EDGE from FACE, get pcurve for this
600     // EDGE and retrieve value from this pcurve
601     const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( Pos );
602     const int              edgeID = n->getshapeId();
603     const TopoDS_Edge& E = TopoDS::Edge( GetMeshDS()->IndexToShape( edgeID ));
604     double f, l, u = epos->GetUParameter();
605     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( E, F, f, l );
606     bool validU = ( !C2d.IsNull() && ( f < u ) && ( u < l ));
607     if ( validU ) uv = C2d->Value( u );
608     else          uv.SetCoord( Precision::Infinite(),0.);
609     if ( check || !validU )
610       uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F ),/*force=*/ !validU );
611
612     // for a node on a seam EDGE select one of UVs on 2 pcurves
613     if ( n2 && IsSeamShape( edgeID ))
614     {
615       uv = getUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
616     }
617     else
618     { // adjust uv to period
619       TopLoc_Location loc;
620       Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
621       Standard_Boolean isUPeriodic = S->IsUPeriodic();
622       Standard_Boolean isVPeriodic = S->IsVPeriodic();
623       gp_Pnt2d newUV = uv;
624       if ( isUPeriodic || isVPeriodic ) {
625         Standard_Real UF,UL,VF,VL;
626         S->Bounds(UF,UL,VF,VL);
627         if ( isUPeriodic ) newUV.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
628         if ( isVPeriodic ) newUV.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
629
630         if ( n2 )
631         {
632           gp_Pnt2d uv2 = GetNodeUV( F, n2, 0, check );
633           if ( isUPeriodic && Abs( uv.X()-uv2.X() ) < Abs( newUV.X()-uv2.X() ))
634             newUV.SetX( uv.X() );
635           if ( isVPeriodic && Abs( uv.Y()-uv2.Y() ) < Abs( newUV.Y()-uv2.Y() ))
636             newUV.SetY( uv.Y() );
637         }
638       }
639       uv = newUV;
640     }
641   }
642   else if ( Pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
643   {
644     if ( int vertexID = n->getshapeId() ) {
645       const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
646       try {
647         uv = BRep_Tool::Parameters( V, F );
648         uvOK = true;
649       }
650       catch (Standard_Failure& exc) {
651       }
652       if ( !uvOK )
653       {
654         if ( !IsSubShape( V, F ))
655         {
656           MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
657                     << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
658           // get UV of a vertex closest to the node
659           double dist = 1e100;
660           gp_Pnt pn = XYZ( n );
661           for ( TopExp_Explorer vert( F,TopAbs_VERTEX ); !uvOK && vert.More(); vert.Next() ) {
662             TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
663             gp_Pnt p = BRep_Tool::Pnt( curV );
664             double curDist = p.SquareDistance( pn );
665             if ( curDist < dist ) {
666               dist = curDist;
667               uv = BRep_Tool::Parameters( curV, F );
668               uvOK = ( dist < DBL_MIN );
669             }
670           }
671         }
672         else
673         {
674           uvOK = false;
675           TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
676           for ( ; it.More(); it.Next() ) {
677             if ( it.Value().ShapeType() == TopAbs_EDGE ) {
678               const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
679               double f,l;
680               Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
681               if ( !C2d.IsNull() ) {
682                 double u = ( V == IthVertex( 0, edge )) ?  f : l;
683                 uv = C2d->Value( u );
684                 uvOK = true;
685                 break;
686               }
687             }
688           }
689           if ( !uvOK && V.Orientation() == TopAbs_INTERNAL )
690           {
691             Handle(ShapeAnalysis_Surface) projector = GetSurface( F );
692             if ( n2 ) uv = GetNodeUV( F, n2 );
693             if ( Precision::IsInfinite( uv.X() ))
694               uv = projector->NextValueOfUV( uv, BRep_Tool::Pnt( V ), BRep_Tool::Tolerance( F ));
695             else
696               uv = projector->ValueOfUV( BRep_Tool::Pnt( V ), BRep_Tool::Tolerance( F ));
697             uvOK = ( projector->Gap() < getFaceMaxTol( F ));
698           }
699         }
700       }
701       if ( n2 && IsSeamShape( vertexID ))
702       {
703         bool isSeam = ( myShape.IsSame( F ));
704         if ( !isSeam ) {
705           SMESH_MesherHelper h( *myMesh );
706           h.SetSubShape( F );
707           isSeam = IsSeamShape( vertexID );
708         }
709
710         if ( isSeam )
711           uv = getUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
712       }
713     }
714   }
715   else
716   {
717     uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 2.*getFaceMaxTol( F ));
718   }
719
720   if ( check && !uvOK )
721     *check = uvOK;
722
723   return uv.XY();
724 }
725
726 //=======================================================================
727 //function : CheckNodeUV
728 //purpose  : Check and fix node UV on a face
729 //=======================================================================
730
731 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face&   F,
732                                      const SMDS_MeshNode* n,
733                                      gp_XY&               uv,
734                                      const double         tol,
735                                      const bool           force,
736                                      double               distXYZ[4]) const
737 {
738   int  shapeID = n->getshapeId();
739   bool infinit;
740   if (( infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ))) ||
741       ( force ) ||
742       ( uv.X() == 0. && uv.Y() == 0. ) ||
743       ( toCheckPosOnShape( shapeID )))
744   {
745     // check that uv is correct
746     TopLoc_Location loc;
747     Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
748     gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
749     double dist = 0;
750     if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
751     if ( infinit ||
752          (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
753     {
754       setPosOnShapeValidity( shapeID, false );
755       if ( !infinit && distXYZ ) {
756         surfPnt.Transform( loc );
757         distXYZ[0] = dist;
758         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
759       }
760       // uv incorrect, project the node to surface
761       GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
762       projector.Perform( nodePnt );
763       if ( !projector.IsDone() || projector.NbPoints() < 1 )
764       {
765         MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
766         return false;
767       }
768       Quantity_Parameter U,V;
769       projector.LowerDistanceParameters(U,V);
770       uv.SetCoord( U,V );
771       surfPnt = surface->Value( U, V );
772       dist = nodePnt.Distance( surfPnt );
773       if ( distXYZ ) {
774         surfPnt.Transform( loc );
775         distXYZ[0] = dist;
776         distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
777       }
778       if ( dist > tol )
779       {
780         MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
781         return false;
782       }
783       // store the fixed UV on the face
784       if ( myShape.IsSame(F) && shapeID == myShapeID && myFixNodeParameters )
785         const_cast<SMDS_MeshNode*>(n)->SetPosition
786           ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
787     }
788     else if ( myShape.IsSame(F) && uv.Modulus() > numeric_limits<double>::min() )
789     {
790       setPosOnShapeValidity( shapeID, true );
791     }
792   }
793   return true;
794 }
795
796 //=======================================================================
797 //function : GetProjector
798 //purpose  : Return projector intitialized by given face without location, which is returned
799 //=======================================================================
800
801 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
802                                                              TopLoc_Location&   loc,
803                                                              double             tol ) const
804 {
805   Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
806   int faceID = GetMeshDS()->ShapeToIndex( F );
807   TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
808   TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
809   if ( i_proj == i2proj.end() )
810   {
811     if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
812     double U1, U2, V1, V2;
813     surface->Bounds(U1, U2, V1, V2);
814     GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
815     proj->Init( surface, U1, U2, V1, V2, tol );
816     i_proj = i2proj.insert( make_pair( faceID, proj )).first;
817   }
818   return *( i_proj->second );
819 }
820
821 //=======================================================================
822 //function : GetSurface
823 //purpose  : Return a cached ShapeAnalysis_Surface of a FACE
824 //=======================================================================
825
826 Handle(ShapeAnalysis_Surface) SMESH_MesherHelper::GetSurface(const TopoDS_Face& F ) const
827 {
828   Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
829   int faceID = GetMeshDS()->ShapeToIndex( F );
830   TID2Surface::iterator i_surf = myFace2Surface.find( faceID );
831   if ( i_surf == myFace2Surface.end() && faceID )
832   {
833     Handle(ShapeAnalysis_Surface) surf( new ShapeAnalysis_Surface( surface ));
834     i_surf = myFace2Surface.insert( make_pair( faceID, surf )).first;
835   }
836   return i_surf->second;
837 }
838
839 namespace
840 {
841   gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
842   gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
843   gp_XY_FunPtr(Subtracted); 
844 }
845
846 //=======================================================================
847 //function : ApplyIn2D
848 //purpose  : Perform given operation on two 2d points in parameric space of given surface.
849 //           It takes into account period of the surface. Use gp_XY_FunPtr macro
850 //           to easily define pointer to function of gp_XY class.
851 //=======================================================================
852
853 gp_XY SMESH_MesherHelper::ApplyIn2D(Handle(Geom_Surface) surface,
854                                     const gp_XY&         uv1,
855                                     const gp_XY&         uv2,
856                                     xyFunPtr             fun,
857                                     const bool           resultInPeriod)
858 {
859   if ( surface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
860     surface = Handle(Geom_RectangularTrimmedSurface)::DownCast( surface )->BasisSurface();
861   Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
862   Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
863   if ( !isUPeriodic && !isVPeriodic )
864     return fun(uv1,uv2);
865
866   // move uv2 not far than half-period from uv1
867   double u2 = 
868     uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
869   double v2 = 
870     uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
871
872   // execute operation
873   gp_XY res = fun( uv1, gp_XY(u2,v2) );
874
875   // move result within period
876   if ( resultInPeriod )
877   {
878     Standard_Real UF,UL,VF,VL;
879     surface->Bounds(UF,UL,VF,VL);
880     if ( isUPeriodic )
881       res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
882     if ( isVPeriodic )
883       res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
884   }
885
886   return res;
887 }
888
889 //=======================================================================
890 //function : AdjustByPeriod
891 //purpose  : Move node positions on a FACE within surface period
892 //=======================================================================
893
894 void SMESH_MesherHelper::AdjustByPeriod( const TopoDS_Face& face, gp_XY uv[], const int nbUV )
895 {
896   SMESH_MesherHelper h( *myMesh ), *ph = face.IsSame( myShape ) ? this : &h;
897   ph->SetSubShape( face );
898
899   for ( int iCoo = U_periodic; iCoo <= V_periodic; ++iCoo )
900     if ( ph->GetPeriodicIndex() & iCoo )
901     {
902       const double period = ( ph->myPar2[iCoo-1] - ph->myPar1[iCoo-1] );
903       const double xRef = uv[0].Coord( iCoo );
904       for ( int i = 1; i < nbUV; ++i )
905       {
906         double x = uv[i].Coord( iCoo );
907         double dx = ShapeAnalysis::AdjustByPeriod( x, xRef, period );
908         uv[i].SetCoord( iCoo, x + dx );
909       }
910     }
911 }
912
913 //=======================================================================
914 //function : GetMiddleUV
915 //purpose  : Return middle UV taking in account surface period
916 //=======================================================================
917
918 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
919                                       const gp_XY&                p1,
920                                       const gp_XY&                p2)
921 {
922   // NOTE:
923   // the proper place of getting basic surface seems to be in ApplyIn2D()
924   // but we put it here to decrease a risk of regressions just before releasing a version
925   // Handle(Geom_Surface) surf = surface;
926   // while ( !surf.IsNull() && surf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
927   //   surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( surf )->BasisSurface();
928
929   return ApplyIn2D( surface, p1, p2, & AverageUV );
930 }
931
932 //=======================================================================
933 //function : GetCenterUV
934 //purpose  : Return UV for the central node of a biquadratic triangle
935 //=======================================================================
936
937 gp_XY SMESH_MesherHelper::GetCenterUV(const gp_XY& uv1,
938                                       const gp_XY& uv2, 
939                                       const gp_XY& uv3, 
940                                       const gp_XY& uv12,
941                                       const gp_XY& uv23,
942                                       const gp_XY& uv31,
943                                       bool *       isBadTria/*=0*/)
944 {
945   bool badTria;
946   gp_XY uvAvg = ( uv12 + uv23 + uv31 ) / 3.;
947
948   if      (( badTria = (( uvAvg - uv1 ) * ( uvAvg - uv23 ) > 0 )))
949     uvAvg = ( uv1 + uv23 ) / 2.;
950   else if (( badTria = (( uvAvg - uv2 ) * ( uvAvg - uv31 ) > 0 )))
951     uvAvg = ( uv2 + uv31 ) / 2.;
952   else if (( badTria = (( uvAvg - uv3 ) * ( uvAvg - uv12 ) > 0 )))
953     uvAvg = ( uv3 + uv12 ) / 2.;
954
955   if ( isBadTria )
956     *isBadTria = badTria;
957   return uvAvg;
958 }
959
960 //=======================================================================
961 //function : GetNodeU
962 //purpose  : Return node U on edge
963 //=======================================================================
964
965 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge&   E,
966                                     const SMDS_MeshNode* n,
967                                     const SMDS_MeshNode* inEdgeNode,
968                                     bool*                check) const
969 {
970   double param = Precision::Infinite();
971
972   const SMDS_PositionPtr pos = n->GetPosition();
973   if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
974   {
975     const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
976     param =  epos->GetUParameter();
977   }
978   else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
979   {
980     if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
981     {
982       Standard_Real f,l;
983       BRep_Tool::Range( E, f,l );
984       double uInEdge = GetNodeU( E, inEdgeNode );
985       param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
986     }
987     else
988     {
989       SMESHDS_Mesh * meshDS = GetMeshDS();
990       int vertexID = n->getshapeId();
991       const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
992       param =  BRep_Tool::Parameter( V, E );
993     }
994   }
995   if ( check )
996   {
997     double tol = BRep_Tool::Tolerance( E );
998     double f,l;  BRep_Tool::Range( E, f,l );
999     bool force = ( param < f-tol || param > l+tol );
1000     if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
1001       force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
1002
1003     *check = CheckNodeU( E, n, param, 2*tol, force );
1004   }
1005   return param;
1006 }
1007
1008 //=======================================================================
1009 //function : CheckNodeU
1010 //purpose  : Check and fix node U on an edge
1011 //           Return false if U is bad and could not be fixed
1012 //=======================================================================
1013
1014 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge&   E,
1015                                     const SMDS_MeshNode* n,
1016                                     double&              u,
1017                                     const double         tol,
1018                                     const bool           force,
1019                                     double               distXYZ[4]) const
1020 {
1021   int  shapeID = n->getshapeId();
1022   bool infinit;
1023   if (( infinit = Precision::IsInfinite( u )) ||
1024       ( force ) ||
1025       ( u == 0. ) ||
1026       ( toCheckPosOnShape( shapeID )))
1027   {
1028     TopLoc_Location loc; double f,l;
1029     Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
1030     if ( curve.IsNull() ) // degenerated edge
1031     {
1032       if ( u+tol < f || u-tol > l )
1033       {
1034         double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
1035         u =  f*r + l*(1-r);
1036       }
1037     }
1038     else
1039     {
1040       gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
1041       if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
1042       gp_Pnt curvPnt;
1043       double dist = 2*tol;
1044       if ( !infinit )
1045       {
1046         curvPnt = curve->Value( u );
1047         dist    = nodePnt.Distance( curvPnt );
1048         if ( distXYZ ) {
1049           curvPnt.Transform( loc );
1050           distXYZ[0] = dist;
1051           distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
1052         }
1053       }
1054       if ( dist > tol )
1055       {
1056         setPosOnShapeValidity( shapeID, false );
1057         // u incorrect, project the node to the curve
1058         int edgeID = GetMeshDS()->ShapeToIndex( E );
1059         TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
1060         TID2ProjectorOnCurve::iterator i_proj =
1061           i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
1062         if ( !i_proj->second  )
1063         {
1064           i_proj->second = new GeomAPI_ProjectPointOnCurve();
1065           i_proj->second->Init( curve, f, l );
1066         }
1067         GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
1068         projector->Perform( nodePnt );
1069         if ( projector->NbPoints() < 1 )
1070         {
1071           MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
1072           return false;
1073         }
1074         Quantity_Parameter U = projector->LowerDistanceParameter();
1075         u = double( U );
1076         MESSAGE(" f " << f << " l " << l << " u " << u);
1077         curvPnt = curve->Value( u );
1078         dist = nodePnt.Distance( curvPnt );
1079         if ( distXYZ ) {
1080           curvPnt.Transform( loc );
1081           distXYZ[0] = dist;
1082           distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
1083         }
1084         if ( dist > tol )
1085         {
1086           MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
1087           MESSAGE("distance " << dist << " " << tol );
1088           return false;
1089         }
1090         // store the fixed U on the edge
1091         if ( myShape.IsSame(E) && shapeID == myShapeID && myFixNodeParameters )
1092           const_cast<SMDS_MeshNode*>(n)->SetPosition
1093             ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
1094       }
1095       else if ( fabs( u ) > numeric_limits<double>::min() )
1096       {
1097         setPosOnShapeValidity( shapeID, true );
1098       }
1099       if (( u < f-tol || u > l+tol ) && force )
1100       {
1101         MESSAGE("u < f-tol || u > l+tol  ; u " << u << " f " << f << " l " << l);
1102         // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
1103         try
1104         {
1105           // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
1106           double period = curve->Period();
1107           u = ( u < f ) ? u + period : u - period;
1108         }
1109         catch (Standard_Failure& exc)
1110         {
1111           return false;
1112         }
1113       }
1114     }
1115   }
1116   return true;
1117 }
1118
1119 //=======================================================================
1120 //function : GetMediumPos
1121 //purpose  : Return index and type of the shape  (EDGE or FACE only) to
1122 //           set a medium node on
1123 //param    : useCurSubShape - if true, returns the shape set via SetSubShape()
1124 //           if any
1125 //param    : expectedSupport - shape type corresponding to element being created,
1126 //                             e.g TopAbs_EDGE if SMDSAbs_Edge is created
1127 //                             basing on \a n1 and \a n2
1128 // Calling GetMediumPos() with useCurSubShape=true is OK only for the
1129 // case where the lower dim mesh is already constructed and converted to quadratic,
1130 // else, nodes on EDGEs are assigned to FACE, for example.
1131 //=======================================================================
1132
1133 std::pair<int, TopAbs_ShapeEnum>
1134 SMESH_MesherHelper::GetMediumPos(const SMDS_MeshNode* n1,
1135                                  const SMDS_MeshNode* n2,
1136                                  const bool           useCurSubShape,
1137                                  TopAbs_ShapeEnum     expectedSupport)
1138 {
1139   if ( useCurSubShape && !myShape.IsNull() )
1140     return std::make_pair( myShapeID, myShape.ShapeType() );
1141
1142   TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1143   int              shapeID = -1;
1144   TopoDS_Shape     shape;
1145
1146   if (( myShapeID == n1->getshapeId() || myShapeID == n2->getshapeId() ) && myShapeID > 0 )
1147   {
1148     shapeType = myShape.ShapeType();
1149     shapeID   = myShapeID;
1150   }
1151   else if ( n1->getshapeId() == n2->getshapeId() )
1152   {
1153     shapeID = n2->getshapeId();
1154     shape = GetSubShapeByNode( n1, GetMeshDS() );
1155   }
1156   else // 2 different shapes
1157   {
1158     const SMDS_TypeOfPosition Pos1 = n1->GetPosition()->GetTypeOfPosition();
1159     const SMDS_TypeOfPosition Pos2 = n2->GetPosition()->GetTypeOfPosition();
1160
1161     if ( Pos1 == SMDS_TOP_3DSPACE || Pos2 == SMDS_TOP_3DSPACE )
1162     {
1163       // in SOLID
1164     }
1165     else if ( Pos1 == SMDS_TOP_FACE || Pos2 == SMDS_TOP_FACE )
1166     {
1167       // in FACE or SOLID
1168       if ( Pos1 != SMDS_TOP_FACE || Pos2 != SMDS_TOP_FACE ) // not 2 FACEs
1169       {
1170         if ( Pos1 != SMDS_TOP_FACE ) std::swap( n1,n2 );
1171         TopoDS_Shape F = GetSubShapeByNode( n1, GetMeshDS() );
1172         TopoDS_Shape S = GetSubShapeByNode( n2, GetMeshDS() );
1173         if ( IsSubShape( S, F ))
1174         {
1175           shapeType = TopAbs_FACE;
1176           shapeID   = n1->getshapeId();
1177         }
1178       }
1179     }
1180     else if ( Pos1 == SMDS_TOP_EDGE && Pos2 == SMDS_TOP_EDGE )
1181     {
1182       TopoDS_Shape E1 = GetSubShapeByNode( n1, GetMeshDS() );
1183       TopoDS_Shape E2 = GetSubShapeByNode( n2, GetMeshDS() );
1184       shape = GetCommonAncestor( E1, E2, *myMesh, TopAbs_FACE );
1185     }
1186     else if ( Pos1 == SMDS_TOP_VERTEX && Pos2 == SMDS_TOP_VERTEX )
1187     {
1188       TopoDS_Shape V1 = GetSubShapeByNode( n1, GetMeshDS() );
1189       TopoDS_Shape V2 = GetSubShapeByNode( n2, GetMeshDS() );
1190       shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_EDGE );
1191       if ( shape.IsNull() ) shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_FACE );
1192     }
1193     else // on VERTEX and EDGE
1194     {
1195       if ( Pos1 != SMDS_TOP_VERTEX ) std::swap( n1,n2 );
1196       TopoDS_Shape V = GetSubShapeByNode( n1, GetMeshDS() );
1197       TopoDS_Shape E = GetSubShapeByNode( n2, GetMeshDS() );
1198       if ( IsSubShape( V, E ))
1199         shape = E;
1200       else
1201         shape = GetCommonAncestor( V, E, *myMesh, TopAbs_FACE );
1202     }
1203   }
1204
1205   if ( !shape.IsNull() )
1206   {
1207     if ( shapeID < 1 )
1208       shapeID = GetMeshDS()->ShapeToIndex( shape );
1209     shapeType = shape.ShapeType(); // EDGE or FACE
1210
1211     if ( expectedSupport < shapeType &&
1212          expectedSupport != TopAbs_SHAPE &&
1213          !myShape.IsNull() &&
1214          myShape.ShapeType() == expectedSupport )
1215     {
1216       // e.g. a side of triangle connects nodes on the same EDGE but does not
1217       // lie on this EDGE (an arc with a coarse mesh)
1218       // =>  shapeType == TopAbs_EDGE, expectedSupport == TopAbs_FACE;
1219       // hope that myShape is a right shape, return it if the found shape
1220       // has converted elements of corresponding dim (segments in our example)
1221       int nbConvertedElems = 0;
1222       SMDSAbs_ElementType type = ( shapeType == TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
1223       for ( int iN = 0; iN < 2; ++iN )
1224       {
1225         const SMDS_MeshNode* n = iN ? n2 : n1;
1226         SMDS_ElemIteratorPtr it = n->GetInverseElementIterator( type );
1227         while ( it->more() )
1228         {
1229           const SMDS_MeshElement* elem = it->next();
1230           if ( elem->getshapeId() == shapeID &&
1231                elem->IsQuadratic() )
1232           {
1233             ++nbConvertedElems;
1234             break;
1235           }
1236         }
1237       }
1238       if ( nbConvertedElems == 2 )
1239       {
1240         shapeType = myShape.ShapeType();
1241         shapeID   = myShapeID;
1242       }
1243     }
1244   }
1245   return make_pair( shapeID, shapeType );
1246 }
1247
1248 //=======================================================================
1249 //function : GetCentralNode
1250 //purpose  : Return existing or create a new central node for a quardilateral
1251 //           quadratic face given its 8 nodes.
1252 //@param   : force3d - true means node creation in between the given nodes,
1253 //           else node position is found on a geometrical face if any.
1254 //=======================================================================
1255
1256 const SMDS_MeshNode* SMESH_MesherHelper::GetCentralNode(const SMDS_MeshNode* n1,
1257                                                         const SMDS_MeshNode* n2,
1258                                                         const SMDS_MeshNode* n3,
1259                                                         const SMDS_MeshNode* n4,
1260                                                         const SMDS_MeshNode* n12,
1261                                                         const SMDS_MeshNode* n23,
1262                                                         const SMDS_MeshNode* n34,
1263                                                         const SMDS_MeshNode* n41,
1264                                                         bool                 force3d)
1265 {
1266   SMDS_MeshNode *centralNode = 0; // central node to return
1267
1268   // Find an existing central node
1269
1270   TBiQuad keyOfMap(n1,n2,n3,n4);
1271   std::map<TBiQuad, const SMDS_MeshNode* >::iterator itMapCentralNode;
1272   itMapCentralNode = myMapWithCentralNode.find( keyOfMap );
1273   if ( itMapCentralNode != myMapWithCentralNode.end() ) 
1274   {
1275     return (*itMapCentralNode).second;
1276   }
1277
1278   // Get type of shape for the new central node
1279
1280   TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1281   int              solidID = -1;
1282   int              faceID = -1;
1283   TopoDS_Shape     shape;
1284   TopTools_ListIteratorOfListOfShape it;
1285
1286   std::map< int, int > faceId2nbNodes;
1287   std::map< int, int > ::iterator itMapWithIdFace;
1288   
1289   SMESHDS_Mesh* meshDS = GetMeshDS();
1290   
1291   // check if a face lies on a FACE, i.e. its all corner nodes lie either on the FACE or
1292   // on sub-shapes of the FACE
1293   if ( GetMesh()->HasShapeToMesh() )
1294   {
1295     const SMDS_MeshNode* nodes[] = { n1, n2, n3, n4 };
1296     for(int i = 0; i < 4; i++)
1297     {
1298       shape = GetSubShapeByNode( nodes[i], meshDS );
1299       if ( shape.IsNull() ) break;
1300       if ( shape.ShapeType() == TopAbs_SOLID )
1301       {
1302         solidID   = nodes[i]->getshapeId();
1303         shapeType = TopAbs_SOLID;
1304         break;
1305       }
1306       if ( shape.ShapeType() == TopAbs_FACE )
1307       {
1308         faceID          = nodes[i]->getshapeId();
1309         itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1310         itMapWithIdFace->second++;
1311       }
1312       else
1313       {
1314         PShapeIteratorPtr it = GetAncestors( shape, *GetMesh(), TopAbs_FACE );
1315         while ( const TopoDS_Shape* face = it->next() )
1316         {
1317           faceID = meshDS->ShapeToIndex( *face );
1318           itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 )).first;
1319           itMapWithIdFace->second++;
1320         }
1321       }
1322     }
1323   }
1324   if ( solidID < 1 && !faceId2nbNodes.empty() ) // SOLID not found
1325   {
1326     // find ID of the FACE the four corner nodes belong to
1327     itMapWithIdFace = faceId2nbNodes.find( myShapeID ); // IPAL52698
1328     if ( itMapWithIdFace != faceId2nbNodes.end() &&
1329          itMapWithIdFace->second == 4 )
1330     {
1331       shapeType = TopAbs_FACE;
1332       faceID = myShapeID;
1333     }
1334     else
1335     {
1336       itMapWithIdFace = faceId2nbNodes.begin();
1337       for ( ; itMapWithIdFace != faceId2nbNodes.end(); ++itMapWithIdFace)
1338       {
1339         if ( itMapWithIdFace->second == 4 )
1340         {
1341           shapeType = TopAbs_FACE;
1342           faceID = (*itMapWithIdFace).first;
1343           break;
1344         }
1345       }
1346     }
1347   }
1348
1349   TopoDS_Face F;
1350   if ( shapeType == TopAbs_FACE )
1351   {
1352     F = TopoDS::Face( meshDS->IndexToShape( faceID ));
1353   }
1354
1355   // Create a node
1356
1357   gp_XY  uvAvg;
1358   gp_Pnt P;
1359   bool toCheck = true;
1360   if ( !F.IsNull() && !force3d )
1361   {
1362     Handle(ShapeAnalysis_Surface) surface = GetSurface( F );
1363     if ( HasDegeneratedEdges() || surface->HasSingularities( 1e-7 ))
1364     {
1365       gp_Pnt center = calcTFI (0.5, 0.5, // IPAL0052863
1366                                SMESH_TNodeXYZ(n1),  SMESH_TNodeXYZ(n2),
1367                                SMESH_TNodeXYZ(n3),  SMESH_TNodeXYZ(n4),
1368                                SMESH_TNodeXYZ(n12), SMESH_TNodeXYZ(n23),
1369                                SMESH_TNodeXYZ(n34), SMESH_TNodeXYZ(n41));
1370       gp_Pnt2d uv12 = GetNodeUV( F, n12, n3, &toCheck );
1371       uvAvg = surface->NextValueOfUV( uv12, center, BRep_Tool::Tolerance( F )).XY();
1372     }
1373     else
1374     {
1375       gp_XY uv[8] = {
1376         GetNodeUV( F,n1,  n3, &toCheck ),
1377         GetNodeUV( F,n2,  n4, &toCheck ),
1378         GetNodeUV( F,n3,  n1, &toCheck ),
1379         GetNodeUV( F,n4,  n2, &toCheck ),
1380         GetNodeUV( F,n12, n3 ),
1381         GetNodeUV( F,n23, n4 ),
1382         GetNodeUV( F,n34, n2 ),
1383         GetNodeUV( F,n41, n2 )
1384       };
1385       AdjustByPeriod( F, uv, 8 ); // put uv[] within a period (IPAL52698)
1386
1387       uvAvg = calcTFI (0.5, 0.5, uv[0],uv[1],uv[2],uv[3], uv[4],uv[5],uv[6],uv[7] );
1388     }
1389     P = surface->Value( uvAvg );
1390     centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1391     // if ( mySetElemOnShape ) node is not elem!
1392     meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1393   }
1394   else // ( force3d || F.IsNull() )
1395   {
1396     P = calcTFI (0.5, 0.5,
1397                  SMESH_TNodeXYZ(n1),  SMESH_TNodeXYZ(n2),
1398                  SMESH_TNodeXYZ(n3),  SMESH_TNodeXYZ(n4),
1399                  SMESH_TNodeXYZ(n12), SMESH_TNodeXYZ(n23),
1400                  SMESH_TNodeXYZ(n34), SMESH_TNodeXYZ(n41));
1401     centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1402
1403     if ( !F.IsNull() ) // force3d
1404     {
1405       uvAvg = (GetNodeUV(F,n1,n3,&toCheck) +
1406                GetNodeUV(F,n2,n4,&toCheck) +
1407                GetNodeUV(F,n3,n1,&toCheck) +
1408                GetNodeUV(F,n4,n2,&toCheck)) / 4;
1409       //CheckNodeUV( F, centralNode, uvAvg, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1410       meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1411     }
1412     else if ( solidID > 0 )
1413     {
1414       meshDS->SetNodeInVolume( centralNode, solidID );
1415     }
1416     else if ( myShapeID > 0 && mySetElemOnShape )
1417     {
1418       meshDS->SetMeshElementOnShape( centralNode, myShapeID );
1419     }
1420   }
1421   myMapWithCentralNode.insert( std::make_pair( keyOfMap, centralNode ) );
1422   return centralNode;
1423 }
1424
1425 //=======================================================================
1426 //function : GetCentralNode
1427 //purpose  : Return existing or create a new central node for a
1428 //           quadratic triangle given its 6 nodes.
1429 //@param   : force3d - true means node creation in between the given nodes,
1430 //           else node position is found on a geometrical face if any.
1431 //=======================================================================
1432
1433 const SMDS_MeshNode* SMESH_MesherHelper::GetCentralNode(const SMDS_MeshNode* n1,
1434                                                         const SMDS_MeshNode* n2,
1435                                                         const SMDS_MeshNode* n3,
1436                                                         const SMDS_MeshNode* n12,
1437                                                         const SMDS_MeshNode* n23,
1438                                                         const SMDS_MeshNode* n31,
1439                                                         bool                 force3d)
1440 {
1441   SMDS_MeshNode *centralNode = 0; // central node to return
1442
1443   // Find an existing central node
1444
1445   TBiQuad keyOfMap(n1,n2,n3);
1446   std::map<TBiQuad, const SMDS_MeshNode* >::iterator itMapCentralNode;
1447   itMapCentralNode = myMapWithCentralNode.find( keyOfMap );
1448   if ( itMapCentralNode != myMapWithCentralNode.end() ) 
1449   {
1450     return (*itMapCentralNode).second;
1451   }
1452
1453   // Get type of shape for the new central node
1454
1455   TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
1456   int              solidID = -1;
1457   int              faceID = -1;
1458   TopoDS_Shape     shape;
1459   TopTools_ListIteratorOfListOfShape it;
1460
1461   std::map< int, int > faceId2nbNodes;
1462   std::map< int, int > ::iterator itMapWithIdFace;
1463   
1464   SMESHDS_Mesh* meshDS = GetMeshDS();
1465   
1466   // check if a face lies on a FACE, i.e. its all corner nodes lie either on the FACE or
1467   // on sub-shapes of the FACE
1468   if ( GetMesh()->HasShapeToMesh() )
1469   {
1470     const SMDS_MeshNode* nodes[] = { n1, n2, n3 };
1471     for(int i = 0; i < 3; i++)
1472     {
1473       shape = GetSubShapeByNode( nodes[i], meshDS );
1474       if ( shape.IsNull() ) break;
1475       if ( shape.ShapeType() == TopAbs_SOLID )
1476       {
1477         solidID   = nodes[i]->getshapeId();
1478         shapeType = TopAbs_SOLID;
1479         break;
1480       }
1481       if ( shape.ShapeType() == TopAbs_FACE )
1482       {
1483         faceID          = nodes[i]->getshapeId();
1484         itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1485         itMapWithIdFace->second++;
1486       }
1487       else
1488       {
1489         PShapeIteratorPtr it = GetAncestors(shape, *GetMesh(), TopAbs_FACE );
1490         while ( const TopoDS_Shape* face = it->next() )
1491         {
1492           faceID = meshDS->ShapeToIndex( *face );
1493           itMapWithIdFace = faceId2nbNodes.insert( std::make_pair( faceID, 0 ) ).first;
1494           itMapWithIdFace->second++;
1495         }
1496       }
1497     }
1498   }
1499   if ( solidID < 1 && !faceId2nbNodes.empty() ) // SOLID not found
1500   {
1501     // find ID of the FACE the four corner nodes belong to
1502     itMapWithIdFace = faceId2nbNodes.find( myShapeID ); // IPAL52698
1503     if ( itMapWithIdFace != faceId2nbNodes.end() &&
1504          itMapWithIdFace->second == 4 )
1505     {
1506       shapeType = TopAbs_FACE;
1507       faceID = myShapeID;
1508     }
1509     else
1510     {
1511       itMapWithIdFace = faceId2nbNodes.begin();
1512       for ( ; itMapWithIdFace != faceId2nbNodes.end(); ++itMapWithIdFace)
1513       {
1514         if ( itMapWithIdFace->second == 3 )
1515         {
1516           shapeType = TopAbs_FACE;
1517           faceID = (*itMapWithIdFace).first;
1518           break;
1519         }
1520       }
1521     }
1522   }
1523
1524   TopoDS_Face F;
1525   gp_XY       uvAvg;
1526
1527   if ( shapeType == TopAbs_FACE )
1528   {
1529     F = TopoDS::Face( meshDS->IndexToShape( faceID ));
1530     bool checkOK = true, badTria = false;
1531     gp_XY uv[6] = {
1532       GetNodeUV( F, n1, n23, &checkOK ),
1533       GetNodeUV( F, n2, n31, &checkOK ),
1534       GetNodeUV( F, n3, n12, &checkOK ),
1535       GetNodeUV( F, n12, n3, &checkOK ),
1536       GetNodeUV( F, n23, n1, &checkOK ),
1537       GetNodeUV( F, n31, n2, &checkOK )
1538     };
1539     AdjustByPeriod( F, uv, 6 ); // put uv[] within a period (IPAL52698)
1540
1541     uvAvg = GetCenterUV( uv[0],uv[1],uv[2], uv[3],uv[4],uv[5], &badTria );
1542
1543     if ( badTria || !checkOK )
1544       force3d = true;
1545   }
1546
1547   // Create a central node
1548
1549   gp_Pnt P;
1550   if ( !F.IsNull() && !force3d )
1551   {
1552     TopLoc_Location        loc;
1553     Handle( Geom_Surface ) S = BRep_Tool::Surface( F, loc );
1554     P = S->Value( uvAvg.X(), uvAvg.Y() ).Transformed( loc );
1555     centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1556     // if ( mySetElemOnShape ) node is not elem!
1557     meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1558   }
1559   else // ( force3d || F.IsNull() )
1560   {
1561     P = ( SMESH_TNodeXYZ( n12 ) +
1562           SMESH_TNodeXYZ( n23 ) +
1563           SMESH_TNodeXYZ( n31 ) ) / 3;
1564     centralNode = meshDS->AddNode( P.X(), P.Y(), P.Z() );
1565
1566     if ( !F.IsNull() ) // force3d
1567     {
1568       meshDS->SetNodeOnFace( centralNode, faceID, uvAvg.X(), uvAvg.Y() );
1569     }
1570     else if ( solidID > 0 )
1571     {
1572       meshDS->SetNodeInVolume( centralNode, solidID );
1573     }
1574     else if ( myShapeID > 0 && mySetElemOnShape )
1575     {
1576       meshDS->SetMeshElementOnShape( centralNode, myShapeID );
1577     }
1578   }
1579   myMapWithCentralNode.insert( std::make_pair( keyOfMap, centralNode ) );
1580   return centralNode;
1581 }
1582
1583 //=======================================================================
1584 //function : GetMediumNode
1585 //purpose  : Return existing or create a new medium node between given ones
1586 //=======================================================================
1587
1588 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
1589                                                        const SMDS_MeshNode* n2,
1590                                                        bool                 force3d,
1591                                                        TopAbs_ShapeEnum     expectedSupport)
1592 {
1593   // Find existing node
1594
1595   SMESH_TLink link(n1,n2);
1596   ItTLinkNode itLN = myTLinkNodeMap.find( link );
1597   if ( itLN != myTLinkNodeMap.end() ) {
1598     return (*itLN).second;
1599   }
1600
1601   // Create medium node
1602
1603   SMDS_MeshNode* n12;
1604   SMESHDS_Mesh* meshDS = GetMeshDS();
1605
1606   if ( IsSeamShape( n1->getshapeId() ))
1607     // to get a correct UV of a node on seam, the second node must have checked UV
1608     std::swap( n1, n2 );
1609
1610   // get type of shape for the new medium node
1611   int faceID = -1, edgeID = -1;
1612   TopoDS_Edge E; double u [2];
1613   TopoDS_Face F; gp_XY  uv[2];
1614   bool uvOK[2] = { true, true };
1615   const bool useCurSubShape = ( !myShape.IsNull() && myShape.ShapeType() == TopAbs_EDGE );
1616
1617   pair<int, TopAbs_ShapeEnum> pos = GetMediumPos( n1, n2, useCurSubShape, expectedSupport );
1618
1619   // get positions of the given nodes on shapes
1620   if ( pos.second == TopAbs_FACE )
1621   {
1622     F = TopoDS::Face(meshDS->IndexToShape( faceID = pos.first ));
1623     uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
1624     if (( !force3d ) &&
1625         ( HasDegeneratedEdges() || GetSurface( F )->HasSingularities( 1e-7 )))
1626     {
1627       // IPAL52850 (degen VERTEX not at singularity)
1628       // project middle point to a surface
1629       SMESH_TNodeXYZ p1( n1 ), p2( n2 );
1630       gp_Pnt pMid = 0.5 * ( p1 + p2 );
1631       Handle(ShapeAnalysis_Surface) projector = GetSurface( F );
1632       gp_Pnt2d uvMid;
1633       if ( uvOK[0] )
1634         uvMid = projector->NextValueOfUV( uv[0], pMid, BRep_Tool::Tolerance( F ));
1635       else
1636         uvMid = projector->ValueOfUV( pMid, getFaceMaxTol( F ));
1637       if ( projector->Gap() * projector->Gap() < ( p1 - p2 ).SquareModulus() / 4 )
1638       {
1639         gp_Pnt pProj = projector->Value( uvMid );
1640         n12  = meshDS->AddNode( pProj.X(), pProj.Y(), pProj.Z() );
1641         meshDS->SetNodeOnFace( n12, faceID, uvMid.X(), uvMid.Y() );
1642         myTLinkNodeMap.insert( make_pair ( link, n12 ));
1643         return n12;
1644       }
1645     }
1646     uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
1647   }
1648   else if ( pos.second == TopAbs_EDGE )
1649   {
1650     const SMDS_PositionPtr Pos1 = n1->GetPosition();
1651     const SMDS_PositionPtr Pos2 = n2->GetPosition();
1652     if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1653          Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1654          n1->getshapeId() != n2->getshapeId() )
1655     {
1656       // issue 0021006
1657       return getMediumNodeOnComposedWire(n1,n2,force3d);
1658     }
1659     E = TopoDS::Edge(meshDS->IndexToShape( edgeID = pos.first ));
1660     try {
1661       u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
1662       u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
1663     }
1664     catch ( Standard_Failure& f )
1665     {
1666       // issue 22502 / a node is on VERTEX not belonging to E
1667       // issue 22568 / both nodes are on non-connected VERTEXes
1668       return getMediumNodeOnComposedWire(n1,n2,force3d);
1669     }
1670   }
1671
1672   if ( !force3d & uvOK[0] && uvOK[1] )
1673   {
1674     // we try to create medium node using UV parameters of
1675     // nodes, else - medium between corresponding 3d points
1676     if( ! F.IsNull() )
1677     {
1678       //if ( uvOK[0] && uvOK[1] )
1679       {
1680         if ( IsDegenShape( n1->getshapeId() )) {
1681           if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
1682           else                           uv[0].SetCoord( 2, uv[1].Coord( 2 ));
1683         }
1684         else if ( IsDegenShape( n2->getshapeId() )) {
1685           if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
1686           else                           uv[1].SetCoord( 2, uv[0].Coord( 2 ));
1687         }
1688         TopLoc_Location loc;
1689         Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
1690         gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
1691         gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
1692         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1693         // if ( mySetElemOnShape ) node is not elem!
1694         meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
1695         myTLinkNodeMap.insert(make_pair(link,n12));
1696         return n12;
1697       }
1698     }
1699     else if ( !E.IsNull() )
1700     {
1701       double f,l;
1702       Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
1703       if(!C.IsNull())
1704       {
1705         Standard_Boolean isPeriodic = C->IsPeriodic();
1706         double U;
1707         if(isPeriodic) {
1708           Standard_Real Period = C->Period();
1709           Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
1710           Standard_Real pmid = (u[0]+p)/2.;
1711           U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
1712         }
1713         else
1714           U = (u[0]+u[1])/2.;
1715
1716         gp_Pnt P = C->Value( U );
1717         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1718         //if ( mySetElemOnShape ) node is not elem!
1719         meshDS->SetNodeOnEdge(n12, edgeID, U);
1720         myTLinkNodeMap.insert(make_pair(link,n12));
1721         return n12;
1722       }
1723     }
1724   }
1725
1726   // 3d variant
1727   double x = ( n1->X() + n2->X() )/2.;
1728   double y = ( n1->Y() + n2->Y() )/2.;
1729   double z = ( n1->Z() + n2->Z() )/2.;
1730   n12 = meshDS->AddNode(x,y,z);
1731
1732   //if ( mySetElemOnShape ) node is not elem!
1733   {
1734     if ( !F.IsNull() )
1735     {
1736       gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1737       CheckNodeUV( F, n12, UV, 2 * BRep_Tool::Tolerance( F ), /*force=*/true);
1738       meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1739     }
1740     else if ( !E.IsNull() )
1741     {
1742       double U = ( u[0] + u[1] ) / 2.;
1743       CheckNodeU( E, n12, U, 2 * BRep_Tool::Tolerance( E ), /*force=*/true);
1744       meshDS->SetNodeOnEdge(n12, edgeID, U);
1745     }
1746     else if ( myShapeID > 0 && mySetElemOnShape )
1747     {
1748       meshDS->SetMeshElementOnShape(n12, myShapeID);
1749     }
1750   }
1751
1752   myTLinkNodeMap.insert( make_pair( link, n12 ));
1753   return n12;
1754 }
1755
1756 //================================================================================
1757 /*!
1758  * \brief Makes a medium node if nodes reside different edges
1759  */
1760 //================================================================================
1761
1762 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1763                                                                      const SMDS_MeshNode* n2,
1764                                                                      bool                 force3d)
1765 {
1766   SMESH_TNodeXYZ p1( n1 ), p2( n2 );
1767   gp_Pnt      middle = 0.5 * p1 + 0.5 * p2;
1768   SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1769
1770   // To find position on edge and 3D position for n12,
1771   // project <middle> to 2 edges and select projection most close to <middle>
1772
1773   TopoDS_Edge bestEdge;
1774   double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4], f,l;
1775
1776   // get shapes under the nodes
1777   TopoDS_Shape shape[2];
1778   int nbShapes = 0;
1779   for ( int is2nd = 0; is2nd < 2; ++is2nd )
1780   {
1781     const SMDS_MeshNode* n = is2nd ? n2 : n1;
1782     TopoDS_Shape S = GetSubShapeByNode( n, GetMeshDS() );
1783     if ( !S.IsNull() )
1784       shape[ nbShapes++ ] = S;
1785   }
1786   // get EDGEs
1787   vector< TopoDS_Shape > edges;
1788   for ( int iS = 0; iS < nbShapes; ++iS )
1789   {
1790     switch ( shape[iS].ShapeType() ) {
1791     case TopAbs_EDGE:
1792     {
1793       edges.push_back( shape[iS] );
1794       break;
1795     }
1796     case TopAbs_VERTEX:
1797     {
1798       TopoDS_Shape edge;
1799       if ( nbShapes == 2 && iS==0 && shape[1-iS].ShapeType() == TopAbs_VERTEX )
1800         edge = GetCommonAncestor( shape[iS], shape[1-iS], *myMesh, TopAbs_EDGE );
1801
1802       if ( edge.IsNull() )
1803       {
1804         PShapeIteratorPtr eIt = GetAncestors( shape[iS], *myMesh, TopAbs_EDGE );
1805         while( const TopoDS_Shape* e = eIt->next() )
1806           edges.push_back( *e );
1807       }
1808       break;
1809     }
1810     case TopAbs_FACE:
1811     {
1812       if ( nbShapes == 1 || shape[1-iS].ShapeType() < TopAbs_EDGE )
1813         for ( TopExp_Explorer e( shape[iS], TopAbs_EDGE ); e.More(); e.Next() )
1814           edges.push_back( e.Current() );
1815       break;
1816     }
1817     default:
1818       continue;
1819     }
1820   }
1821   // project to get U of projection and distance from middle to projection
1822   for ( size_t iE = 0; iE < edges.size(); ++iE )
1823   {
1824     const TopoDS_Edge& edge = TopoDS::Edge( edges[ iE ]);
1825     distXYZ[0] = distMiddleProj;
1826     double testU = 0;
1827     CheckNodeU( edge, n12, testU, 2 * BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1828     if ( distXYZ[0] < distMiddleProj )
1829     {
1830       distMiddleProj = distXYZ[0];
1831       u = testU;
1832       bestEdge = edge;
1833     }
1834   }
1835   // {
1836   //   // both projections failed; set n12 on the edge of n1 with U of a common vertex
1837   //   TopoDS_Vertex vCommon;
1838   //   if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1839   //     u = BRep_Tool::Parameter( vCommon, edges[0] );
1840   //   else
1841   //   {
1842   //     double f,l, u0 = GetNodeU( edges[0], n1 );
1843   //     BRep_Tool::Range( edges[0],f,l );
1844   //     u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1845   //   }
1846   //   iOkEdge = 0;
1847   //   distMiddleProj = 0;
1848   // }
1849
1850   if ( !bestEdge.IsNull() )
1851   {
1852     // move n12 to position of a successfull projection
1853     //double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1854     if ( !force3d /*&& distMiddleProj > 2*tol*/ )
1855     {
1856       TopLoc_Location loc;
1857       Handle(Geom_Curve) curve = BRep_Tool::Curve( bestEdge,loc,f,l );
1858       gp_Pnt p = curve->Value( u ).Transformed( loc );
1859       GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1860     }
1861     //if ( mySetElemOnShape ) node is not elem!
1862     {
1863       int edgeID = GetMeshDS()->ShapeToIndex( bestEdge );
1864       if ( edgeID != n12->getshapeId() )
1865         GetMeshDS()->UnSetNodeOnShape( n12 );
1866       GetMeshDS()->SetNodeOnEdge(n12, edgeID, u);
1867     }
1868   }
1869   myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1870
1871   return n12;
1872 }
1873
1874 //=======================================================================
1875 //function : AddNode
1876 //purpose  : Creates a node
1877 //=======================================================================
1878
1879 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID,
1880                                            double u, double v)
1881 {
1882   SMESHDS_Mesh * meshDS = GetMeshDS();
1883   SMDS_MeshNode* node = 0;
1884   if ( ID )
1885     node = meshDS->AddNodeWithID( x, y, z, ID );
1886   else
1887     node = meshDS->AddNode( x, y, z );
1888   if ( mySetElemOnShape && myShapeID > 0 ) { // node is not elem ?
1889     switch ( myShape.ShapeType() ) {
1890     case TopAbs_SOLID:  meshDS->SetNodeInVolume( node, myShapeID);       break;
1891     case TopAbs_SHELL:  meshDS->SetNodeInVolume( node, myShapeID);       break;
1892     case TopAbs_FACE:   meshDS->SetNodeOnFace(   node, myShapeID, u, v); break;
1893     case TopAbs_EDGE:   meshDS->SetNodeOnEdge(   node, myShapeID, u);    break;
1894     case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID);       break;
1895     default: ;
1896     }
1897   }
1898   return node;
1899 }
1900
1901 //=======================================================================
1902 //function : AddEdge
1903 //purpose  : Creates quadratic or linear edge
1904 //=======================================================================
1905
1906 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1907                                            const SMDS_MeshNode* n2,
1908                                            const int            id,
1909                                            const bool           force3d)
1910 {
1911   SMESHDS_Mesh * meshDS = GetMeshDS();
1912   
1913   SMDS_MeshEdge* edge = 0;
1914   if (myCreateQuadratic) {
1915     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1916     if(id)
1917       edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1918     else
1919       edge = meshDS->AddEdge(n1, n2, n12);
1920   }
1921   else {
1922     if(id)
1923       edge = meshDS->AddEdgeWithID(n1, n2, id);
1924     else
1925       edge = meshDS->AddEdge(n1, n2);
1926   }
1927
1928   if ( mySetElemOnShape && myShapeID > 0 )
1929     meshDS->SetMeshElementOnShape( edge, myShapeID );
1930
1931   return edge;
1932 }
1933
1934 //=======================================================================
1935 //function : AddFace
1936 //purpose  : Creates quadratic or linear triangle
1937 //=======================================================================
1938
1939 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1940                                            const SMDS_MeshNode* n2,
1941                                            const SMDS_MeshNode* n3,
1942                                            const int id,
1943                                            const bool force3d)
1944 {
1945   SMESHDS_Mesh * meshDS = GetMeshDS();
1946   SMDS_MeshFace* elem = 0;
1947
1948   if( n1==n2 || n2==n3 || n3==n1 )
1949     return elem;
1950
1951   if(!myCreateQuadratic) {
1952     if(id)
1953       elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1954     else
1955       elem = meshDS->AddFace(n1, n2, n3);
1956   }
1957   else {
1958     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
1959     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_FACE );
1960     const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_FACE );
1961     if(myCreateBiQuadratic)
1962     {
1963      const SMDS_MeshNode* nCenter = GetCentralNode(n1, n2, n3, n12, n23, n31, force3d);
1964      if(id)
1965        elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, nCenter, id);
1966      else
1967        elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31, nCenter);
1968     }
1969     else
1970     {
1971       if(id)
1972         elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1973       else
1974         elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1975     }
1976   }
1977   if ( mySetElemOnShape && myShapeID > 0 )
1978     meshDS->SetMeshElementOnShape( elem, myShapeID );
1979
1980   return elem;
1981 }
1982
1983 //=======================================================================
1984 //function : AddFace
1985 //purpose  : Creates bi-quadratic, quadratic or linear quadrangle
1986 //=======================================================================
1987
1988 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1989                                            const SMDS_MeshNode* n2,
1990                                            const SMDS_MeshNode* n3,
1991                                            const SMDS_MeshNode* n4,
1992                                            const int            id,
1993                                            const bool           force3d)
1994 {
1995   SMESHDS_Mesh * meshDS = GetMeshDS();
1996   SMDS_MeshFace* elem = 0;
1997
1998   if( n1==n2 ) {
1999     return AddFace(n1,n3,n4,id,force3d);
2000   }
2001   if( n1==n3 ) {
2002     return AddFace(n1,n2,n4,id,force3d);
2003   }
2004   if( n1==n4 ) {
2005     return AddFace(n1,n2,n3,id,force3d);
2006   }
2007   if( n2==n3 ) {
2008     return AddFace(n1,n2,n4,id,force3d);
2009   }
2010   if( n2==n4 ) {
2011     return AddFace(n1,n2,n3,id,force3d);
2012   }
2013   if( n3==n4 ) {
2014     return AddFace(n1,n2,n3,id,force3d);
2015   }
2016
2017   if(!myCreateQuadratic) {
2018     if(id)
2019       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
2020     else
2021       elem = meshDS->AddFace(n1, n2, n3, n4);
2022   }
2023   else {
2024     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
2025     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_FACE );
2026     const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_FACE );
2027     const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_FACE );
2028     if(myCreateBiQuadratic)
2029     {
2030      const SMDS_MeshNode* nCenter = GetCentralNode(n1, n2, n3, n4, n12, n23, n34, n41, force3d);
2031      if(id)
2032        elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, nCenter, id);
2033      else
2034        elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41, nCenter);
2035     }
2036     else
2037     {
2038       if(id)
2039         elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
2040       else
2041         elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
2042     }
2043   }
2044   if ( mySetElemOnShape && myShapeID > 0 )
2045     meshDS->SetMeshElementOnShape( elem, myShapeID );
2046
2047   return elem;
2048 }
2049
2050 //=======================================================================
2051 //function : AddPolygonalFace
2052 //purpose  : Creates polygon, with additional nodes in quadratic mesh
2053 //=======================================================================
2054
2055 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
2056                                                      const int                           id,
2057                                                      const bool                          force3d)
2058 {
2059   SMESHDS_Mesh * meshDS = GetMeshDS();
2060   SMDS_MeshFace* elem = 0;
2061
2062   if(!myCreateQuadratic)
2063   {
2064     if(id)
2065       elem = meshDS->AddPolygonalFaceWithID(nodes, id);
2066     else
2067       elem = meshDS->AddPolygonalFace(nodes);
2068   }
2069   else
2070   {
2071     vector<const SMDS_MeshNode*> newNodes( nodes.size() * 2 );
2072     newNodes = nodes;
2073     for ( size_t i = 0; i < nodes.size(); ++i )
2074     {
2075       const SMDS_MeshNode* n1 = nodes[i];
2076       const SMDS_MeshNode* n2 = nodes[(i+1)%nodes.size()];
2077       const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_FACE );
2078       newNodes.push_back( n12 );
2079     }
2080     if(id)
2081       elem = meshDS->AddQuadPolygonalFaceWithID(newNodes, id);
2082     else
2083       elem = meshDS->AddQuadPolygonalFace(newNodes);
2084   }
2085   if ( mySetElemOnShape && myShapeID > 0 )
2086     meshDS->SetMeshElementOnShape( elem, myShapeID );
2087
2088   return elem;
2089 }
2090
2091 //=======================================================================
2092 //function : AddVolume
2093 //purpose  : Creates quadratic or linear prism
2094 //=======================================================================
2095
2096 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2097                                                const SMDS_MeshNode* n2,
2098                                                const SMDS_MeshNode* n3,
2099                                                const SMDS_MeshNode* n4,
2100                                                const SMDS_MeshNode* n5,
2101                                                const SMDS_MeshNode* n6,
2102                                                const int id,
2103                                                const bool force3d)
2104 {
2105   SMESHDS_Mesh * meshDS = GetMeshDS();
2106   SMDS_MeshVolume* elem = 0;
2107   if(!myCreateQuadratic) {
2108     if(id)
2109       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
2110     else
2111       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
2112   }
2113   else {
2114     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2115     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2116     const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_SOLID );
2117
2118     const SMDS_MeshNode* n45 = GetMediumNode( n4, n5, force3d, TopAbs_SOLID );
2119     const SMDS_MeshNode* n56 = GetMediumNode( n5, n6, force3d, TopAbs_SOLID );
2120     const SMDS_MeshNode* n64 = GetMediumNode( n6, n4, force3d, TopAbs_SOLID );
2121
2122     const SMDS_MeshNode* n14 = GetMediumNode( n1, n4, force3d, TopAbs_SOLID );
2123     const SMDS_MeshNode* n25 = GetMediumNode( n2, n5, force3d, TopAbs_SOLID );
2124     const SMDS_MeshNode* n36 = GetMediumNode( n3, n6, force3d, TopAbs_SOLID );
2125
2126     if(id)
2127       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
2128                                      n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
2129     else
2130       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
2131                                n12, n23, n31, n45, n56, n64, n14, n25, n36);
2132   }
2133   if ( mySetElemOnShape && myShapeID > 0 )
2134     meshDS->SetMeshElementOnShape( elem, myShapeID );
2135
2136   return elem;
2137 }
2138
2139 //=======================================================================
2140 //function : AddVolume
2141 //purpose  : Creates quadratic or linear tetrahedron
2142 //=======================================================================
2143
2144 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2145                                                const SMDS_MeshNode* n2,
2146                                                const SMDS_MeshNode* n3,
2147                                                const SMDS_MeshNode* n4,
2148                                                const int id,
2149                                                const bool force3d)
2150 {
2151   SMESHDS_Mesh * meshDS = GetMeshDS();
2152   SMDS_MeshVolume* elem = 0;
2153   if(!myCreateQuadratic) {
2154     if(id)
2155       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
2156     else
2157       elem = meshDS->AddVolume(n1, n2, n3, n4);
2158   }
2159   else {
2160     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2161     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2162     const SMDS_MeshNode* n31 = GetMediumNode( n3, n1, force3d, TopAbs_SOLID );
2163
2164     const SMDS_MeshNode* n14 = GetMediumNode( n1, n4, force3d, TopAbs_SOLID );
2165     const SMDS_MeshNode* n24 = GetMediumNode( n2, n4, force3d, TopAbs_SOLID );
2166     const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2167
2168     if(id)
2169       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
2170     else
2171       elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
2172   }
2173   if ( mySetElemOnShape && myShapeID > 0 )
2174     meshDS->SetMeshElementOnShape( elem, myShapeID );
2175
2176   return elem;
2177 }
2178
2179 //=======================================================================
2180 //function : AddVolume
2181 //purpose  : Creates quadratic or linear pyramid
2182 //=======================================================================
2183
2184 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2185                                                const SMDS_MeshNode* n2,
2186                                                const SMDS_MeshNode* n3,
2187                                                const SMDS_MeshNode* n4,
2188                                                const SMDS_MeshNode* n5,
2189                                                const int id,
2190                                                const bool force3d)
2191 {
2192   SMDS_MeshVolume* elem = 0;
2193   if(!myCreateQuadratic) {
2194     if(id)
2195       elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
2196     else
2197       elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
2198   }
2199   else {
2200     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2201     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2202     const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2203     const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_SOLID );
2204
2205     const SMDS_MeshNode* n15 = GetMediumNode( n1, n5, force3d, TopAbs_SOLID );
2206     const SMDS_MeshNode* n25 = GetMediumNode( n2, n5, force3d, TopAbs_SOLID );
2207     const SMDS_MeshNode* n35 = GetMediumNode( n3, n5, force3d, TopAbs_SOLID );
2208     const SMDS_MeshNode* n45 = GetMediumNode( n4, n5, force3d, TopAbs_SOLID );
2209
2210     if(id)
2211       elem = GetMeshDS()->AddVolumeWithID ( n1,  n2,  n3,  n4,  n5,
2212                                             n12, n23, n34, n41,
2213                                             n15, n25, n35, n45,
2214                                             id);
2215     else
2216       elem = GetMeshDS()->AddVolume( n1,  n2,  n3,  n4,  n5,
2217                                      n12, n23, n34, n41,
2218                                      n15, n25, n35, n45);
2219   }
2220   if ( mySetElemOnShape && myShapeID > 0 )
2221     GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
2222
2223   return elem;
2224 }
2225
2226 //=======================================================================
2227 //function : AddVolume
2228 //purpose  : Creates tri-quadratic, quadratic or linear hexahedron
2229 //=======================================================================
2230
2231 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2232                                                const SMDS_MeshNode* n2,
2233                                                const SMDS_MeshNode* n3,
2234                                                const SMDS_MeshNode* n4,
2235                                                const SMDS_MeshNode* n5,
2236                                                const SMDS_MeshNode* n6,
2237                                                const SMDS_MeshNode* n7,
2238                                                const SMDS_MeshNode* n8,
2239                                                const int id,
2240                                                const bool force3d)
2241 {
2242   SMESHDS_Mesh * meshDS = GetMeshDS();
2243   SMDS_MeshVolume* elem = 0;
2244   if(!myCreateQuadratic) {
2245     if(id)
2246       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
2247     else
2248       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
2249   }
2250   else {
2251     const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2252     const SMDS_MeshNode* n23 = GetMediumNode( n2, n3, force3d, TopAbs_SOLID );
2253     const SMDS_MeshNode* n34 = GetMediumNode( n3, n4, force3d, TopAbs_SOLID );
2254     const SMDS_MeshNode* n41 = GetMediumNode( n4, n1, force3d, TopAbs_SOLID );
2255
2256     const SMDS_MeshNode* n56 = GetMediumNode( n5, n6, force3d, TopAbs_SOLID );
2257     const SMDS_MeshNode* n67 = GetMediumNode( n6, n7, force3d, TopAbs_SOLID );
2258     const SMDS_MeshNode* n78 = GetMediumNode( n7, n8, force3d, TopAbs_SOLID );
2259     const SMDS_MeshNode* n85 = GetMediumNode( n8, n5, force3d, TopAbs_SOLID );
2260
2261     const SMDS_MeshNode* n15 = GetMediumNode( n1, n5, force3d, TopAbs_SOLID );
2262     const SMDS_MeshNode* n26 = GetMediumNode( n2, n6, force3d, TopAbs_SOLID );
2263     const SMDS_MeshNode* n37 = GetMediumNode( n3, n7, force3d, TopAbs_SOLID );
2264     const SMDS_MeshNode* n48 = GetMediumNode( n4, n8, force3d, TopAbs_SOLID );
2265     if ( myCreateBiQuadratic )
2266     {
2267       const SMDS_MeshNode* n1234 = GetCentralNode( n1,n2,n3,n4,n12,n23,n34,n41,force3d );
2268       const SMDS_MeshNode* n1256 = GetCentralNode( n1,n2,n5,n6,n12,n26,n56,n15,force3d );
2269       const SMDS_MeshNode* n2367 = GetCentralNode( n2,n3,n6,n7,n23,n37,n67,n26,force3d );
2270       const SMDS_MeshNode* n3478 = GetCentralNode( n3,n4,n7,n8,n34,n48,n78,n37,force3d );
2271       const SMDS_MeshNode* n1458 = GetCentralNode( n1,n4,n5,n8,n41,n48,n15,n85,force3d );
2272       const SMDS_MeshNode* n5678 = GetCentralNode( n5,n6,n7,n8,n56,n67,n78,n85,force3d );
2273
2274       vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
2275
2276       pointsOnShapes[ SMESH_Block::ID_V000 ] = SMESH_TNodeXYZ( n4 );
2277       pointsOnShapes[ SMESH_Block::ID_V100 ] = SMESH_TNodeXYZ( n8 );
2278       pointsOnShapes[ SMESH_Block::ID_V010 ] = SMESH_TNodeXYZ( n3 );
2279       pointsOnShapes[ SMESH_Block::ID_V110 ] = SMESH_TNodeXYZ( n7 );
2280       pointsOnShapes[ SMESH_Block::ID_V001 ] = SMESH_TNodeXYZ( n1 );
2281       pointsOnShapes[ SMESH_Block::ID_V101 ] = SMESH_TNodeXYZ( n5 );
2282       pointsOnShapes[ SMESH_Block::ID_V011 ] = SMESH_TNodeXYZ( n2 );
2283       pointsOnShapes[ SMESH_Block::ID_V111 ] = SMESH_TNodeXYZ( n6 );
2284
2285       pointsOnShapes[ SMESH_Block::ID_Ex00 ] = SMESH_TNodeXYZ( n48 );
2286       pointsOnShapes[ SMESH_Block::ID_Ex10 ] = SMESH_TNodeXYZ( n37 );
2287       pointsOnShapes[ SMESH_Block::ID_E0y0 ] = SMESH_TNodeXYZ( n15 );
2288       pointsOnShapes[ SMESH_Block::ID_E1y0 ] = SMESH_TNodeXYZ( n26 );
2289       pointsOnShapes[ SMESH_Block::ID_Ex01 ] = SMESH_TNodeXYZ( n34 );
2290       pointsOnShapes[ SMESH_Block::ID_Ex11 ] = SMESH_TNodeXYZ( n78 );
2291       pointsOnShapes[ SMESH_Block::ID_E0y1 ] = SMESH_TNodeXYZ( n12 );
2292       pointsOnShapes[ SMESH_Block::ID_E1y1 ] = SMESH_TNodeXYZ( n56 );
2293       pointsOnShapes[ SMESH_Block::ID_E00z ] = SMESH_TNodeXYZ( n41 );
2294       pointsOnShapes[ SMESH_Block::ID_E10z ] = SMESH_TNodeXYZ( n85 );
2295       pointsOnShapes[ SMESH_Block::ID_E01z ] = SMESH_TNodeXYZ( n23 );
2296       pointsOnShapes[ SMESH_Block::ID_E11z ] = SMESH_TNodeXYZ( n67 );
2297
2298       pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = SMESH_TNodeXYZ( n3478 );
2299       pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = SMESH_TNodeXYZ( n1256 );
2300       pointsOnShapes[ SMESH_Block::ID_Fx0z ] = SMESH_TNodeXYZ( n1458 );
2301       pointsOnShapes[ SMESH_Block::ID_Fx1z ] = SMESH_TNodeXYZ( n2367 );
2302       pointsOnShapes[ SMESH_Block::ID_F0yz ] = SMESH_TNodeXYZ( n1234 );
2303       pointsOnShapes[ SMESH_Block::ID_F1yz ] = SMESH_TNodeXYZ( n5678 );
2304
2305       gp_XYZ centerCube(0.5, 0.5, 0.5);
2306       gp_XYZ nCenterElem;
2307       SMESH_Block::ShellPoint( centerCube, pointsOnShapes, nCenterElem );
2308       const SMDS_MeshNode* nCenter =
2309         meshDS->AddNode( nCenterElem.X(), nCenterElem.Y(), nCenterElem.Z() );
2310       meshDS->SetNodeInVolume( nCenter, myShapeID );
2311
2312       if(id)
2313         elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
2314                                        n12, n23, n34, n41, n56, n67,
2315                                        n78, n85, n15, n26, n37, n48,
2316                                        n1234, n1256, n2367, n3478, n1458, n5678, nCenter, id);
2317       else
2318         elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
2319                                  n12, n23, n34, n41, n56, n67,
2320                                  n78, n85, n15, n26, n37, n48,
2321                                  n1234, n1256, n2367, n3478, n1458, n5678, nCenter);
2322     }
2323     else
2324     {
2325       if(id)
2326         elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
2327                                        n12, n23, n34, n41, n56, n67,
2328                                        n78, n85, n15, n26, n37, n48, id);
2329       else
2330         elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
2331                                  n12, n23, n34, n41, n56, n67,
2332                                  n78, n85, n15, n26, n37, n48);
2333     }
2334   }
2335   if ( mySetElemOnShape && myShapeID > 0 )
2336     meshDS->SetMeshElementOnShape( elem, myShapeID );
2337
2338   return elem;
2339 }
2340
2341 //=======================================================================
2342 //function : AddVolume
2343 //purpose  : Creates LINEAR!!!!!!!!! octahedron
2344 //=======================================================================
2345
2346 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
2347                                                const SMDS_MeshNode* n2,
2348                                                const SMDS_MeshNode* n3,
2349                                                const SMDS_MeshNode* n4,
2350                                                const SMDS_MeshNode* n5,
2351                                                const SMDS_MeshNode* n6,
2352                                                const SMDS_MeshNode* n7,
2353                                                const SMDS_MeshNode* n8,
2354                                                const SMDS_MeshNode* n9,
2355                                                const SMDS_MeshNode* n10,
2356                                                const SMDS_MeshNode* n11,
2357                                                const SMDS_MeshNode* n12,
2358                                                const int id, 
2359                                                bool force3d)
2360 {
2361   SMESHDS_Mesh * meshDS = GetMeshDS();
2362   SMDS_MeshVolume* elem = 0;
2363   if(id)
2364     elem = meshDS->AddVolumeWithID(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,id);
2365   else
2366     elem = meshDS->AddVolume(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12);
2367   if ( mySetElemOnShape && myShapeID > 0 )
2368     meshDS->SetMeshElementOnShape( elem, myShapeID );
2369   return elem;
2370 }
2371
2372 //=======================================================================
2373 //function : AddPolyhedralVolume
2374 //purpose  : Creates polyhedron. In quadratic mesh, adds medium nodes
2375 //=======================================================================
2376
2377 SMDS_MeshVolume*
2378 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
2379                                          const std::vector<int>&                  quantities,
2380                                          const int                                id,
2381                                          const bool                               force3d)
2382 {
2383   SMESHDS_Mesh * meshDS = GetMeshDS();
2384   SMDS_MeshVolume* elem = 0;
2385   if(!myCreateQuadratic)
2386   {
2387     if(id)
2388       elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
2389     else
2390       elem = meshDS->AddPolyhedralVolume(nodes, quantities);
2391   }
2392   else
2393   {
2394     vector<const SMDS_MeshNode*> newNodes;
2395     vector<int> newQuantities;
2396     for ( size_t iFace = 0, iN = 0; iFace < quantities.size(); ++iFace )
2397     {
2398       int nbNodesInFace = quantities[iFace];
2399       newQuantities.push_back(0);
2400       for ( int i = 0; i < nbNodesInFace; ++i )
2401       {
2402         const SMDS_MeshNode* n1 = nodes[ iN + i ];
2403         newNodes.push_back( n1 );
2404         newQuantities.back()++;
2405
2406         const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
2407         // if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
2408         //      n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
2409         {
2410           const SMDS_MeshNode* n12 = GetMediumNode( n1, n2, force3d, TopAbs_SOLID );
2411           newNodes.push_back( n12 );
2412           newQuantities.back()++;
2413         }
2414       }
2415       iN += nbNodesInFace;
2416     }
2417     if(id)
2418       elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
2419     else
2420       elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
2421   }
2422   if ( mySetElemOnShape && myShapeID > 0 )
2423     meshDS->SetMeshElementOnShape( elem, myShapeID );
2424
2425   return elem;
2426 }
2427
2428 namespace
2429 {
2430   //================================================================================
2431   /*!
2432    * \brief Check if a node belongs to any face of sub-mesh
2433    */
2434   //================================================================================
2435
2436   bool isNodeInSubMesh( const SMDS_MeshNode* n, const SMESHDS_SubMesh* sm )
2437   {
2438     SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
2439     while ( fIt->more() )
2440       if ( sm->Contains( fIt->next() ))
2441         return true;
2442     return false;
2443   }
2444 }
2445
2446 //=======================================================================
2447 //function : IsSameElemGeometry
2448 //purpose  : Returns true if all elements of a sub-mesh are of same shape
2449 //=======================================================================
2450
2451 bool SMESH_MesherHelper::IsSameElemGeometry(const SMESHDS_SubMesh* smDS,
2452                                             SMDSAbs_GeometryType   shape,
2453                                             const bool             nullSubMeshRes)
2454 {
2455   if ( !smDS ) return nullSubMeshRes;
2456
2457   SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
2458   while ( elemIt->more() ) {
2459     const SMDS_MeshElement* e = elemIt->next();
2460     if ( e->GetGeomType() != shape )
2461       return false;
2462   }
2463   return true;
2464 }
2465
2466 //=======================================================================
2467 //function : LoadNodeColumns
2468 //purpose  : Load nodes bound to face into a map of node columns
2469 //=======================================================================
2470
2471 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
2472                                          const TopoDS_Face& theFace,
2473                                          const TopoDS_Edge& theBaseEdge,
2474                                          SMESHDS_Mesh*      theMesh,
2475                                          SMESH_ProxyMesh*   theProxyMesh)
2476 {
2477   return LoadNodeColumns(theParam2ColumnMap,
2478                          theFace,
2479                          std::list<TopoDS_Edge>(1,theBaseEdge),
2480                          theMesh,
2481                          theProxyMesh);
2482 }
2483
2484 //=======================================================================
2485 //function : LoadNodeColumns
2486 //purpose  : Load nodes bound to face into a map of node columns
2487 //=======================================================================
2488
2489 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap &            theParam2ColumnMap,
2490                                          const TopoDS_Face&            theFace,
2491                                          const std::list<TopoDS_Edge>& theBaseSide,
2492                                          SMESHDS_Mesh*                 theMesh,
2493                                          SMESH_ProxyMesh*              theProxyMesh)
2494 {
2495   // get a right sub-mesh of theFace
2496
2497   const SMESHDS_SubMesh* faceSubMesh = 0;
2498   if ( theProxyMesh )
2499   {
2500     faceSubMesh = theProxyMesh->GetSubMesh( theFace );
2501     if ( !faceSubMesh ||
2502          faceSubMesh->NbElements() == 0 ||
2503          theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
2504     {
2505       // can use a proxy sub-mesh with not temporary elements only
2506       faceSubMesh = 0;
2507       theProxyMesh = 0;
2508     }
2509   }
2510   if ( !faceSubMesh )
2511     faceSubMesh = theMesh->MeshElements( theFace );
2512   if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
2513     return false;
2514
2515   if ( theParam2ColumnMap.empty() )
2516   {
2517     // get data of edges for normalization of params
2518     vector< double > length;
2519     double fullLen = 0;
2520     list<TopoDS_Edge>::const_iterator edge;
2521     {
2522       for ( edge = theBaseSide.begin(); edge != theBaseSide.end(); ++edge )
2523       {
2524         double len = std::max( 1e-10, SMESH_Algo::EdgeLength( *edge ));
2525         fullLen += len;
2526         length.push_back( len );
2527       }
2528     }
2529
2530     // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
2531     edge = theBaseSide.begin();
2532     for ( int iE = 0; edge != theBaseSide.end(); ++edge, ++iE )
2533     {
2534       map< double, const SMDS_MeshNode*> sortedBaseNN;
2535       SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNN );
2536
2537       map< double, const SMDS_MeshNode*>::iterator u_n;
2538       // pb with mesh_Projection_2D_00/A1 fixed by adding expectedSupport arg to GetMediumPos()
2539       // so the following solution is commented (hope forever :)
2540       //
2541       // SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNN,
2542       // // SMDSAbs_Edge here is needed to be coherent with
2543       // // StdMeshers_FaceSide used by Quadrangle to get nodes
2544       // // on EDGE; else pb in mesh_Projection_2D_00/A1 where a
2545       // // medium node on EDGE is medium in a triangle but not
2546       // // in a segment
2547       // SMDSAbs_Edge );
2548       // if ( faceSubMesh->GetElements()->next()->IsQuadratic() )
2549       //   // filter off nodes medium in faces on theFace (same pb with mesh_Projection_2D_00/A1)
2550       //   for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end() ;     )
2551       //   {
2552       //     const SMDS_MeshNode* node = u_n->second;
2553       //     SMDS_ElemIteratorPtr faceIt = node->GetInverseElementIterator( SMDSAbs_Face );
2554       //     if ( faceIt->more() && node ) {
2555       //       const SMDS_MeshElement* face = faceIt->next();
2556       //       if ( faceSubMesh->Contains( face ) && face->IsMediumNode( node ))
2557       //         node = 0;
2558       //     }
2559       //     if ( !node )
2560       //       sortedBaseNN.erase( u_n++ );
2561       //     else
2562       //       ++u_n;
2563       //   }
2564       if ( sortedBaseNN.empty() ) continue;
2565
2566       u_n = sortedBaseNN.begin();
2567       if ( theProxyMesh ) // from sortedBaseNN remove nodes not shared by faces of faceSubMesh
2568       {
2569         const SMDS_MeshNode* n1 = (++sortedBaseNN.begin())->second;
2570         const SMDS_MeshNode* n2 = (++sortedBaseNN.rbegin())->second;
2571         bool allNodesAreProxy = ( n1 != theProxyMesh->GetProxyNode( n1 ) &&
2572                                   n2 != theProxyMesh->GetProxyNode( n2 ));
2573         if ( allNodesAreProxy )
2574           for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
2575             u_n->second = theProxyMesh->GetProxyNode( u_n->second );
2576
2577         if ( u_n = sortedBaseNN.begin(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
2578         {
2579           while ( ++u_n != sortedBaseNN.end() && !isNodeInSubMesh( u_n->second, faceSubMesh ));
2580           sortedBaseNN.erase( sortedBaseNN.begin(), u_n );
2581         }
2582         if ( !sortedBaseNN.empty() )
2583           if ( u_n = --sortedBaseNN.end(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
2584           {
2585             while ( u_n != sortedBaseNN.begin() && !isNodeInSubMesh( (--u_n)->second, faceSubMesh ));
2586             sortedBaseNN.erase( ++u_n, sortedBaseNN.end() );
2587           }
2588         if ( sortedBaseNN.empty() ) continue;
2589       }
2590
2591       double f, l;
2592       BRep_Tool::Range( *edge, f, l );
2593       if ( edge->Orientation() == TopAbs_REVERSED ) std::swap( f, l );
2594       const double coeff = 1. / ( l - f ) * length[iE] / fullLen;
2595       const double prevPar = theParam2ColumnMap.empty() ? 0 : theParam2ColumnMap.rbegin()->first;
2596       for ( u_n = sortedBaseNN.begin(); u_n != sortedBaseNN.end(); u_n++ )
2597       {
2598         double par = prevPar + coeff * ( u_n->first - f );
2599         TParam2ColumnMap::iterator u2nn =
2600           theParam2ColumnMap.insert( theParam2ColumnMap.end(), make_pair( par, TNodeColumn()));
2601         u2nn->second.push_back( u_n->second );
2602       }
2603     }
2604     if ( theParam2ColumnMap.size() < 2 )
2605       return false;
2606   }
2607
2608   // nb rows of nodes
2609   size_t prevNbRows     = theParam2ColumnMap.begin()->second.size(); // current, at least 1 here
2610   size_t expectNbRows = faceSubMesh->NbElements() / ( theParam2ColumnMap.size()-1 ); // to be added
2611
2612   // fill theParam2ColumnMap column by column by passing from nodes on
2613   // theBaseEdge up via mesh faces on theFace
2614
2615   TParam2ColumnMap::iterator par_nVec_1, par_nVec_2;
2616   par_nVec_2 = theParam2ColumnMap.begin();
2617   par_nVec_1 = par_nVec_2++;
2618   TIDSortedElemSet emptySet, avoidSet;
2619   for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
2620   {
2621     vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
2622     vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
2623     nCol1.resize( prevNbRows + expectNbRows );
2624     nCol2.resize( prevNbRows + expectNbRows );
2625
2626     int i1, i2; size_t foundNbRows = 0;
2627     const SMDS_MeshNode *n1 = nCol1[ prevNbRows-1 ];
2628     const SMDS_MeshNode *n2 = nCol2[ prevNbRows-1 ];
2629     // find face sharing node n1 and n2 and belonging to faceSubMesh
2630     while ( const SMDS_MeshElement* face =
2631             SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
2632     {
2633       if ( faceSubMesh->Contains( face ))
2634       {
2635         int nbNodes = face->NbCornerNodes();
2636         if ( nbNodes != 4 )
2637           return false;
2638         if ( foundNbRows + 1 > expectNbRows )
2639           return false;
2640         n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
2641         n2 = face->GetNode( (i1+2) % 4 );
2642         nCol1[ prevNbRows + foundNbRows] = n1;
2643         nCol2[ prevNbRows + foundNbRows] = n2;
2644         ++foundNbRows;
2645       }
2646       avoidSet.insert( face );
2647     }
2648     if ((size_t) foundNbRows != expectNbRows )
2649       return false;
2650     avoidSet.clear();
2651   }
2652   return ( theParam2ColumnMap.size() > 1 &&
2653            theParam2ColumnMap.begin()->second.size() == prevNbRows + expectNbRows );
2654 }
2655
2656 namespace
2657 {
2658   //================================================================================
2659   /*!
2660    * \brief Return true if a node is at a corner of a 2D structured mesh of FACE
2661    */
2662   //================================================================================
2663
2664   bool isCornerOfStructure( const SMDS_MeshNode*   n,
2665                             const SMESHDS_SubMesh* faceSM,
2666                             SMESH_MesherHelper&    faceAnalyser )
2667   {
2668     int nbFacesInSM = 0;
2669     if ( n ) {
2670       SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
2671       while ( fIt->more() )
2672         nbFacesInSM += faceSM->Contains( fIt->next() );
2673     }
2674     if ( nbFacesInSM == 1 )
2675       return true;
2676
2677     if ( nbFacesInSM == 2 && n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
2678     {
2679       return faceAnalyser.IsRealSeam( n->getshapeId() );
2680     }
2681     return false;
2682   }
2683 }
2684
2685 //=======================================================================
2686 //function : IsStructured
2687 //purpose  : Return true if 2D mesh on FACE is a structured rectangle
2688 //=======================================================================
2689
2690 bool SMESH_MesherHelper::IsStructured( SMESH_subMesh* faceSM )
2691 {
2692   SMESHDS_SubMesh* fSM = faceSM->GetSubMeshDS();
2693   if ( !fSM || fSM->NbElements() == 0 )
2694     return false;
2695
2696   list< TopoDS_Edge > edges;
2697   list< int > nbEdgesInWires;
2698   int nbWires = SMESH_Block::GetOrderedEdges( TopoDS::Face( faceSM->GetSubShape() ),
2699                                               edges, nbEdgesInWires );
2700   if ( nbWires != 1 /*|| nbEdgesInWires.front() != 4*/ ) // allow composite sides
2701     return false;
2702
2703   // algo: find corners of a structure and then analyze nb of faces and
2704   // length of structure sides
2705
2706   SMESHDS_Mesh* meshDS = faceSM->GetFather()->GetMeshDS();
2707   SMESH_MesherHelper faceAnalyser( *faceSM->GetFather() );
2708   faceAnalyser.SetSubShape( faceSM->GetSubShape() );
2709
2710   // rotate edges to get the first node being at corner
2711   // (in principle it's not necessary because so far none SALOME algo can make
2712   //  such a structured mesh that all corner nodes are not on VERTEXes)
2713   bool isCorner     = false;
2714   int nbRemainEdges = nbEdgesInWires.front();
2715   do {
2716     TopoDS_Vertex V = IthVertex( 0, edges.front() );
2717     isCorner = isCornerOfStructure( SMESH_Algo::VertexNode( V, meshDS ),
2718                                     fSM, faceAnalyser);
2719     if ( !isCorner ) {
2720       edges.splice( edges.end(), edges, edges.begin() );
2721       --nbRemainEdges;
2722     }
2723   }
2724   while ( !isCorner && nbRemainEdges > 0 );
2725
2726   if ( !isCorner )
2727     return false;
2728
2729   // get all nodes from EDGEs
2730   list< const SMDS_MeshNode* > nodes;
2731   list< TopoDS_Edge >::iterator edge = edges.begin();
2732   for ( ; edge != edges.end(); ++edge )
2733   {
2734     map< double, const SMDS_MeshNode* > u2Nodes;
2735     if ( !SMESH_Algo::GetSortedNodesOnEdge( meshDS, *edge,
2736                                             /*skipMedium=*/true, u2Nodes ))
2737       return false;
2738
2739     list< const SMDS_MeshNode* > edgeNodes;
2740     map< double, const SMDS_MeshNode* >::iterator u2n = u2Nodes.begin();
2741     for ( ; u2n != u2Nodes.end(); ++u2n )
2742       edgeNodes.push_back( u2n->second );
2743     if ( edge->Orientation() == TopAbs_REVERSED )
2744       edgeNodes.reverse();
2745
2746     if ( !nodes.empty() && nodes.back() == edgeNodes.front() )
2747       edgeNodes.pop_front();
2748     nodes.splice( nodes.end(), edgeNodes, edgeNodes.begin(), edgeNodes.end() );
2749   }
2750
2751   // get length of structured sides
2752   vector<int> nbEdgesInSide;
2753   int nbEdges = 0;
2754   list< const SMDS_MeshNode* >::iterator n = ++nodes.begin();
2755   for ( ; n != nodes.end(); ++n )
2756   {
2757     ++nbEdges;
2758     if ( isCornerOfStructure( *n, fSM, faceAnalyser )) {
2759       nbEdgesInSide.push_back( nbEdges );
2760       nbEdges = 0;
2761     }
2762   }
2763
2764   // checks
2765   if ( nbEdgesInSide.size() != 4 )
2766     return false;
2767   if ( nbEdgesInSide[0] != nbEdgesInSide[2] )
2768     return false;
2769   if ( nbEdgesInSide[1] != nbEdgesInSide[3] )
2770     return false;
2771   if ( nbEdgesInSide[0] * nbEdgesInSide[1] != fSM->NbElements() )
2772     return false;
2773
2774   return true;
2775 }
2776
2777 //=======================================================================
2778 //function : IsDistorted2D
2779 //purpose  : Return true if 2D mesh on FACE is ditorted
2780 //=======================================================================
2781
2782 bool SMESH_MesherHelper::IsDistorted2D( SMESH_subMesh* faceSM,
2783                                         bool           checkUV)
2784 {
2785   if ( !faceSM || faceSM->GetSubShape().ShapeType() != TopAbs_FACE )
2786     return false;
2787
2788   bool haveBadFaces = false;
2789
2790   SMESH_MesherHelper helper( *faceSM->GetFather() );
2791   helper.SetSubShape( faceSM->GetSubShape() );
2792
2793   const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
2794   SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( F );
2795   if ( !smDS || smDS->NbElements() == 0 ) return false;
2796
2797   SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2798   double prevArea = 0;
2799   vector< const SMDS_MeshNode* > nodes;
2800   vector< gp_XY >                uv;
2801   bool* toCheckUV = checkUV ? & checkUV : 0;
2802   while ( faceIt->more() && !haveBadFaces )
2803   {
2804     const SMDS_MeshElement* face = faceIt->next();
2805
2806     // get nodes
2807     nodes.resize( face->NbCornerNodes() );
2808     SMDS_MeshElement::iterator n = face->begin_nodes();
2809     for ( size_t i = 0; i < nodes.size(); ++n, ++i )
2810       nodes[ i ] = *n;
2811
2812     // avoid elems on degenarate shapes as UV on them can be wrong
2813     if ( helper.HasDegeneratedEdges() )
2814     {
2815       bool isOnDegen = false;
2816       for ( size_t i = 0; ( i < nodes.size() && !isOnDegen ); ++i )
2817         isOnDegen = helper.IsDegenShape( nodes[ i ]->getshapeId() );
2818       if ( isOnDegen )
2819         continue;
2820     }
2821     // prepare to getting UVs
2822     const SMDS_MeshNode* inFaceNode = 0;
2823     if ( helper.HasSeam() ) {
2824       for ( size_t i = 0; ( i < nodes.size() && !inFaceNode ); ++i )
2825         if ( !helper.IsSeamShape( nodes[ i ]->getshapeId() ))
2826           inFaceNode = nodes[ i ];
2827       if ( !inFaceNode )
2828         continue;
2829     }
2830     // get UVs
2831     uv.resize( nodes.size() );
2832     for ( size_t i = 0; i < nodes.size(); ++i )
2833       uv[ i ] = helper.GetNodeUV( F, nodes[ i ], inFaceNode, toCheckUV );
2834
2835     // compare orientation of triangles
2836     double faceArea = 0;
2837     for ( int iT = 0, nbT = nodes.size()-2; iT < nbT; ++iT )
2838     {
2839       gp_XY v1 = uv[ iT+1 ] - uv[ 0 ];
2840       gp_XY v2 = uv[ iT+2 ] - uv[ 0 ];
2841       faceArea += v2 ^ v1;
2842     }
2843     haveBadFaces = ( faceArea * prevArea < 0 );
2844     prevArea = faceArea;
2845   }
2846
2847   return haveBadFaces;
2848 }
2849
2850 //================================================================================
2851 /*!
2852  * \brief Find out elements orientation on a geometrical face
2853  * \param theFace - The face correctly oriented in the shape being meshed
2854  * \retval bool - true if the face normal and the normal of first element
2855  *                in the correspoding submesh point in different directions
2856  */
2857 //================================================================================
2858
2859 bool SMESH_MesherHelper::IsReversedSubMesh (const TopoDS_Face& theFace)
2860 {
2861   if ( theFace.IsNull() )
2862     return false;
2863
2864   // find out orientation of a meshed face
2865   int faceID = GetMeshDS()->ShapeToIndex( theFace );
2866   TopoDS_Shape aMeshedFace = GetMeshDS()->IndexToShape( faceID );
2867   bool isReversed = ( theFace.Orientation() != aMeshedFace.Orientation() );
2868
2869   const SMESHDS_SubMesh * aSubMeshDSFace = GetMeshDS()->MeshElements( faceID );
2870   if ( !aSubMeshDSFace )
2871     return isReversed;
2872
2873   // find an element on a bounday of theFace
2874   SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
2875   const SMDS_MeshNode* nn[2];
2876   while ( iteratorElem->more() ) // loop on elements on theFace
2877   {
2878     const SMDS_MeshElement* elem = iteratorElem->next();
2879     if ( ! elem ) continue;
2880
2881     // look for 2 nodes on EDGE
2882     int nbNodes = elem->NbCornerNodes();
2883     nn[0] = elem->GetNode( nbNodes-1 );
2884     for ( int iN = 0; iN < nbNodes; ++iN )
2885     {
2886       nn[1] = elem->GetNode( iN );
2887       if ( nn[0]->GetPosition()->GetDim() < 2 &&
2888            nn[1]->GetPosition()->GetDim() < 2 )
2889       {
2890         TopoDS_Shape s0 = GetSubShapeByNode( nn[0], GetMeshDS() );
2891         TopoDS_Shape s1 = GetSubShapeByNode( nn[1], GetMeshDS() );
2892         TopoDS_Shape  E = GetCommonAncestor( s0, s1, *myMesh, TopAbs_EDGE );
2893         if ( !E.IsNull() && !s0.IsSame( s1 ))
2894         {
2895           // is E seam edge?
2896           int nb = 0;
2897           for ( TopExp_Explorer exp( theFace, TopAbs_EDGE ); exp.More(); exp.Next() )
2898             if ( E.IsSame( exp.Current() )) {
2899               ++nb;
2900               E = exp.Current(); // to know orientation
2901             }
2902           if ( nb == 1 )
2903           {
2904             bool ok = true;
2905             double u0 = GetNodeU( TopoDS::Edge( E ), nn[0], nn[1], &ok );
2906             double u1 = GetNodeU( TopoDS::Edge( E ), nn[1], nn[0], &ok );
2907             // check that the 2 nodes are connected with a segment (IPAL53055)
2908             // if ( SMESHDS_SubMesh* sm = GetMeshDS()->MeshElements( E ))
2909             //   if ( sm->NbElements() > 0 && !GetMeshDS()->FindEdge( nn[0], nn[1] ))
2910             //     ok = false;
2911             if ( ok )
2912             {
2913               isReversed = ( u0 > u1 );
2914               if ( E.Orientation() == TopAbs_REVERSED )
2915                 isReversed = !isReversed;
2916               return isReversed;
2917             }
2918           }
2919         }
2920       }
2921       nn[0] = nn[1];
2922     }
2923   }
2924
2925   // find an element with a good normal
2926   gp_Vec Ne;
2927   bool normalOK = false;
2928   gp_XY uv;
2929   iteratorElem = aSubMeshDSFace->GetElements();
2930   while ( !normalOK && iteratorElem->more() ) // loop on elements on theFace
2931   {
2932     const SMDS_MeshElement* elem = iteratorElem->next();
2933     if ( ! SMESH_MeshAlgos::FaceNormal( elem, const_cast<gp_XYZ&>( Ne.XYZ() ), /*normalized=*/0 ))
2934       continue;
2935     normalOK = true;
2936
2937     // get UV of a node inside theFACE
2938     SMDS_ElemIteratorPtr nodesIt = elem->nodesIterator();
2939     const SMDS_MeshNode* nInFace = 0;
2940     int iPosDim = SMDS_TOP_VERTEX;
2941     while ( nodesIt->more() ) // loop on nodes
2942     {
2943       const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nodesIt->next() );
2944       if ( n->GetPosition()->GetTypeOfPosition() >= iPosDim )
2945       {
2946         nInFace = n;
2947         iPosDim = n->GetPosition()->GetTypeOfPosition();
2948       }
2949     }
2950     uv = GetNodeUV( theFace, nInFace, 0, &normalOK );
2951   }
2952   if ( !normalOK )
2953     return isReversed;
2954
2955   // face normal at node position
2956   TopLoc_Location loc;
2957   Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace, loc );
2958   // if ( surf.IsNull() || surf->Continuity() < GeomAbs_C1 )
2959   // some surfaces not detected as GeomAbs_C1 are nevertheless correct for meshing
2960   if ( surf.IsNull() || surf->Continuity() < GeomAbs_C0 )
2961     return isReversed;
2962
2963   gp_Vec d1u, d1v; gp_Pnt p;
2964   surf->D1( uv.X(), uv.Y(), p, d1u, d1v );
2965   gp_Vec Nf = (d1u ^ d1v).Transformed( loc );
2966
2967   if ( theFace.Orientation() == TopAbs_REVERSED )
2968     Nf.Reverse();
2969
2970   return Ne * Nf < 0.;
2971 }
2972
2973 //=======================================================================
2974 //function : Count
2975 //purpose  : Count nb of sub-shapes
2976 //=======================================================================
2977
2978 int SMESH_MesherHelper::Count(const TopoDS_Shape&    shape,
2979                               const TopAbs_ShapeEnum type,
2980                               const bool             ignoreSame)
2981 {
2982   if ( ignoreSame ) {
2983     TopTools_IndexedMapOfShape map;
2984     TopExp::MapShapes( shape, type, map );
2985     return map.Extent();
2986   }
2987   else {
2988     int nb = 0;
2989     for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
2990       ++nb;
2991     return nb;
2992   }
2993 }
2994
2995 //=======================================================================
2996 //function : NbAncestors
2997 //purpose  : Return number of unique ancestors of the shape
2998 //=======================================================================
2999
3000 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
3001                                     const SMESH_Mesh&   mesh,
3002                                     TopAbs_ShapeEnum    ancestorType/*=TopAbs_SHAPE*/)
3003 {
3004   TopTools_MapOfShape ancestors;
3005   TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
3006   for ( ; ansIt.More(); ansIt.Next() ) {
3007     if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
3008       ancestors.Add( ansIt.Value() );
3009   }
3010   return ancestors.Extent();
3011 }
3012
3013 //=======================================================================
3014 //function : GetSubShapeOri
3015 //purpose  : Return orientation of sub-shape in the main shape
3016 //=======================================================================
3017
3018 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
3019                                                       const TopoDS_Shape& subShape)
3020 {
3021   TopAbs_Orientation ori = TopAbs_Orientation(-1);
3022   if ( !shape.IsNull() && !subShape.IsNull() )
3023   {
3024     TopExp_Explorer e( shape, subShape.ShapeType() );
3025     if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
3026       e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
3027     for ( ; e.More(); e.Next())
3028       if ( subShape.IsSame( e.Current() ))
3029         break;
3030     if ( e.More() )
3031       ori = e.Current().Orientation();
3032   }
3033   return ori;
3034 }
3035
3036 //=======================================================================
3037 //function : IsSubShape
3038 //purpose  : 
3039 //=======================================================================
3040
3041 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
3042                                      const TopoDS_Shape& mainShape )
3043 {
3044   if ( !shape.IsNull() && !mainShape.IsNull() )
3045   {
3046     for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
3047           exp.More();
3048           exp.Next() )
3049       if ( shape.IsSame( exp.Current() ))
3050         return true;
3051   }
3052   SCRUTE((shape.IsNull()));
3053   SCRUTE((mainShape.IsNull()));
3054   return false;
3055 }
3056
3057 //=======================================================================
3058 //function : IsSubShape
3059 //purpose  : 
3060 //=======================================================================
3061
3062 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
3063 {
3064   if ( shape.IsNull() || !aMesh )
3065     return false;
3066   return
3067     aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
3068     // PAL16202
3069     (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
3070 }
3071
3072 //=======================================================================
3073 //function : IsBlock
3074 //purpose  : 
3075 //=======================================================================
3076
3077 bool SMESH_MesherHelper::IsBlock( const TopoDS_Shape& shape )
3078 {
3079   if ( shape.IsNull() )
3080     return false;
3081
3082   TopoDS_Shell shell;
3083   TopExp_Explorer exp( shape, TopAbs_SHELL );
3084   if ( !exp.More() ) return false;
3085   shell = TopoDS::Shell( exp.Current() );
3086   if ( exp.Next(), exp.More() ) return false;
3087
3088   TopoDS_Vertex v;
3089   TopTools_IndexedMapOfOrientedShape map;
3090   return SMESH_Block::FindBlockShapes( shell, v, v, map );
3091 }
3092
3093
3094 //================================================================================
3095 /*!
3096  * \brief Return maximal tolerance of shape
3097  */
3098 //================================================================================
3099
3100 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
3101 {
3102   double tol = Precision::Confusion();
3103   TopExp_Explorer exp;
3104   for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
3105     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
3106   for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3107     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
3108   for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
3109     tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
3110
3111   return tol;
3112 }
3113
3114 //================================================================================
3115 /*!
3116  * \brief Return MaxTolerance( face ), probably cached
3117  */
3118 //================================================================================
3119
3120 double SMESH_MesherHelper::getFaceMaxTol( const TopoDS_Shape& face ) const
3121 {
3122   int faceID = GetMeshDS()->ShapeToIndex( face );
3123
3124   SMESH_MesherHelper* me = const_cast< SMESH_MesherHelper* >( this );
3125   double & tol = me->myFaceMaxTol.insert( make_pair( faceID, -1. )).first->second;
3126   if ( tol < 0 )
3127     tol = MaxTolerance( face );
3128
3129   return tol;
3130 }
3131
3132 //================================================================================
3133 /*!
3134  * \brief Return an angle between two EDGEs sharing a common VERTEX with reference
3135  *        of the FACE normal
3136  *  \return double - the angle (between -Pi and Pi), negative if the angle is concave,
3137  *                   1e100 in case of failure
3138  *  \waring Care about order of the EDGEs and their orientation to be as they are
3139  *          within the FACE! Don't pass degenerated EDGEs neither!
3140  */
3141 //================================================================================
3142
3143 double SMESH_MesherHelper::GetAngle( const TopoDS_Edge &   theE1,
3144                                      const TopoDS_Edge &   theE2,
3145                                      const TopoDS_Face &   theFace,
3146                                      const TopoDS_Vertex & theCommonV,
3147                                      gp_Vec*               theFaceNormal)
3148 {
3149   double angle = 1e100;
3150   try
3151   {
3152     double f,l;
3153     Handle(Geom_Curve)     c1 = BRep_Tool::Curve( theE1, f,l );
3154     Handle(Geom_Curve)     c2 = BRep_Tool::Curve( theE2, f,l );
3155     Handle(Geom2d_Curve) c2d1 = BRep_Tool::CurveOnSurface( theE1, theFace, f,l );
3156     Handle(Geom_Surface) surf = BRep_Tool::Surface( theFace );
3157     double                 p1 = BRep_Tool::Parameter( theCommonV, theE1 );
3158     double                 p2 = BRep_Tool::Parameter( theCommonV, theE2 );
3159     if ( c1.IsNull() || c2.IsNull() )
3160       return angle;
3161     gp_XY uv = c2d1->Value( p1 ).XY();
3162     gp_Vec du, dv; gp_Pnt p;
3163     surf->D1( uv.X(), uv.Y(), p, du, dv );
3164     gp_Vec vec1, vec2, vecRef = du ^ dv;
3165     int  nbLoops = 0;
3166     double p1tmp = p1;
3167     while ( vecRef.SquareMagnitude() < 1e-25 )
3168     {
3169       double dp = ( l - f ) / 1000.;
3170       p1tmp += dp * (( Abs( p1 - f ) > Abs( p1 - l )) ? -1. : +1.);
3171       uv = c2d1->Value( p1tmp ).XY();
3172       surf->D1( uv.X(), uv.Y(), p, du, dv );
3173       vecRef = du ^ dv;
3174       if ( ++nbLoops > 10 )
3175       {
3176 #ifdef _DEBUG_
3177         cout << "SMESH_MesherHelper::GetAngle(): Captured in a sigularity" << endl;
3178 #endif
3179         return angle;
3180       }
3181     }
3182     if ( theFace.Orientation() == TopAbs_REVERSED )
3183       vecRef.Reverse();
3184     if ( theFaceNormal ) *theFaceNormal = vecRef;
3185
3186     c1->D1( p1, p, vec1 );
3187     c2->D1( p2, p, vec2 );
3188     // TopoDS_Face F = theFace;
3189     // if ( F.Orientation() == TopAbs_INTERNAL )
3190     //   F.Orientation( TopAbs_FORWARD );
3191     if ( theE1.Orientation() /*GetSubShapeOri( F, theE1 )*/ == TopAbs_REVERSED )
3192       vec1.Reverse();
3193     if ( theE2.Orientation() /*GetSubShapeOri( F, theE2 )*/ == TopAbs_REVERSED )
3194       vec2.Reverse();
3195     angle = vec1.AngleWithRef( vec2, vecRef );
3196
3197     if ( Abs ( angle ) >= 0.99 * M_PI )
3198     {
3199       BRep_Tool::Range( theE1, f, l );
3200       p1 += 1e-7 * ( p1-f < l-p1 ? +1. : -1. );
3201       c1->D1( p1, p, vec1 );
3202       if ( theE1.Orientation() == TopAbs_REVERSED )
3203         vec1.Reverse();
3204       BRep_Tool::Range( theE2, f, l );
3205       p2 += 1e-7 * ( p2-f < l-p2 ? +1. : -1. );
3206       c2->D1( p2, p, vec2 );
3207       if ( theE2.Orientation() == TopAbs_REVERSED )
3208         vec2.Reverse();
3209       angle = vec1.AngleWithRef( vec2, vecRef );
3210     }
3211   }
3212   catch (...)
3213   {
3214   }
3215   return angle;
3216 }
3217
3218 //================================================================================
3219 /*!
3220  * \brief Check if the first and last vertices of an edge are the same
3221  * \param anEdge - the edge to check
3222  * \retval bool - true if same
3223  */
3224 //================================================================================
3225
3226 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
3227 {
3228   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
3229     return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
3230   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
3231 }
3232
3233 //================================================================================
3234 /*!
3235  * \brief Wrapper over TopExp::FirstVertex() and TopExp::LastVertex() fixing them
3236  *  in the case of INTERNAL edge
3237  */
3238 //================================================================================
3239
3240 TopoDS_Vertex SMESH_MesherHelper::IthVertex( const bool  is2nd,
3241                                              TopoDS_Edge anEdge,
3242                                              const bool  CumOri )
3243 {
3244   if ( anEdge.Orientation() >= TopAbs_INTERNAL )
3245     anEdge.Orientation( TopAbs_FORWARD );
3246
3247   const TopAbs_Orientation tgtOri = is2nd ? TopAbs_REVERSED : TopAbs_FORWARD;
3248   TopoDS_Iterator vIt( anEdge, CumOri );
3249   while ( vIt.More() && vIt.Value().Orientation() != tgtOri )
3250     vIt.Next();
3251
3252   return ( vIt.More() ? TopoDS::Vertex(vIt.Value()) : TopoDS_Vertex() );
3253 }
3254
3255 //================================================================================
3256 /*!
3257  * \brief Return type of shape contained in a group 
3258  *  \param group - a shape of type TopAbs_COMPOUND
3259  *  \param avoidCompound - not to return TopAbs_COMPOUND
3260  */
3261 //================================================================================
3262
3263 TopAbs_ShapeEnum SMESH_MesherHelper::GetGroupType(const TopoDS_Shape& group,
3264                                                   const bool          avoidCompound)
3265 {
3266   if ( !group.IsNull() )
3267   {
3268     if ( group.ShapeType() != TopAbs_COMPOUND )
3269       return group.ShapeType();
3270
3271     // iterate on a compound
3272     TopoDS_Iterator it( group );
3273     if ( it.More() )
3274       return avoidCompound ? GetGroupType( it.Value() ) : it.Value().ShapeType();
3275   }
3276   return TopAbs_SHAPE;
3277 }
3278
3279 //================================================================================
3280 /*!
3281  * \brief Returns a shape, to which a hypothesis used to mesh a given shape is assigned
3282  *  \param [in] hyp - the hypothesis
3283  *  \param [in] shape - the shape, for meshing which the \a hyp is used
3284  *  \param [in] mesh - the mesh
3285  *  \return TopoDS_Shape - the shape the \a hyp is assigned to
3286  */
3287 //================================================================================
3288
3289 TopoDS_Shape SMESH_MesherHelper::GetShapeOfHypothesis( const SMESHDS_Hypothesis * hyp,
3290                                                        const TopoDS_Shape&        shape,
3291                                                        SMESH_Mesh*                mesh)
3292 {
3293   const SMESH_Hypothesis* h = static_cast<const SMESH_Hypothesis*>( hyp );
3294   SMESH_HypoFilter hypFilter( SMESH_HypoFilter::Is( h ));
3295
3296   TopoDS_Shape shapeOfHyp;
3297   mesh->GetHypothesis( shape, hypFilter, /*checkAncestors=*/true, &shapeOfHyp );
3298   return shapeOfHyp;
3299 }
3300
3301 //=======================================================================
3302 //function : IsQuadraticMesh
3303 //purpose  : Check mesh without geometry for: if all elements on this shape are quadratic,
3304 //           quadratic elements will be created.
3305 //           Used then generated 3D mesh without geometry.
3306 //=======================================================================
3307
3308 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
3309 {
3310   int NbAllEdgsAndFaces=0;
3311   int NbQuadFacesAndEdgs=0;
3312   int NbFacesAndEdges=0;
3313   //All faces and edges
3314   NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
3315   if ( NbAllEdgsAndFaces == 0 )
3316     return SMESH_MesherHelper::LINEAR;
3317   
3318   //Quadratic faces and edges
3319   NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
3320
3321   //Linear faces and edges
3322   NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
3323   
3324   if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
3325     //Quadratic mesh
3326     return SMESH_MesherHelper::QUADRATIC;
3327   }
3328   else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
3329     //Linear mesh
3330     return SMESH_MesherHelper::LINEAR;
3331   }
3332   else
3333     //Mesh with both type of elements
3334     return SMESH_MesherHelper::COMP;
3335 }
3336
3337 //=======================================================================
3338 //function : GetOtherParam
3339 //purpose  : Return an alternative parameter for a node on seam
3340 //=======================================================================
3341
3342 double SMESH_MesherHelper::GetOtherParam(const double param) const
3343 {
3344   int i = myParIndex & U_periodic ? 0 : 1;
3345   return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
3346 }
3347
3348 namespace {
3349
3350   //=======================================================================
3351   /*!
3352    * \brief Iterator on ancestors of the given type
3353    */
3354   //=======================================================================
3355
3356   struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
3357   {
3358     TopTools_ListIteratorOfListOfShape _ancIter;
3359     TopAbs_ShapeEnum                   _type;
3360     TopTools_MapOfShape                _encountered;
3361     TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
3362       : _ancIter( ancestors ), _type( type )
3363     {
3364       if ( _ancIter.More() ) {
3365         if ( _ancIter.Value().ShapeType() != _type ) next();
3366         else _encountered.Add( _ancIter.Value() );
3367       }
3368     }
3369     virtual bool more()
3370     {
3371       return _ancIter.More();
3372     }
3373     virtual const TopoDS_Shape* next()
3374     {
3375       const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
3376       if ( _ancIter.More() )
3377         for ( _ancIter.Next();  _ancIter.More(); _ancIter.Next())
3378           if ( _ancIter.Value().ShapeType() == _type && _encountered.Add( _ancIter.Value() ))
3379             break;
3380       return s;
3381     }
3382   };
3383
3384 } // namespace
3385
3386 //=======================================================================
3387 /*!
3388  * \brief Return iterator on ancestors of the given type
3389  */
3390 //=======================================================================
3391
3392 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
3393                                                    const SMESH_Mesh&   mesh,
3394                                                    TopAbs_ShapeEnum    ancestorType)
3395 {
3396   return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
3397 }
3398
3399 //=======================================================================
3400 //function : GetCommonAncestor
3401 //purpose  : Find a common ancestors of two shapes of the given type
3402 //=======================================================================
3403
3404 TopoDS_Shape SMESH_MesherHelper::GetCommonAncestor(const TopoDS_Shape& shape1,
3405                                                    const TopoDS_Shape& shape2,
3406                                                    const SMESH_Mesh&   mesh,
3407                                                    TopAbs_ShapeEnum    ancestorType)
3408 {
3409   TopoDS_Shape commonAnc;
3410   if ( !shape1.IsNull() && !shape2.IsNull() )
3411   {
3412     if ( shape1.ShapeType() == ancestorType && IsSubShape( shape2, shape1 ))
3413       return shape1;
3414     if ( shape2.ShapeType() == ancestorType && IsSubShape( shape1, shape2 ))
3415       return shape2;
3416
3417     PShapeIteratorPtr ancIt = GetAncestors( shape1, mesh, ancestorType );
3418     while ( const TopoDS_Shape* anc = ancIt->next() )
3419       if ( IsSubShape( shape2, *anc ))
3420       {
3421         commonAnc = *anc;
3422         break;
3423       }
3424   }
3425   return commonAnc;
3426 }
3427
3428 //#include <Perf_Meter.hxx>
3429
3430 //=======================================================================
3431 namespace { // Structures used by FixQuadraticElements()
3432 //=======================================================================
3433
3434 #define __DMP__(txt) \
3435   // cout << txt
3436 #define MSG(txt) __DMP__(txt<<endl)
3437 #define MSGBEG(txt) __DMP__(txt)
3438
3439   //const double straightTol2 = 1e-33; // to detect straing links
3440   bool isStraightLink(double linkLen2, double middleNodeMove2)
3441   {
3442     // straight if <node move> < 1/15 * <link length>
3443     return middleNodeMove2 < 1/15./15. * linkLen2;
3444   }
3445
3446   struct QFace;
3447   // ---------------------------------------
3448   /*!
3449    * \brief Quadratic link knowing its faces
3450    */
3451   struct QLink: public SMESH_TLink
3452   {
3453     const SMDS_MeshNode*          _mediumNode;
3454     mutable vector<const QFace* > _faces;
3455     mutable gp_Vec                _nodeMove;
3456     mutable int                   _nbMoves;
3457     mutable bool                  _is2dFixed; // is moved along surface or in 3D
3458
3459     QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
3460       SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
3461       _faces.reserve(4);
3462       _nodeMove = MediumPnt() - MiddlePnt();
3463       _is2dFixed = ( MediumPos() != SMDS_TOP_FACE );
3464     }
3465     void SetContinuesFaces() const;
3466     const QFace* GetContinuesFace( const QFace* face ) const;
3467     bool   OnBoundary() const;
3468     gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
3469     gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
3470
3471     SMDS_TypeOfPosition  MediumPos() const
3472     { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
3473     SMDS_TypeOfPosition  EndPos(bool isSecond) const
3474     { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
3475     const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
3476     { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
3477
3478     void Move(const gp_Vec& move, bool sum=false, bool is2dFixed=false) const
3479     { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; _is2dFixed |= is2dFixed; }
3480     gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
3481     bool IsMoved() const { return (_nbMoves > 0 /*&& !IsStraight()*/); }
3482     bool IsFixedOnSurface() const { return _is2dFixed; }
3483     bool IsStraight() const
3484     { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
3485                              _nodeMove.SquareMagnitude());
3486     }
3487     bool operator<(const QLink& other) const {
3488       return (node1()->GetID() == other.node1()->GetID() ?
3489               node2()->GetID() < other.node2()->GetID() :
3490               node1()->GetID() < other.node1()->GetID());
3491     }
3492 //     struct PtrComparator {
3493 //       bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
3494 //     };
3495   };
3496   // ---------------------------------------------------------
3497   /*!
3498    * \brief Link in the chain of links; it connects two faces
3499    */
3500   struct TChainLink
3501   {
3502     const QLink*         _qlink;
3503     mutable const QFace* _qfaces[2];
3504
3505     TChainLink(const QLink* qlink=0):_qlink(qlink) {
3506       _qfaces[0] = _qfaces[1] = 0;
3507     }
3508     void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
3509
3510     bool IsBoundary() const { return !_qfaces[1]; }
3511
3512     void RemoveFace( const QFace* face ) const
3513     { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
3514
3515     const QFace* NextFace( const QFace* f ) const
3516     { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
3517
3518     const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
3519     { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
3520
3521     bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
3522
3523     operator bool() const { return (_qlink); }
3524
3525     const QLink* operator->() const { return _qlink; }
3526
3527     gp_Vec Normal() const;
3528
3529     bool IsStraight() const;
3530   };
3531   // --------------------------------------------------------------------
3532   typedef list< TChainLink > TChain;
3533   typedef set < TChainLink > TLinkSet;
3534   typedef TLinkSet::const_iterator TLinkInSet;
3535
3536   const int theFirstStep = 5;
3537
3538   enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
3539   // --------------------------------------------------------------------
3540   /*!
3541    * \brief Quadratic face shared by two volumes and bound by QLinks
3542    */
3543   struct QFace: public TIDSortedNodeSet
3544   {
3545     mutable const SMDS_MeshElement* _volumes[2];
3546     mutable vector< const QLink* >  _sides;
3547     mutable bool                    _sideIsAdded[4]; // added in chain of links
3548     gp_Vec                          _normal;
3549 #ifdef _DEBUG_
3550     mutable const SMDS_MeshElement* _face;
3551 #endif
3552
3553     QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
3554
3555     void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
3556
3557     int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
3558
3559     void AddSelfToLinks() const {
3560       for ( size_t i = 0; i < _sides.size(); ++i )
3561         _sides[i]->_faces.push_back( this );
3562     }
3563     int LinkIndex( const QLink* side ) const {
3564       for (size_t i = 0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
3565       return -1;
3566     }
3567     bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
3568
3569     bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
3570     {
3571       int i = LinkIndex( link._qlink );
3572       if ( i < 0 ) return true;
3573       _sideIsAdded[i] = true;
3574       link.SetFace( this );
3575       // continue from opposite link
3576       return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
3577     }
3578     bool IsBoundary() const { return !_volumes[1]; }
3579
3580     bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
3581
3582     bool IsSpoiled(const QLink* bentLink ) const;
3583
3584     TLinkInSet GetBoundaryLink( const TLinkSet&      links,
3585                                 const TChainLink&    avoidLink,
3586                                 TLinkInSet *         notBoundaryLink = 0,
3587                                 const SMDS_MeshNode* nodeToContain = 0,
3588                                 bool *               isAdjacentUsed = 0,
3589                                 int                  nbRecursionsLeft = -1) const;
3590
3591     TLinkInSet GetLinkByNode( const TLinkSet&      links,
3592                               const TChainLink&    avoidLink,
3593                               const SMDS_MeshNode* nodeToContain) const;
3594
3595     const SMDS_MeshNode* GetNodeInFace() const {
3596       for ( size_t iL = 0; iL < _sides.size(); ++iL )
3597         if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
3598       return 0;
3599     }
3600
3601     gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
3602
3603     double MoveByBoundary( const TChainLink&   theLink,
3604                            const gp_Vec&       theRefVec,
3605                            const TLinkSet&     theLinks,
3606                            SMESH_MesherHelper* theFaceHelper=0,
3607                            const double        thePrevLen=0,
3608                            const int           theStep=theFirstStep,
3609                            gp_Vec*             theLinkNorm=0,
3610                            double              theSign=1.0) const;
3611   };
3612
3613   //================================================================================
3614   /*!
3615    * \brief Dump QLink and QFace
3616    */
3617   ostream& operator << (ostream& out, const QLink& l)
3618   {
3619     out <<"QLink nodes: "
3620         << l.node1()->GetID() << " - "
3621         << l._mediumNode->GetID() << " - "
3622         << l.node2()->GetID() << endl;
3623     return out;
3624   }
3625   ostream& operator << (ostream& out, const QFace& f)
3626   {
3627     out <<"QFace nodes: "/*<< &f << "  "*/;
3628     for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
3629       out << (*n)->GetID() << " ";
3630     out << " \tvolumes: "
3631         << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
3632         << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
3633     out << "  \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
3634     return out;
3635   }
3636
3637   //================================================================================
3638   /*!
3639    * \brief Construct QFace from QLinks 
3640    */
3641   //================================================================================
3642
3643   QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
3644   {
3645     _volumes[0] = _volumes[1] = 0;
3646     _sides = links;
3647     _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
3648     _normal.SetCoord(0,0,0);
3649     for ( size_t i = 1; i < _sides.size(); ++i ) {
3650       const QLink *l1 = _sides[i-1], *l2 = _sides[i];
3651       insert( l1->node1() ); insert( l1->node2() );
3652       // compute normal
3653       gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
3654       gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
3655       if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
3656         v1.Reverse(); 
3657       _normal += v1 ^ v2;
3658     }
3659     double normSqSize = _normal.SquareMagnitude();
3660     if ( normSqSize > numeric_limits<double>::min() )
3661       _normal /= sqrt( normSqSize );
3662     else
3663       _normal.SetCoord(1e-33,0,0);
3664
3665 #ifdef _DEBUG_
3666     _face = face;
3667 #endif
3668   }
3669   //================================================================================
3670   /*!
3671    * \brief Make up a chain of links
3672    *  \param iSide - link to add first
3673    *  \param chain - chain to fill in
3674    *  \param pos   - postion of medium nodes the links should have
3675    *  \param error - out, specifies what is wrong
3676    *  \retval bool - false if valid chain can't be built; "valid" means that links
3677    *                 of the chain belongs to rectangles bounding hexahedrons
3678    */
3679   //================================================================================
3680
3681   bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
3682   {
3683     if ( iSide >= (int)_sides.size() ) // wrong argument iSide
3684       return false;
3685     if ( _sideIsAdded[ iSide ]) // already in chain
3686       return true;
3687
3688     if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
3689       MSGBEG( *this );
3690       TLinkSet links;
3691       list< const QFace* > faces( 1, this );
3692       while ( !faces.empty() ) {
3693         const QFace* face = faces.front();
3694         for ( size_t i = 0; i < face->_sides.size(); ++i ) {
3695           if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
3696             face->_sideIsAdded[i] = true;
3697             // find a face side in the chain
3698             TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
3699 //             TChain::iterator chLink = chain.begin();
3700 //             for ( ; chLink != chain.end(); ++chLink )
3701 //               if ( chLink->_qlink == face->_sides[i] )
3702 //                 break;
3703 //             if ( chLink == chain.end() )
3704 //               chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
3705             // add a face to a chained link and put a continues face in the queue
3706             chLink->SetFace( face );
3707             if ( face->_sides[i]->MediumPos() == pos )
3708               if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
3709                 if ( contFace->_sides.size() == 3 )
3710                   faces.push_back( contFace );
3711           }
3712         }
3713         faces.pop_front();
3714       }
3715       if ( error < ERR_TRI )
3716         error = ERR_TRI;
3717       chain.insert( chain.end(), links.begin(),links.end() );
3718       return false;
3719     }
3720     _sideIsAdded[iSide] = true; // not to add this link to chain again
3721     const QLink* link = _sides[iSide];
3722     if ( !link)
3723       return true;
3724
3725     // add link into chain
3726     TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
3727     chLink->SetFace( this );
3728     MSGBEG( *this );
3729
3730     // propagate from a quadrangle to neighbour faces
3731     if ( link->MediumPos() >= pos ) {
3732       int nbLinkFaces = link->_faces.size();
3733       if ( nbLinkFaces == 4 || (/*nbLinkFaces < 4 && */link->OnBoundary())) {
3734         // hexahedral mesh or boundary quadrangles - goto a continous face
3735         if ( const QFace* f = link->GetContinuesFace( this ))
3736           if ( f->_sides.size() == 4 )
3737             return f->GetLinkChain( *chLink, chain, pos, error );
3738       }
3739       else {
3740         TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
3741         for ( int i = 0; i < nbLinkFaces; ++i )
3742           if ( link->_faces[i] )
3743             link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
3744         if ( error < ERR_PRISM )
3745           error = ERR_PRISM;
3746         return false;
3747       }
3748     }
3749     return true;
3750   }
3751
3752   //================================================================================
3753   /*!
3754    * \brief Return a boundary link of the triangle face
3755    *  \param links - set of all links
3756    *  \param avoidLink - link not to return
3757    *  \param notBoundaryLink - out, neither the returned link nor avoidLink
3758    *  \param nodeToContain - node the returned link must contain; if provided, search
3759    *                         also performed on adjacent faces
3760    *  \param isAdjacentUsed - returns true if link is found in adjacent faces
3761    *  \param nbRecursionsLeft - to limit recursion
3762    */
3763   //================================================================================
3764
3765   TLinkInSet QFace::GetBoundaryLink( const TLinkSet&      links,
3766                                      const TChainLink&    avoidLink,
3767                                      TLinkInSet *         notBoundaryLink,
3768                                      const SMDS_MeshNode* nodeToContain,
3769                                      bool *               isAdjacentUsed,
3770                                      int                  nbRecursionsLeft) const
3771   {
3772     TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
3773
3774     typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
3775     TFaceLinkList adjacentFaces;
3776
3777     for ( size_t iL = 0; iL < _sides.size(); ++iL )
3778     {
3779       if ( avoidLink._qlink == _sides[iL] )
3780         continue;
3781       TLinkInSet link = links.find( _sides[iL] );
3782       if ( link == linksEnd ) continue;
3783       if ( (*link)->MediumPos() > SMDS_TOP_FACE )
3784         continue; // We work on faces here, don't go inside a solid
3785
3786       // check link
3787       if ( link->IsBoundary() ) {
3788         if ( !nodeToContain ||
3789              (*link)->node1() == nodeToContain ||
3790              (*link)->node2() == nodeToContain )
3791         {
3792           boundaryLink = link;
3793           if ( !notBoundaryLink ) break;
3794         }
3795       }
3796       else if ( notBoundaryLink ) {
3797         *notBoundaryLink = link;
3798         if ( boundaryLink != linksEnd ) break;
3799       }
3800
3801       if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
3802         if ( const QFace* adj = link->NextFace( this ))
3803           if ( adj->Contains( nodeToContain ))
3804             adjacentFaces.push_back( make_pair( adj, link ));
3805     }
3806
3807     if ( isAdjacentUsed ) *isAdjacentUsed = false;
3808     if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
3809     {
3810       if ( nbRecursionsLeft < 0 )
3811         nbRecursionsLeft = nodeToContain->NbInverseElements();
3812       TFaceLinkList::iterator adj = adjacentFaces.begin();
3813       for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
3814         boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
3815                                                     isAdjacentUsed, nbRecursionsLeft-1);
3816       if ( isAdjacentUsed ) *isAdjacentUsed = true;
3817     }
3818     return boundaryLink;
3819   }
3820   //================================================================================
3821   /*!
3822    * \brief Return a link ending at the given node but not avoidLink
3823    */
3824   //================================================================================
3825
3826   TLinkInSet QFace::GetLinkByNode( const TLinkSet&      links,
3827                                    const TChainLink&    avoidLink,
3828                                    const SMDS_MeshNode* nodeToContain) const
3829   {
3830     for ( size_t i = 0; i < _sides.size(); ++i )
3831       if ( avoidLink._qlink != _sides[i] &&
3832            (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
3833         return links.find( _sides[i] );
3834     return links.end();
3835   }
3836
3837   //================================================================================
3838   /*!
3839    * \brief Return normal to the i-th side pointing outside the face
3840    */
3841   //================================================================================
3842
3843   gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
3844   {
3845     gp_Vec   norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
3846     gp_XYZ    pIn = ( _sides[ (i+1)%3 ]->MiddlePnt() +
3847                       _sides[ (i+2)%3 ]->MiddlePnt() ) / 2.;
3848     gp_Vec vecOut = ( _sides[i]->MiddlePnt() - pIn );
3849
3850     if ( norm * vecOut < 0 )
3851       norm.Reverse();
3852     double mag2 = norm.SquareMagnitude();
3853     if ( mag2 > numeric_limits<double>::min() )
3854       norm /= sqrt( mag2 );
3855     return norm;
3856   }
3857   //================================================================================
3858   /*!
3859    * \brief Move medium node of theLink according to its distance from boundary
3860    *  \param theLink - link to fix
3861    *  \param theRefVec - movement of boundary
3862    *  \param theLinks - all adjacent links of continous triangles
3863    *  \param theFaceHelper - helper is not used so far
3864    *  \param thePrevLen - distance from the boundary
3865    *  \param theStep - number of steps till movement propagation limit
3866    *  \param theLinkNorm - out normal to theLink
3867    *  \param theSign - 1 or -1 depending on movement of boundary
3868    *  \retval double - distance from boundary to propagation limit or other boundary
3869    */
3870   //================================================================================
3871
3872   double QFace::MoveByBoundary( const TChainLink&   theLink,
3873                                 const gp_Vec&       theRefVec,
3874                                 const TLinkSet&     theLinks,
3875                                 SMESH_MesherHelper* theFaceHelper,
3876                                 const double        thePrevLen,
3877                                 const int           theStep,
3878                                 gp_Vec*             theLinkNorm,
3879                                 double              theSign) const
3880   {
3881     if ( !theStep )
3882       return thePrevLen; // propagation limit reached
3883
3884     size_t iL; // index of theLink
3885     for ( iL = 0; iL < _sides.size(); ++iL )
3886       if ( theLink._qlink == _sides[ iL ])
3887         break;
3888
3889     MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
3890         <<" thePrevLen " << thePrevLen);
3891     MSG(string(theStep,'.')<<" "<<*theLink._qlink);
3892
3893     gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
3894     double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
3895     if ( theStep == theFirstStep )
3896       theSign = refProj < 0. ? -1. : 1.;
3897     else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
3898       return thePrevLen; // to propagate movement forward only, not in side dir or backward
3899
3900     int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
3901     TLinkInSet link1 = theLinks.find( _sides[iL1] );
3902     TLinkInSet link2 = theLinks.find( _sides[iL2] );
3903
3904     const QFace *f1 = 0, *f2 = 0;  // adjacent faces
3905     bool isBndLink1 = true, isBndLink2 = true;
3906     if ( link1 != theLinks.end() && link2 != theLinks.end() )
3907     {
3908       f1 = link1->NextFace( this );
3909       f2 = link2->NextFace( this );
3910
3911       isBndLink1 = ( theLink->MediumPos() > (*link1)->MediumPos() );
3912       isBndLink2 = ( theLink->MediumPos() > (*link2)->MediumPos() );
3913       if ( theStep == theFirstStep ) // (issue 22541) quad-dominant mesh
3914       {
3915         if ( !isBndLink1 && !f1 )
3916           f1 = (*link1)->GetContinuesFace( this ); // get a quadrangle face
3917         if ( !isBndLink2 && !f2 )
3918           f2 = (*link2)->GetContinuesFace( this );
3919       }
3920     }
3921     else if ( _sides.size() < 4 )
3922       return thePrevLen;      
3923
3924     // propagate to adjacent faces till limit step or boundary
3925     double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
3926     double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
3927     gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
3928     gp_Vec linkDir2(0,0,0);
3929     try {
3930       OCC_CATCH_SIGNALS;
3931       if ( f1 && !isBndLink1 )
3932         len1 = f1->MoveByBoundary
3933           ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
3934       else
3935         linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
3936     } catch (...) {
3937       MSG( " --------------- EXCEPTION");
3938       return thePrevLen;
3939     }
3940     try {
3941       OCC_CATCH_SIGNALS;
3942       if ( f2 && !isBndLink2 )
3943         len2 = f2->MoveByBoundary
3944           ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
3945       else
3946         linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
3947     } catch (...) {
3948       MSG( " --------------- EXCEPTION");
3949       return thePrevLen;
3950     }
3951
3952     double fullLen = 0;
3953     if ( theStep != theFirstStep )
3954     {
3955       // choose chain length by direction of propagation most codirected with theRefVec
3956       bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
3957       fullLen = choose1 ? len1 : len2;
3958       double r = thePrevLen / fullLen;
3959
3960       gp_Vec move = linkNorm * refProj * ( 1 - r );
3961       theLink->Move( move, /*sum=*/true );
3962
3963       MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
3964           " by " << refProj * ( 1 - r ) << " following " <<
3965           (choose1 ? *link1->_qlink : *link2->_qlink)); // warning: link1 can be invalid
3966
3967       if ( theLinkNorm ) *theLinkNorm = linkNorm;
3968     }
3969     return fullLen;
3970   }
3971
3972   //================================================================================
3973   /*!
3974    * \brief Checks if the face is distorted due to bentLink
3975    */
3976   //================================================================================
3977
3978   bool QFace::IsSpoiled(const QLink* bentLink ) const
3979   {
3980     // code is valid for convex faces only
3981     gp_XYZ gc(0,0,0);
3982     for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
3983       gc += XYZ( *n ) / size();
3984     for (unsigned i = 0; i < _sides.size(); ++i )
3985     {
3986       if ( _sides[i] == bentLink ) continue;
3987       gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
3988       gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
3989       if ( linkNorm * vecOut < 0 )
3990         linkNorm.Reverse();
3991       double mag2 = linkNorm.SquareMagnitude();
3992       if ( mag2 > numeric_limits<double>::min() )
3993         linkNorm /= sqrt( mag2 );
3994       gp_Vec vecBent    ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
3995       gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
3996       if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
3997         return true;
3998     }
3999     return false;
4000     
4001   }
4002
4003   //================================================================================
4004   /*!
4005    * \brief Find pairs of continues faces 
4006    */
4007   //================================================================================
4008
4009   void QLink::SetContinuesFaces() const
4010   {
4011     //       x0         x - QLink, [-|] - QFace, v - volume
4012     //   v0  |   v1   
4013     //       |          Between _faces of link x2 two vertical faces are continues
4014     // x1----x2-----x3  and two horizontal faces are continues. We set vertical faces
4015     //       |          to _faces[0] and _faces[1] and horizontal faces to
4016     //   v2  |   v3     _faces[2] and _faces[3] (or vise versa).
4017     //       x4
4018
4019     if ( _faces.empty() )
4020       return;
4021     int iFaceCont = -1, nbBoundary = 0, iBoundary[2]={-1,-1};
4022     if ( _faces[0]->IsBoundary() )
4023       iBoundary[ nbBoundary++ ] = 0;
4024     for ( size_t iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
4025     {
4026       // look for a face bounding none of volumes bound by _faces[0]
4027       bool sameVol = false;
4028       int nbVol = _faces[iF]->NbVolumes();
4029       for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
4030         sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
4031                     _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
4032       if ( !sameVol )
4033         iFaceCont = iF;
4034       if ( _faces[iF]->IsBoundary() )
4035         iBoundary[ nbBoundary++ ] = iF;
4036     }
4037     // Set continues faces: arrange _faces to have
4038     // _faces[0] continues to _faces[1]
4039     // _faces[2] continues to _faces[3]
4040     if ( nbBoundary == 2 ) // bnd faces are continues
4041     {
4042       if (( iBoundary[0] < 2 ) != ( iBoundary[1] < 2 ))
4043       {
4044         int iNear0 = iBoundary[0] < 2 ? 1-iBoundary[0] : 5-iBoundary[0];
4045         std::swap( _faces[ iBoundary[1] ], _faces[iNear0] );
4046       }
4047     }
4048     else if ( iFaceCont > 0 ) // continues faces found
4049     {
4050       if ( iFaceCont != 1 )
4051         std::swap( _faces[1], _faces[iFaceCont] );
4052     }
4053     else if ( _faces.size() > 1 ) // not found, set NULL by the first face
4054     {
4055       _faces.insert( ++_faces.begin(), (QFace*) 0 );
4056     }
4057   }
4058   //================================================================================
4059   /*!
4060    * \brief Return a face continues to the given one
4061    */
4062   //================================================================================
4063
4064   const QFace* QLink::GetContinuesFace( const QFace* face ) const
4065   {
4066     if ( _faces.size() <= 4 )
4067       for ( size_t i = 0; i < _faces.size(); ++i ) {
4068         if ( _faces[i] == face ) {
4069           int iF = i < 2 ? 1-i : 5-i;
4070           return iF < (int)_faces.size() ? _faces[iF] : 0;
4071         }
4072       }
4073     return 0;
4074   }
4075   //================================================================================
4076   /*!
4077    * \brief True if link is on mesh boundary
4078    */
4079   //================================================================================
4080
4081   bool QLink::OnBoundary() const
4082   {
4083     for ( size_t i = 0; i < _faces.size(); ++i )
4084       if (_faces[i] && _faces[i]->IsBoundary()) return true;
4085     return false;
4086   }
4087   //================================================================================
4088   /*!
4089    * \brief Return normal of link of the chain
4090    */
4091   //================================================================================
4092
4093   gp_Vec TChainLink::Normal() const {
4094     gp_Vec norm;
4095     if (_qfaces[0]) norm  = _qfaces[0]->_normal;
4096     if (_qfaces[1]) norm += _qfaces[1]->_normal;
4097     return norm;
4098   }
4099   //================================================================================
4100   /*!
4101    * \brief Test link curvature taking into account size of faces
4102    */
4103   //================================================================================
4104
4105   bool TChainLink::IsStraight() const
4106   {
4107     bool isStraight = _qlink->IsStraight();
4108     if ( isStraight && _qfaces[0] && !_qfaces[1] )
4109     {
4110       int i = _qfaces[0]->LinkIndex( _qlink );
4111       int iOpp = ( i + 2 ) % _qfaces[0]->_sides.size();
4112       gp_XYZ mid1 = _qlink->MiddlePnt();
4113       gp_XYZ mid2 = _qfaces[0]->_sides[ iOpp ]->MiddlePnt();
4114       double faceSize2 = (mid1-mid2).SquareModulus();
4115       isStraight = _qlink->_nodeMove.SquareMagnitude() < 1/10./10. * faceSize2;
4116     }
4117     return isStraight;
4118   }
4119   
4120   //================================================================================
4121   /*!
4122    * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
4123    */
4124   //================================================================================
4125
4126   void fixPrism( TChain& allLinks )
4127   {
4128     // separate boundary links from internal ones
4129     typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
4130     QLinkSet interLinks, bndLinks1, bndLink2;
4131
4132     bool isCurved = false;
4133     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
4134       if ( (*lnk)->OnBoundary() )
4135         bndLinks1.insert( lnk->_qlink );
4136       else
4137         interLinks.insert( lnk->_qlink );
4138       isCurved = isCurved || !lnk->IsStraight();
4139     }
4140     if ( !isCurved )
4141       return; // no need to move
4142
4143     QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
4144
4145     while ( !interLinks.empty() && !curBndLinks->empty() )
4146     {
4147       // propagate movement from boundary links to connected internal links
4148       QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
4149       for ( ; bnd != bndEnd; ++bnd )
4150       {
4151         const QLink* bndLink = *bnd;
4152         for ( size_t i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
4153         {
4154           const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
4155           if ( !face ) continue;
4156           // find and move internal link opposite to bndLink within the face
4157           int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
4158           const QLink* interLink = face->_sides[ interInd ];
4159           QLinkSet::iterator pInterLink = interLinks.find( interLink );
4160           if ( pInterLink == interLinks.end() ) continue; // not internal link
4161           interLink->Move( bndLink->_nodeMove );
4162           // treated internal links become new boundary ones
4163           interLinks.erase( pInterLink );
4164           newBndLinks->insert( interLink );
4165         }
4166       }
4167       curBndLinks->clear();
4168       std::swap( curBndLinks, newBndLinks );
4169     }
4170   }
4171
4172   //================================================================================
4173   /*!
4174    * \brief Fix links of continues triangles near curved boundary
4175    */
4176   //================================================================================
4177
4178   void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
4179   {
4180     if ( allLinks.empty() ) return;
4181
4182     TLinkSet linkSet( allLinks.begin(), allLinks.end());
4183     TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
4184
4185     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
4186     {
4187       if ( linkIt->IsBoundary() && !linkIt->IsStraight() && linkIt->_qfaces[0])
4188       {
4189         // move iff a boundary link is bent towards inside of a face (issue 0021084)
4190         const QFace* face = linkIt->_qfaces[0];
4191         gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
4192                        face->_sides[1]->MiddlePnt() +
4193                        face->_sides[2]->MiddlePnt() ) / 3.;
4194         gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
4195         bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
4196         //if ( face->IsSpoiled( linkIt->_qlink ))
4197         if ( linkBentInside )
4198           face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
4199       }
4200     }
4201   }
4202
4203   //================================================================================
4204   /*!
4205    * \brief Detect rectangular structure of links and build chains from them
4206    */
4207   //================================================================================
4208
4209   enum TSplitTriaResult {
4210     _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
4211     _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
4212
4213   TSplitTriaResult splitTrianglesIntoChains( TChain &            allLinks,
4214                                              vector< TChain> &   resultChains,
4215                                              SMDS_TypeOfPosition pos )
4216   {
4217     // put links in the set and evalute number of result chains by number of boundary links
4218     TLinkSet linkSet;
4219     size_t nbBndLinks = 0;
4220     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
4221       linkSet.insert( *lnk );
4222       nbBndLinks += lnk->IsBoundary();
4223     }
4224     resultChains.clear();
4225     resultChains.reserve( nbBndLinks / 2 );
4226
4227     TLinkInSet linkIt, linksEnd = linkSet.end();
4228
4229     // find a boundary link with corner node; corner node has position pos-2
4230     // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
4231     // links in volume
4232     SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
4233     const SMDS_MeshNode* corner = 0;
4234     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
4235       if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
4236         break;
4237     if ( !corner)
4238       return _NO_CORNERS;
4239
4240     TLinkInSet           startLink = linkIt;
4241     const SMDS_MeshNode* startCorner = corner;
4242     vector< TChain* >    rowChains;
4243     int iCol = 0;
4244
4245     while ( startLink != linksEnd) // loop on columns
4246     {
4247       // We suppose we have a rectangular structure like shown here. We have found a
4248       //               corner of the rectangle (startCorner) and a boundary link sharing  
4249       //    |/  |/  |  the startCorner (startLink). We are going to loop on rows of the   
4250       //  --o---o---o  structure making several chains at once. One chain (columnChain)   
4251       //    |\  |  /|  starts at startLink and continues upward (we look at the structure 
4252       //  \ | \ | / |  from such point that startLink is on the bottom of the structure). 
4253       //   \|  \|/  |  While going upward we also fill horizontal chains (rowChains) we   
4254       //  --o---o---o  encounter.                                                         
4255       //   /|\  |\  |
4256       //  / | \ | \ |  startCorner
4257       //    |  \|  \|,'
4258       //  --o---o---o
4259       //          `.startLink
4260
4261       if ( resultChains.size() == nbBndLinks / 2 )
4262         return _NOT_RECT;
4263       resultChains.push_back( TChain() );
4264       TChain& columnChain = resultChains.back();
4265
4266       TLinkInSet botLink = startLink; // current horizontal link to go up from
4267       corner = startCorner; // current corner the botLink ends at
4268       size_t iRow = 0;
4269       while ( botLink != linksEnd ) // loop on rows
4270       {
4271         // add botLink to the columnChain
4272         columnChain.push_back( *botLink );
4273
4274         const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
4275         if ( !botTria )
4276         { // the column ends
4277           if ( botLink == startLink )
4278             return _TWISTED_CHAIN; // issue 0020951
4279           linkSet.erase( botLink );
4280           if ( iRow != rowChains.size() )
4281             return _FEW_ROWS; // different nb of rows in columns
4282           break;
4283         }
4284         // find the link dividing the quadrangle (midQuadLink) and vertical boundary
4285         // link ending at <corner> (sideLink); there are two cases:
4286         // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
4287         //   since midQuadLink is not at boundary while sideLink is.
4288         // 2) midQuadLink ends at <corner>
4289         bool isCase2;
4290         TLinkInSet midQuadLink = linksEnd;
4291         TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
4292                                                         corner, &isCase2 );
4293         if ( isCase2 ) { // find midQuadLink among links of botTria
4294           midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
4295           if ( midQuadLink->IsBoundary() )
4296             return _BAD_MIDQUAD;
4297         }
4298         if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
4299           return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
4300
4301         // fill chains
4302         columnChain.push_back( *midQuadLink );
4303         if ( iRow >= rowChains.size() ) {
4304           if ( iCol > 0 )
4305             return _MANY_ROWS; // different nb of rows in columns
4306           if ( resultChains.size() == nbBndLinks / 2 )
4307             return _NOT_RECT;
4308           resultChains.push_back( TChain() );
4309           rowChains.push_back( & resultChains.back() );
4310         }
4311         rowChains[iRow]->push_back( *sideLink );
4312         rowChains[iRow]->push_back( *midQuadLink );
4313
4314         const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
4315         if ( !upTria)
4316           return _NO_UPTRIA;
4317         if ( iRow == 0 ) {
4318           // prepare startCorner and startLink for the next column
4319           startCorner = startLink->NextNode( startCorner );
4320           if (isCase2)
4321             startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
4322           else
4323             startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
4324           // check if no more columns remains
4325           if ( startLink != linksEnd ) {
4326             const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
4327             if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
4328               startLink = linksEnd; // startLink bounds upTria or botTria
4329             else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
4330               return _BAD_START;
4331           }
4332         }
4333         // find bottom link and corner for the next row
4334         corner = sideLink->NextNode( corner );
4335         // next bottom link ends at the new corner
4336         linkSet.erase( botLink );
4337         botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
4338         if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
4339           return _NO_BOTLINK;
4340         if ( midQuadLink == startLink || sideLink == startLink )
4341           return _TWISTED_CHAIN; // issue 0020951
4342         linkSet.erase( midQuadLink );
4343         linkSet.erase( sideLink );
4344
4345         // make faces neighboring the found ones be boundary
4346         if ( startLink != linksEnd ) {
4347           const QFace* tria = isCase2 ? botTria : upTria;
4348           for ( int iL = 0; iL < 3; ++iL ) {
4349             linkIt = linkSet.find( tria->_sides[iL] );
4350             if ( linkIt != linksEnd )
4351               linkIt->RemoveFace( tria );
4352           }
4353         }
4354         if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
4355           botLink->RemoveFace( upTria ); // make next botTria first in vector
4356
4357         iRow++;
4358       } // loop on rows
4359
4360       iCol++;
4361     }
4362     // In the linkSet, there must remain the last links of rowChains; add them
4363     if ( linkSet.size() != rowChains.size() )
4364       return _BAD_SET_SIZE;
4365     for ( size_t iRow = 0; iRow < rowChains.size(); ++iRow ) {
4366       // find the link (startLink) ending at startCorner
4367       corner = 0;
4368       for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
4369         if ( (*startLink)->node1() == startCorner ) {
4370           corner = (*startLink)->node2(); break;
4371         }
4372         else if ( (*startLink)->node2() == startCorner) {
4373           corner = (*startLink)->node1(); break;
4374         }
4375       }
4376       if ( startLink == linksEnd )
4377         return _BAD_CORNER;
4378       rowChains[ iRow ]->push_back( *startLink );
4379       linkSet.erase( startLink );
4380       startCorner = corner;
4381     }
4382
4383     return _OK;
4384   }
4385
4386   //================================================================================
4387   /*!
4388    * \brief Place medium nodes at the link middle for elements whose corner nodes
4389    *        are out of geometrical boundary to prevent distorting elements.
4390    *        Issue 0020982, note 0013990
4391    */
4392   //================================================================================
4393
4394   void force3DOutOfBoundary( SMESH_MesherHelper&    theHelper,
4395                              SMESH_ComputeErrorPtr& theError)
4396   {
4397     SMESHDS_Mesh* meshDS = theHelper.GetMeshDS();
4398     TopoDS_Shape  shape = theHelper.GetSubShape().Oriented( TopAbs_FORWARD );
4399     if ( shape.IsNull() ) return;
4400
4401     if ( !theError ) theError = SMESH_ComputeError::New();
4402
4403     gp_XYZ faceNorm;
4404
4405     if ( shape.ShapeType() == TopAbs_FACE ) // 2D
4406     {
4407       if ( theHelper.GetMesh()->NbTriangles( ORDER_QUADRATIC ) < 1 ) return;
4408
4409       SMESHDS_SubMesh* faceSM = meshDS->MeshElements( shape );
4410       if ( !faceSM ) return;
4411
4412       const TopoDS_Face&      face = TopoDS::Face( shape );
4413       Handle(Geom_Surface) surface = BRep_Tool::Surface( face );
4414
4415       TopExp_Explorer edgeIt( face, TopAbs_EDGE );
4416       for ( ; edgeIt.More(); edgeIt.Next() ) // loop on EDGEs of a FACE
4417       {
4418         // check if the EDGE needs checking
4419         const TopoDS_Edge& edge = TopoDS::Edge( edgeIt.Current() );
4420         if ( SMESH_Algo::isDegenerated( edge ) )
4421           continue;
4422         if ( theHelper.IsRealSeam( edge ) &&
4423              edge.Orientation() == TopAbs_REVERSED )
4424           continue;
4425
4426         SMESHDS_SubMesh* edgeSM = meshDS->MeshElements( edge );
4427         if ( !edgeSM ) continue;
4428
4429         double f,l;
4430         Handle(Geom2d_Curve) pcurve  = BRep_Tool::CurveOnSurface( edge, face, f, l );
4431         BRepAdaptor_Curve    curve3D( edge );
4432         switch ( curve3D.GetType() ) {
4433         case GeomAbs_Line: continue;
4434         case GeomAbs_Circle:
4435         case GeomAbs_Ellipse:
4436         case GeomAbs_Hyperbola:
4437         case GeomAbs_Parabola:
4438           try
4439           {
4440             gp_Vec D1, D2, Du1, Dv1; gp_Pnt p;
4441             curve3D.D2( 0.5 * ( f + l ), p, D1, D2 );
4442             gp_Pnt2d uv = pcurve->Value( 0.5 * ( f + l ) );
4443             surface->D1( uv.X(), uv.Y(), p, Du1, Dv1 );
4444             gp_Vec fNorm = Du1 ^ Dv1;
4445             if ( fNorm.IsParallel( D2, M_PI * 25./180. ))
4446               continue; // face is normal to the curve3D
4447
4448             gp_Vec curvNorm = fNorm ^ D1;
4449             if ( edge.Orientation() == TopAbs_REVERSED ) curvNorm.Reverse();
4450             if ( curvNorm * D2 > 0 )
4451               continue; // convex edge
4452           }
4453           catch ( Standard_Failure )
4454           {
4455             continue;
4456           }
4457         default:;
4458         }
4459         // get nodes shared by faces that may be distorted
4460         SMDS_NodeIteratorPtr nodeIt;
4461         if ( edgeSM->NbNodes() > 0 ) {
4462           nodeIt = edgeSM->GetNodes();
4463         }
4464         else {
4465           SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( theHelper.IthVertex( 0, edge ));
4466           if ( !vertexSM )
4467             vertexSM = meshDS->MeshElements( theHelper.IthVertex( 1, edge ));
4468           if ( !vertexSM ) continue;
4469           nodeIt = vertexSM->GetNodes();
4470         }
4471
4472         // find suspicious faces
4473         TIDSortedElemSet checkedFaces;
4474         vector< const SMDS_MeshNode* > nOnEdge( 2 );
4475         const SMDS_MeshNode*           nOnFace;
4476         while ( nodeIt->more() )
4477         {
4478           const SMDS_MeshNode* n      = nodeIt->next();
4479           SMDS_ElemIteratorPtr faceIt = n->GetInverseElementIterator( SMDSAbs_Face );
4480           while ( faceIt->more() )
4481           {
4482             const SMDS_MeshElement* f = faceIt->next();
4483             if ( !faceSM->Contains( f ) ||
4484                  f->NbNodes() < 6       || // check quadratic triangles only
4485                  !checkedFaces.insert( f ).second )
4486               continue;
4487
4488             // get nodes on EDGE and on FACE of a suspicious face
4489             nOnEdge.clear(); nOnFace = 0;
4490             SMDS_MeshElement::iterator triNode = f->begin_nodes();
4491             for ( int nbN = 0; nbN < 3; ++triNode, ++nbN )
4492             {
4493               n = *triNode;
4494               if ( n->GetPosition()->GetDim() == 2 )
4495                 nOnFace = n;
4496               else
4497                 nOnEdge.push_back( n );
4498             }
4499
4500             // check if nOnFace is inside the FACE
4501             if ( nOnFace && nOnEdge.size() == 2 )
4502             {
4503               theHelper.AddTLinks( static_cast< const SMDS_MeshFace* > ( f ));
4504               if ( !SMESH_MeshAlgos::FaceNormal( f, faceNorm, /*normalized=*/false ))
4505                 continue;
4506               gp_XYZ edgeDir  = SMESH_TNodeXYZ( nOnEdge[0] ) - SMESH_TNodeXYZ( nOnEdge[1] );
4507               gp_XYZ edgeNorm = faceNorm ^ edgeDir;
4508               n = theHelper.GetMediumNode( nOnEdge[0], nOnEdge[1], true ); // find n, not create 
4509               gp_XYZ pN0     = SMESH_TNodeXYZ( nOnEdge[0] );
4510               gp_XYZ pMedium = SMESH_TNodeXYZ( n );                   // on-edge node location
4511               gp_XYZ pFaceN  = SMESH_TNodeXYZ( nOnFace );             // on-face node location
4512               double hMedium = edgeNorm * gp_Vec( pN0, pMedium ).XYZ();
4513               double hFace   = edgeNorm * gp_Vec( pN0, pFaceN ).XYZ();
4514               if ( Abs( hMedium ) > Abs( hFace * 0.6 ))
4515               {
4516                 // nOnFace is out of FACE, move a medium on-edge node to the middle
4517                 gp_XYZ pMid3D = 0.5 * ( pN0 + SMESH_TNodeXYZ( nOnEdge[1] ));
4518                 meshDS->MoveNode( n, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
4519                 MSG( "move OUT of face " << n );
4520                 theError->myBadElements.push_back( f );
4521               }
4522             }
4523           }
4524         }
4525       }
4526       if ( !theError->myBadElements.empty() )
4527         theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
4528       return;
4529
4530     } // 2D ==============================================================================
4531
4532     if ( shape.ShapeType() == TopAbs_SOLID ) // 3D
4533     {
4534       if ( theHelper.GetMesh()->NbTetras  ( ORDER_QUADRATIC ) < 1 &&
4535            theHelper.GetMesh()->NbPyramids( ORDER_QUADRATIC ) < 1 ) return;
4536
4537       SMESHDS_SubMesh* solidSM = meshDS->MeshElements( shape );
4538       if ( !solidSM ) return;
4539
4540       // check if the SOLID is bound by concave FACEs
4541       vector< TopoDS_Face > concaveFaces;
4542       TopExp_Explorer faceIt( shape, TopAbs_FACE );
4543       for ( ; faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4544       {
4545         const TopoDS_Face&  face = TopoDS::Face( faceIt.Current() );
4546         if ( !meshDS->MeshElements( face )) continue;
4547
4548         BRepAdaptor_Surface surface( face );
4549         switch ( surface.GetType() ) {
4550         case GeomAbs_Plane: continue;
4551         case GeomAbs_Cylinder:
4552         case GeomAbs_Cone:
4553         case GeomAbs_Sphere:
4554           try
4555           {
4556             double u = 0.5 * ( surface.FirstUParameter() + surface.LastUParameter() );
4557             double v = 0.5 * ( surface.FirstVParameter() + surface.LastVParameter() );
4558             gp_Vec Du1, Dv1, Du2, Dv2, Duv2; gp_Pnt p;
4559             surface.D2( u,v, p, Du1, Dv1, Du2, Dv2, Duv2 );
4560             gp_Vec fNorm = Du1 ^ Dv1;
4561             if ( face.Orientation() == TopAbs_REVERSED ) fNorm.Reverse();
4562             bool concaveU = ( fNorm * Du2 > 1e-100 );
4563             bool concaveV = ( fNorm * Dv2 > 1e-100 );
4564             if ( concaveU || concaveV )
4565               concaveFaces.push_back( face );
4566           }
4567           catch ( Standard_Failure )
4568           {
4569             concaveFaces.push_back( face );
4570           }
4571         default:;
4572         }
4573       }
4574       if ( concaveFaces.empty() )
4575         return;
4576
4577       // fix 2D mesh on the SOLID
4578       for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4579       {
4580         SMESH_MesherHelper faceHelper( *theHelper.GetMesh() );
4581         faceHelper.SetSubShape( faceIt.Current() );
4582         force3DOutOfBoundary( faceHelper, theError );
4583       }
4584
4585       // get an iterator over faces on concaveFaces
4586       vector< SMDS_ElemIteratorPtr > faceIterVec( concaveFaces.size() );
4587       for ( size_t i = 0; i < concaveFaces.size(); ++i )
4588         faceIterVec[i] = meshDS->MeshElements( concaveFaces[i] )->GetElements();
4589       typedef SMDS_IteratorOnIterators
4590         < const SMDS_MeshElement*, vector< SMDS_ElemIteratorPtr > > TIterOnIter;
4591       SMDS_ElemIteratorPtr faceIter( new TIterOnIter( faceIterVec ));
4592
4593       // a seacher to check if a volume is close to a concave face
4594       std::auto_ptr< SMESH_ElementSearcher > faceSearcher
4595         ( SMESH_MeshAlgos::GetElementSearcher( *theHelper.GetMeshDS(), faceIter ));
4596
4597       // classifier
4598       //BRepClass3d_SolidClassifier solidClassifier( shape );
4599
4600       TIDSortedElemSet checkedVols, movedNodes;
4601       //for ( faceIt.ReInit(); faceIt.More(); faceIt.Next() ) // loop on FACEs of a SOLID
4602       for ( size_t iF = 0; iF < concaveFaces.size(); ++iF ) // loop on concave FACEs
4603       {
4604         //const TopoDS_Shape& face = faceIt.Current();
4605         const TopoDS_Shape& face = concaveFaces[ iF ];
4606         SMESHDS_SubMesh*  faceSM = meshDS->MeshElements( face );
4607         if ( !faceSM ) continue;
4608
4609         // get nodes shared by volumes (tet and pyra) on the FACE that may be distorted
4610         SMDS_NodeIteratorPtr nodeIt;
4611         if ( faceSM->NbNodes() > 0 ) {
4612           nodeIt = faceSM->GetNodes();
4613         }
4614         else {
4615           TopExp_Explorer vertex( face, TopAbs_VERTEX );
4616           SMESHDS_SubMesh* vertexSM = meshDS->MeshElements( vertex.Current() );
4617           if ( !vertexSM ) continue;
4618           nodeIt = vertexSM->GetNodes();
4619         }
4620         // get ids of sub-shapes of the FACE
4621         set< int > subIDs;
4622         SMESH_subMeshIteratorPtr smIt =
4623           theHelper.GetMesh()->GetSubMesh( face )->getDependsOnIterator(/*includeSelf=*/true);
4624         while ( smIt->more() )
4625           subIDs.insert( smIt->next()->GetId() );
4626
4627         // find suspicious volumes adjacent to the FACE
4628         vector< const SMDS_MeshNode* >    nOnFace( 4 );
4629         const SMDS_MeshNode*              nInSolid;
4630         while ( nodeIt->more() )
4631         {
4632           const SMDS_MeshNode* n     = nodeIt->next();
4633           SMDS_ElemIteratorPtr volIt = n->GetInverseElementIterator( SMDSAbs_Volume );
4634           while ( volIt->more() )
4635           {
4636             const SMDS_MeshElement* vol = volIt->next();
4637             size_t                  nbN = vol->NbCornerNodes();
4638             if ( ( nbN != 4 && nbN != 5 )  ||
4639                  !solidSM->Contains( vol ) ||
4640                  !checkedVols.insert( vol ).second )
4641               continue;
4642
4643             // get nodes on FACE and in SOLID of a suspicious volume
4644             nOnFace.clear(); nInSolid = 0;
4645             SMDS_MeshElement::iterator volNode = vol->begin_nodes();
4646             for ( int nb = nbN; nb > 0; ++volNode, --nb )
4647             {
4648               n = *volNode;
4649               if ( n->GetPosition()->GetDim() == 3 )
4650                 nInSolid = n;
4651               else if ( subIDs.count( n->getshapeId() ))
4652                 nOnFace.push_back( n );
4653               else
4654                 nInSolid = n;
4655             }
4656             if ( !nInSolid || nOnFace.size() != nbN - 1 )
4657               continue;
4658
4659             // get size of the vol
4660             SMESH_TNodeXYZ pInSolid( nInSolid ), pOnFace0( nOnFace[0] );
4661             double volLength = pInSolid.SquareDistance( nOnFace[0] );
4662             for ( size_t i = 1; i < nOnFace.size(); ++i )
4663             {
4664               volLength = Max( volLength, pOnFace0.SquareDistance( nOnFace[i] ));
4665             }
4666
4667             // check if vol is close to concaveFaces
4668             const SMDS_MeshElement* closeFace =
4669               faceSearcher->FindClosestTo( pInSolid, SMDSAbs_Face );
4670             if ( !closeFace ||
4671                  pInSolid.SquareDistance( closeFace->GetNode(0) ) > 4 * volLength )
4672               continue;
4673
4674             // check if vol is distorted, i.e. a medium node is much closer
4675             // to nInSolid than the link middle
4676             bool isDistorted = false;
4677             SMDS_FaceOfNodes onFaceTria( nOnFace[0], nOnFace[1], nOnFace[2] );
4678             if ( !SMESH_MeshAlgos::FaceNormal( &onFaceTria, faceNorm, /*normalized=*/false ))
4679               continue;
4680             theHelper.AddTLinks( static_cast< const SMDS_MeshVolume* > ( vol ));
4681             vector< pair< SMESH_TLink, const SMDS_MeshNode* > > links;
4682             for ( size_t i = 0; i < nOnFace.size(); ++i ) // loop on links between nOnFace
4683               for ( size_t j = i+1; j < nOnFace.size(); ++j )
4684               {
4685                 SMESH_TLink link( nOnFace[i], nOnFace[j] );
4686                 TLinkNodeMap::const_iterator linkIt =
4687                   theHelper.GetTLinkNodeMap().find( link );
4688                 if ( linkIt != theHelper.GetTLinkNodeMap().end() )
4689                 {
4690                   links.push_back( make_pair( linkIt->first, linkIt->second  ));
4691                   if ( !isDistorted ) {
4692                     // compare projections of nInSolid and nMedium to face normal
4693                     gp_Pnt pMedium = SMESH_TNodeXYZ( linkIt->second );
4694                     double hMedium = faceNorm * gp_Vec( pOnFace0, pMedium ).XYZ();
4695                     double hVol    = faceNorm * gp_Vec( pOnFace0, pInSolid ).XYZ();
4696                     isDistorted = ( Abs( hMedium ) > Abs( hVol * 0.5 ));
4697                   }
4698                 }
4699               }
4700             // move medium nodes to link middle
4701             if ( isDistorted )
4702             {
4703               for ( size_t i = 0; i < links.size(); ++i )
4704               {
4705                 const SMDS_MeshNode* nMedium = links[i].second;
4706                 if ( movedNodes.insert( nMedium ).second )
4707                 {
4708                   gp_Pnt pMid3D = 0.5 * ( SMESH_TNodeXYZ( links[i].first.node1() ) +
4709                                           SMESH_TNodeXYZ( links[i].first.node2() ));
4710                   meshDS->MoveNode( nMedium, pMid3D.X(), pMid3D.Y(), pMid3D.Z() );
4711                   MSG( "move OUT of solid " << nMedium );
4712                 }
4713               }
4714               theError->myBadElements.push_back( vol );
4715             }
4716           } // loop on volumes sharing a node on FACE
4717         } // loop on nodes on FACE
4718       }  // loop on FACEs of a SOLID
4719
4720       if ( !theError->myBadElements.empty() )
4721         theError->myName = EDITERR_NO_MEDIUM_ON_GEOM;
4722     } // 3D case
4723   }
4724
4725 } //namespace
4726
4727 //=======================================================================
4728 /*!
4729  * \brief Move medium nodes of faces and volumes to fix distorted elements
4730  * \param error - container of fixed distorted elements
4731  * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
4732  * 
4733  * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
4734  */
4735 //=======================================================================
4736
4737 void SMESH_MesherHelper::FixQuadraticElements(SMESH_ComputeErrorPtr& compError,
4738                                               bool                   volumeOnly)
4739 {
4740   // setenv NO_FixQuadraticElements to know if FixQuadraticElements() is guilty of bad conversion
4741   if ( getenv("NO_FixQuadraticElements") )
4742     return;
4743
4744   // 0. Apply algorithm to SOLIDs or FACEs
4745   // ----------------------------------------------
4746   if ( myShape.IsNull() ) {
4747     if ( !myMesh->HasShapeToMesh() ) return;
4748     SetSubShape( myMesh->GetShapeToMesh() );
4749
4750 #ifdef _DEBUG_
4751     int nbSolids = 0;
4752     TopTools_IndexedMapOfShape solids;
4753     TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
4754     nbSolids = solids.Extent();
4755 #endif
4756     TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
4757     for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
4758       faces.Add( f.Current() ); // not in solid
4759     }
4760     for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
4761       if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
4762         for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
4763           faces.Add( f.Current() ); // in not meshed solid
4764       }
4765       else { // fix nodes in the solid and its faces
4766 #ifdef _DEBUG_
4767         MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
4768 #endif
4769         SMESH_MesherHelper h(*myMesh);
4770         h.SetSubShape( s.Current() );
4771         h.ToFixNodeParameters(true);
4772         h.FixQuadraticElements( compError, false );
4773       }
4774     }
4775     // fix nodes on geom faces
4776 #ifdef _DEBUG_
4777     int nbfaces = faces.Extent(); /*avoid "unused varianbles": */ nbfaces++, nbfaces--; 
4778 #endif
4779     for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
4780       MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
4781       SMESH_MesherHelper h(*myMesh);
4782       h.SetSubShape( fIt.Key() );
4783       h.ToFixNodeParameters(true);
4784       h.FixQuadraticElements( compError, true);
4785     }
4786     //perf_print_all_meters(1);
4787     if ( compError && compError->myName == EDITERR_NO_MEDIUM_ON_GEOM )
4788       compError->myComment = "during conversion to quadratic, "
4789         "some medium nodes were not placed on geometry to avoid distorting elements";
4790     return;
4791   }
4792
4793   // 1. Find out type of elements and get iterator on them
4794   // ---------------------------------------------------
4795
4796   SMDS_ElemIteratorPtr elemIt;
4797   SMDSAbs_ElementType elemType = SMDSAbs_All;
4798
4799   SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
4800   if ( !submesh )
4801     return;
4802   if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
4803     elemIt = smDS->GetElements();
4804     if ( elemIt->more() ) {
4805       elemType = elemIt->next()->GetType();
4806       elemIt = smDS->GetElements();
4807     }
4808   }
4809   if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
4810     return;
4811
4812   // 2. Fill in auxiliary data structures
4813   // ----------------------------------
4814
4815   set< QLink > links;
4816   set< QFace > faces;
4817   set< QLink >::iterator pLink;
4818   set< QFace >::iterator pFace;
4819
4820   bool isCurved = false;
4821   //bool hasRectFaces = false;
4822   //set<int> nbElemNodeSet;
4823   SMDS_VolumeTool volTool;
4824
4825   TIDSortedNodeSet apexOfPyramid;
4826   const int apexIndex = 4;
4827
4828   // Issue 0020982
4829   // Move medium nodes to the link middle for elements whose corner nodes
4830   // are out of geometrical boundary to fix distorted elements.
4831   force3DOutOfBoundary( *this, compError );
4832
4833   if ( elemType == SMDSAbs_Volume )
4834   {
4835     while ( elemIt->more() ) // loop on volumes
4836     {
4837       const SMDS_MeshElement* vol = elemIt->next();
4838       if ( !vol->IsQuadratic() || !volTool.Set( vol ))
4839         return;
4840       double volMinSize2 = -1.;
4841       for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
4842       {
4843         int nbN = volTool.NbFaceNodes( iF );
4844         //nbElemNodeSet.insert( nbN );
4845         const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
4846         vector< const QLink* > faceLinks( nbN/2 );
4847         for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
4848         {
4849           // store QLink
4850           QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
4851           pLink = links.insert( link ).first;
4852           faceLinks[ iN/2 ] = & *pLink;
4853
4854           if ( link.MediumPos() == SMDS_TOP_3DSPACE )
4855           {
4856             if ( !link.IsStraight() )
4857               return; // already fixed
4858           }
4859           else if ( !isCurved )
4860           {
4861             if ( volMinSize2 < 0 ) volMinSize2 = volTool.MinLinearSize2();
4862             isCurved = !isStraightLink( volMinSize2, link._nodeMove.SquareMagnitude() );
4863           }
4864         }
4865         // store QFace
4866         pFace = faces.insert( QFace( faceLinks )).first;
4867         if ( pFace->NbVolumes() == 0 )
4868           pFace->AddSelfToLinks();
4869         pFace->SetVolume( vol );
4870 //         hasRectFaces = hasRectFaces ||
4871 //           ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
4872 //             volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
4873 #ifdef _DEBUG_
4874         if ( nbN == 6 )
4875           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
4876         else
4877           pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
4878                                                faceNodes[4],faceNodes[6] );
4879 #endif
4880       }
4881       // collect pyramid apexes for further correction
4882       if ( vol->NbCornerNodes() == 5 )
4883         apexOfPyramid.insert( vol->GetNode( apexIndex ));
4884     }
4885     set< QLink >::iterator pLink = links.begin();
4886     for ( ; pLink != links.end(); ++pLink )
4887       pLink->SetContinuesFaces();
4888   }
4889   else
4890   {
4891     while ( elemIt->more() ) // loop on faces
4892     {
4893       const SMDS_MeshElement* face = elemIt->next();
4894       if ( !face->IsQuadratic() )
4895         continue;
4896       //nbElemNodeSet.insert( face->NbNodes() );
4897       int nbN = face->NbNodes()/2;
4898       vector< const QLink* > faceLinks( nbN );
4899       for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
4900       {
4901         // store QLink
4902         QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
4903         pLink = links.insert( link ).first;
4904         faceLinks[ iN ] = & *pLink;
4905         if ( !isCurved &&
4906              link.node1()->GetPosition()->GetTypeOfPosition() < 2 &&
4907              link.node2()->GetPosition()->GetTypeOfPosition() < 2 )
4908           isCurved = !link.IsStraight();
4909       }
4910       // store QFace
4911       pFace = faces.insert( QFace( faceLinks )).first;
4912       pFace->AddSelfToLinks();
4913       //hasRectFaces = ( hasRectFaces || nbN == 4 );
4914     }
4915   }
4916   if ( !isCurved )
4917     return; // no curved edges of faces
4918
4919   // 3. Compute displacement of medium nodes
4920   // ---------------------------------------
4921
4922   SMESH_MesherHelper faceHlp(*myMesh);
4923
4924   // two loops on QFaces: the first is to treat boundary links, the second is for internal ones.
4925   TopLoc_Location loc;
4926   bool checkUV;
4927   // not to treat boundary of volumic sub-mesh.
4928   int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
4929   for ( ; isInside < 2; ++isInside )
4930   {
4931     MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
4932     SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
4933     SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
4934
4935     for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
4936       if ( bool(isInside) == pFace->IsBoundary() )
4937         continue;
4938       for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from the quadrangle
4939       {
4940         MSG( "CHAIN");
4941         // make chain of links connected via continues faces
4942         int error = ERR_OK;
4943         TChain rawChain;
4944         if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
4945         rawChain.reverse();
4946         if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
4947
4948         vector< TChain > chains;
4949         if ( error == ERR_OK ) { // chain contains continues rectangles
4950           chains.resize(1);
4951           chains[0].splice( chains[0].begin(), rawChain );
4952         }
4953         else if ( error == ERR_TRI ) {  // chain contains continues triangles
4954           TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
4955           if ( res != _OK ) { // not 'quadrangles split into triangles' in chain
4956             fixTriaNearBoundary( rawChain, *this );
4957             break;
4958           }
4959         }
4960         else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
4961           fixPrism( rawChain );
4962           break;
4963         }
4964         else {
4965           continue;
4966         }
4967         for ( size_t iC = 0; iC < chains.size(); ++iC )
4968         {
4969           TChain& chain = chains[iC];
4970           if ( chain.empty() ) continue;
4971           if ( chain.front().IsStraight() && chain.back().IsStraight() ) {
4972             MSG("3D straight - ignore");
4973             continue;
4974           }
4975           if ( chain.front()->MediumPos() > bndPos ||
4976                chain.back() ->MediumPos() > bndPos ) {
4977             MSG("Internal chain - ignore");
4978             continue;
4979           }
4980           // mesure chain length and compute link position along the chain
4981           double chainLen = 0;
4982           vector< double > linkPos;
4983           TChain savedChain; // backup
4984           MSGBEG( "Link medium nodes: ");
4985           TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
4986           for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
4987             MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
4988             double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
4989             while ( len < numeric_limits<double>::min() ) { // remove degenerated link
4990               if ( savedChain.empty() ) savedChain = chain;
4991               link1 = chain.erase( link1 );
4992               if ( link1 == chain.end() )
4993                 break;
4994               len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
4995             }
4996             chainLen += len;
4997             linkPos.push_back( chainLen );
4998           }
4999           MSG("");
5000           if ( linkPos.size() <= 2 && savedChain.size() > 2 ) {
5001             //continue;
5002             linkPos.clear();
5003             chainLen = 0;
5004             chain = savedChain;
5005             for ( link1 = chain.begin(); link1 != chain.end(); ++link1 ) {
5006               chainLen += 1;
5007               linkPos.push_back( chainLen );
5008             }
5009           }
5010           gp_Vec move0 = chain.front()->_nodeMove;
5011           gp_Vec move1 = chain.back ()->_nodeMove;
5012
5013           TopoDS_Face face;
5014           if ( !isInside )
5015           {
5016             // compute node displacement of end links of chain in parametric space of FACE
5017             TChainLink& linkOnFace = *(++chain.begin());
5018             const SMDS_MeshNode* nodeOnFace = linkOnFace->_mediumNode;
5019             TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
5020             if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
5021             {
5022               face = TopoDS::Face( f );
5023               faceHlp.SetSubShape( face );
5024               Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
5025               //bool isStraight[2]; // commented for issue 0023118
5026               for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
5027               {
5028                 TChainLink& link = is1 ? chain.back() : chain.front();
5029                 gp_XY uvm  = faceHlp.GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV );
5030                 gp_XY uv1  = faceHlp.GetNodeUV( face, link->node1(),     nodeOnFace, &checkUV );
5031                 gp_XY uv2  = faceHlp.GetNodeUV( face, link->node2(),     nodeOnFace, &checkUV );
5032                 gp_XY uv12 = faceHlp.GetMiddleUV( surf, uv1, uv2 );
5033                 // uvMove = uvm - uv12
5034                 gp_XY uvMove = ApplyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
5035                 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
5036                 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
5037                   nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
5038                 // isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),
5039                 //                                   10 * uvMove.SquareModulus());
5040               }
5041               // if ( isStraight[0] && isStraight[1] ) {
5042               //   MSG("2D straight - ignore");
5043               //   continue; // straight - no need to move nodes of internal links
5044               // }
5045
5046               // check if a chain is already fixed
5047               gp_XY uvm  = faceHlp.GetNodeUV( face, linkOnFace->_mediumNode, 0, &checkUV );
5048               gp_XY uv1  = faceHlp.GetNodeUV( face, linkOnFace->node1(), nodeOnFace, &checkUV );
5049               gp_XY uv2  = faceHlp.GetNodeUV( face, linkOnFace->node2(), nodeOnFace, &checkUV );
5050               gp_XY uv12 = faceHlp.GetMiddleUV( surf, uv1, uv2 );
5051               if (( uvm - uv12 ).SquareModulus() > 1e-10 )
5052               {
5053                 MSG("Already fixed - ignore");
5054                 continue;
5055               }
5056             }
5057           }
5058           gp_Trsf trsf;
5059           if ( isInside || face.IsNull() )
5060           {
5061             // compute node displacement of end links in their local coord systems
5062             {
5063               TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
5064               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
5065                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
5066               move0.Transform(trsf);
5067             }
5068             {
5069               TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
5070               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
5071                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
5072               move1.Transform(trsf);
5073             }
5074           }
5075           // compute displacement of medium nodes
5076           link2 = chain.begin();
5077           link0 = link2++;
5078           link1 = link2++;
5079           for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
5080           {
5081             double r = linkPos[i] / chainLen;
5082             // displacement in local coord system
5083             gp_Vec move = (1. - r) * move0 + r * move1;
5084             if ( isInside || face.IsNull()) {
5085               // transform to global
5086               gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
5087               gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
5088               try {
5089                 gp_Vec x = x01.Normalized() + x12.Normalized();
5090                 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
5091               } catch ( Standard_Failure ) {
5092                 trsf.Invert();
5093               }
5094               move.Transform(trsf);
5095               (*link1)->Move( move, /*sum=*/false, /*is2dFixed=*/false );
5096             }
5097             else {
5098               // compute 3D displacement by 2D one
5099               Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
5100               gp_XY oldUV   = faceHlp.GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV );
5101               gp_XY newUV   = ApplyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added );
5102               gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
5103               move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
5104               if ( SMDS_FacePosition* nPos =
5105                    dynamic_cast< SMDS_FacePosition* >((*link1)->_mediumNode->GetPosition()))
5106                 nPos->SetParameters( newUV.X(), newUV.Y() );
5107 #ifdef _DEBUG_
5108               if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
5109                    move.SquareMagnitude())
5110               {
5111                 gp_XY uv0 = faceHlp.GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV );
5112                 gp_XY uv2 = faceHlp.GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV );
5113                 MSG( "TOO LONG MOVE \t" <<
5114                      "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
5115                      "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
5116                      "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
5117                      "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
5118               }
5119 #endif
5120               (*link1)->Move( move, /*sum=*/false, /*is2dFixed=*/true );
5121             }
5122             MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
5123                  << chain.front()->_mediumNode->GetID() <<"-"
5124                  << chain.back ()->_mediumNode->GetID() <<
5125                  " by " << move.Magnitude());
5126           }
5127         } // loop on chains of links
5128       } // loop on 2 directions of propagation from quadrangle
5129     } // loop on faces
5130   } // fix faces and/or volumes
5131
5132   // 4. Move nodes
5133   // -------------
5134
5135   TIDSortedElemSet biQuadQuas, biQuadTris, triQuadHexa;
5136   const SMDS_MeshElement *biQuadQua, *triQuadHex;
5137   const bool toFixCentralNodes = ( myMesh->NbBiQuadQuadrangles() +
5138                                    myMesh->NbBiQuadTriangles() +
5139                                    myMesh->NbTriQuadraticHexas() );
5140   double distXYZ[4];
5141   faceHlp.ToFixNodeParameters( true );
5142
5143   for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
5144     if ( pLink->IsMoved() )
5145     {
5146       gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
5147
5148       // put on surface nodes on FACE but moved in 3D (23050)
5149       if ( !pLink->IsFixedOnSurface() )
5150       {
5151         faceHlp.SetSubShape( pLink->_mediumNode->getshapeId() );
5152         if ( faceHlp.GetSubShape().ShapeType() == TopAbs_FACE )
5153         {
5154           const_cast<SMDS_MeshNode*>( pLink->_mediumNode )->setXYZ( p.X(), p.Y(), p.Z());
5155           p.Coord( distXYZ[1], distXYZ[2], distXYZ[3] );
5156           gp_XY uv( Precision::Infinite(), 0 );
5157           if ( faceHlp.CheckNodeUV( TopoDS::Face( faceHlp.GetSubShape() ), pLink->_mediumNode,
5158                                     uv, /*tol=*/pLink->Move().Modulus(), /*force=*/true, distXYZ ))
5159             p.SetCoord( distXYZ[1], distXYZ[2], distXYZ[3] );
5160         }
5161       }
5162       GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
5163
5164       // collect bi-quadratic elements
5165       if ( toFixCentralNodes )
5166       {
5167         biQuadQua = triQuadHex = 0;
5168         SMDS_ElemIteratorPtr eIt = pLink->_mediumNode->GetInverseElementIterator();
5169         while ( eIt->more() )
5170         {
5171           const SMDS_MeshElement* e = eIt->next();
5172           switch( e->GetEntityType() ) {
5173           case SMDSEntity_BiQuad_Quadrangle: biQuadQuas.insert( e ); break;
5174           case SMDSEntity_BiQuad_Triangle:   biQuadTris.insert( e ); break;
5175           case SMDSEntity_TriQuad_Hexa:      triQuadHexa.insert( e ); break;
5176           default:;
5177           }
5178         }
5179       }
5180     }
5181   }
5182   // Fix positions of central nodes of bi-tri-quadratic elements
5183
5184   // treat bi-quad quadrangles
5185   {
5186     vector< const SMDS_MeshNode* > nodes( 9 );
5187     gp_XY uv[ 9 ];
5188     TIDSortedElemSet::iterator quadIt = biQuadQuas.begin();
5189     for ( ; quadIt != biQuadQuas.end(); ++quadIt )
5190     {
5191       const SMDS_MeshElement* quad = *quadIt;
5192       // nodes
5193       nodes.clear();
5194       nodes.assign( quad->begin_nodes(), quad->end_nodes() );
5195       // FACE
5196       TopoDS_Shape S = GetSubShapeByNode( nodes.back(), GetMeshDS() );
5197       if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
5198       const TopoDS_Face& F = TopoDS::Face( S );
5199       Handle( Geom_Surface ) surf = BRep_Tool::Surface( F, loc );
5200       const double tol = BRep_Tool::Tolerance( F );
5201       // UV
5202       for ( int i = 0; i < 8; ++i )
5203       {
5204         uv[ i ] = GetNodeUV( F, nodes[i], nodes[8], &checkUV );
5205         // as this method is used after mesh generation, UV of nodes is not
5206         // updated according to bending links, so we update 
5207         if ( i > 3 && nodes[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
5208           CheckNodeUV( F, nodes[i], uv[ i ], 2*tol, /*force=*/true );
5209       }
5210       AdjustByPeriod( F, uv, 8 ); // put uv[] within a period (IPAL52698)
5211       // move the central node
5212       gp_XY uvCent = calcTFI (0.5, 0.5, uv[0],uv[1],uv[2],uv[3],uv[4],uv[5],uv[6],uv[7] );
5213       gp_Pnt p = surf->Value( uvCent.X(), uvCent.Y() ).Transformed( loc );
5214       GetMeshDS()->MoveNode( nodes[8], p.X(), p.Y(), p.Z());
5215     }
5216   }
5217
5218   // treat bi-quad triangles
5219   {
5220     vector< const SMDS_MeshNode* > nodes;
5221     gp_XY uv[ 6 ];
5222     TIDSortedElemSet::iterator triIt = biQuadTris.begin();
5223     for ( ; triIt != biQuadTris.end(); ++triIt )
5224     {
5225       const SMDS_MeshElement* tria = *triIt;
5226       // FACE
5227       const TopoDS_Shape& S = GetMeshDS()->IndexToShape( tria->getshapeId() );
5228       if ( S.IsNull() || S.ShapeType() != TopAbs_FACE ) continue;
5229       const TopoDS_Face& F = TopoDS::Face( S );
5230       Handle( Geom_Surface ) surf = BRep_Tool::Surface( F, loc );
5231       const double tol = BRep_Tool::Tolerance( F );
5232
5233       // nodes
5234       nodes.assign( tria->begin_nodes(), tria->end_nodes() );
5235       // UV
5236       bool uvOK = true, badTria = false;
5237       for ( int i = 0; i < 6; ++i )
5238       {
5239         uv[ i ] = GetNodeUV( F, nodes[i], nodes[(i+1)%3], &uvOK );
5240         // as this method is used after mesh generation, UV of nodes is not
5241         // updated according to bending links, so we update 
5242         if ( nodes[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
5243           CheckNodeUV( F, nodes[i], uv[ i ], 2*tol, /*force=*/true );
5244       }
5245
5246       // move the central node
5247       gp_Pnt p;
5248       if ( !uvOK || badTria )
5249       {
5250         p = ( SMESH_TNodeXYZ( nodes[3] ) +
5251               SMESH_TNodeXYZ( nodes[4] ) +
5252               SMESH_TNodeXYZ( nodes[5] )) / 3;
5253       }
5254       else
5255       {
5256         AdjustByPeriod( F, uv, 6 ); // put uv[] within a period (IPAL52698)
5257         gp_XY uvCent = GetCenterUV( uv[0], uv[1], uv[2], uv[3], uv[4], uv[5], &badTria );
5258         p = surf->Value( uvCent.X(), uvCent.Y() ).Transformed( loc );
5259       }
5260       GetMeshDS()->MoveNode( tria->GetNode(6), p.X(), p.Y(), p.Z() );
5261     }
5262   }
5263
5264   // treat tri-quadratic hexahedra
5265   {
5266     SMDS_VolumeTool volExp;
5267     TIDSortedElemSet::iterator hexIt = triQuadHexa.begin();
5268     for ( ; hexIt != triQuadHexa.end(); ++hexIt )
5269     {
5270       volExp.Set( *hexIt, /*ignoreCentralNodes=*/false );
5271
5272       // fix nodes central in sides
5273       for ( int iQuad = 0; iQuad < volExp.NbFaces(); ++iQuad )
5274       {
5275         const SMDS_MeshNode** quadNodes = volExp.GetFaceNodes( iQuad );
5276         if ( quadNodes[8]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
5277         {
5278           gp_XYZ p = calcTFI( 0.5, 0.5,
5279                               SMESH_TNodeXYZ( quadNodes[0] ), SMESH_TNodeXYZ( quadNodes[2] ),
5280                               SMESH_TNodeXYZ( quadNodes[4] ), SMESH_TNodeXYZ( quadNodes[6] ),
5281                               SMESH_TNodeXYZ( quadNodes[1] ), SMESH_TNodeXYZ( quadNodes[3] ),
5282                               SMESH_TNodeXYZ( quadNodes[5] ), SMESH_TNodeXYZ( quadNodes[7] ));
5283           GetMeshDS()->MoveNode( quadNodes[8], p.X(), p.Y(), p.Z());
5284         }
5285       }
5286
5287       // fix the volume central node
5288       vector<gp_XYZ> pointsOnShapes( SMESH_Block::ID_Shell );
5289       const SMDS_MeshNode** hexNodes = volExp.GetNodes();
5290
5291       pointsOnShapes[ SMESH_Block::ID_V000 ] = SMESH_TNodeXYZ( hexNodes[ 0 ] );
5292       pointsOnShapes[ SMESH_Block::ID_V100 ] = SMESH_TNodeXYZ( hexNodes[ 3 ] );
5293       pointsOnShapes[ SMESH_Block::ID_V010 ] = SMESH_TNodeXYZ( hexNodes[ 1 ] );
5294       pointsOnShapes[ SMESH_Block::ID_V110 ] = SMESH_TNodeXYZ( hexNodes[ 2 ] );
5295       pointsOnShapes[ SMESH_Block::ID_V001 ] = SMESH_TNodeXYZ( hexNodes[ 4 ] );
5296       pointsOnShapes[ SMESH_Block::ID_V101 ] = SMESH_TNodeXYZ( hexNodes[ 7 ] );
5297       pointsOnShapes[ SMESH_Block::ID_V011 ] = SMESH_TNodeXYZ( hexNodes[ 5 ] );
5298       pointsOnShapes[ SMESH_Block::ID_V111 ] = SMESH_TNodeXYZ( hexNodes[ 6 ] );
5299
5300       pointsOnShapes[ SMESH_Block::ID_Ex00 ] = SMESH_TNodeXYZ( hexNodes[ 11 ] );
5301       pointsOnShapes[ SMESH_Block::ID_Ex10 ] = SMESH_TNodeXYZ( hexNodes[  9 ] );
5302       pointsOnShapes[ SMESH_Block::ID_E0y0 ] = SMESH_TNodeXYZ( hexNodes[  8 ] );
5303       pointsOnShapes[ SMESH_Block::ID_E1y0 ] = SMESH_TNodeXYZ( hexNodes[ 10 ] );
5304       pointsOnShapes[ SMESH_Block::ID_Ex01 ] = SMESH_TNodeXYZ( hexNodes[ 15 ] );
5305       pointsOnShapes[ SMESH_Block::ID_Ex11 ] = SMESH_TNodeXYZ( hexNodes[ 13 ] );
5306       pointsOnShapes[ SMESH_Block::ID_E0y1 ] = SMESH_TNodeXYZ( hexNodes[ 12 ] );
5307       pointsOnShapes[ SMESH_Block::ID_E1y1 ] = SMESH_TNodeXYZ( hexNodes[ 14 ] );
5308       pointsOnShapes[ SMESH_Block::ID_E00z ] = SMESH_TNodeXYZ( hexNodes[ 16 ] );    
5309       pointsOnShapes[ SMESH_Block::ID_E10z ] = SMESH_TNodeXYZ( hexNodes[ 19 ] );    
5310       pointsOnShapes[ SMESH_Block::ID_E01z ] = SMESH_TNodeXYZ( hexNodes[ 17 ] );    
5311       pointsOnShapes[ SMESH_Block::ID_E11z ] = SMESH_TNodeXYZ( hexNodes[ 18 ] );
5312
5313       pointsOnShapes[ SMESH_Block::ID_Fxy0 ] = SMESH_TNodeXYZ( hexNodes[ 20 ] );
5314       pointsOnShapes[ SMESH_Block::ID_Fxy1 ] = SMESH_TNodeXYZ( hexNodes[ 25 ] );
5315       pointsOnShapes[ SMESH_Block::ID_Fx0z ] = SMESH_TNodeXYZ( hexNodes[ 21 ] );   
5316       pointsOnShapes[ SMESH_Block::ID_Fx1z ] = SMESH_TNodeXYZ( hexNodes[ 23 ] );   
5317       pointsOnShapes[ SMESH_Block::ID_F0yz ] = SMESH_TNodeXYZ( hexNodes[ 24 ] );    
5318       pointsOnShapes[ SMESH_Block::ID_F1yz ] = SMESH_TNodeXYZ( hexNodes[ 22 ] );
5319
5320       gp_XYZ nCenterParams(0.5, 0.5, 0.5), nCenterCoords;
5321       SMESH_Block::ShellPoint( nCenterParams, pointsOnShapes, nCenterCoords );
5322       GetMeshDS()->MoveNode( hexNodes[26],
5323                              nCenterCoords.X(), nCenterCoords.Y(), nCenterCoords.Z());
5324     }
5325   }
5326 }