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