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