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