Salome HOME
Merge from V5_1_3_BR branch (07/12/09)
[modules/smesh.git] / src / SMESH / SMESH_MesherHelper.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // File:      SMESH_MesherHelper.cxx
23 // Created:   15.02.06 15:22:41
24 // Author:    Sergey KUUL
25 //
26 #include "SMESH_MesherHelper.hxx"
27
28 #include "SMDS_FacePosition.hxx" 
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_VolumeTool.hxx"
31 #include "SMESH_subMesh.hxx"
32
33 #include <BRepAdaptor_Surface.hxx>
34 #include <BRepTools.hxx>
35 #include <BRepTools_WireExplorer.hxx>
36 #include <BRep_Tool.hxx>
37 #include <Geom2d_Curve.hxx>
38 #include <GeomAPI_ProjectPointOnSurf.hxx>
39 #include <Geom_Curve.hxx>
40 #include <Geom_Surface.hxx>
41 #include <ShapeAnalysis.hxx>
42 #include <TopExp.hxx>
43 #include <TopExp_Explorer.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TopTools_MapIteratorOfMapOfShape.hxx>
46 #include <TopTools_MapOfShape.hxx>
47 #include <TopoDS.hxx>
48 #include <gp_Ax3.hxx>
49 #include <gp_Pnt2d.hxx>
50 #include <gp_Trsf.hxx>
51
52 #include <Standard_Failure.hxx>
53 #include <Standard_ErrorHandler.hxx>
54
55 #include <utilities.h>
56
57 #include <limits>
58
59 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
60
61 namespace {
62
63   gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
64
65 }
66
67 //================================================================================
68 /*!
69  * \brief Constructor
70  */
71 //================================================================================
72
73 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
74   : myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false)
75 {
76   mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
77 }
78
79 //=======================================================================
80 //function : CheckShape
81 //purpose  : 
82 //=======================================================================
83
84 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
85 {
86   SMESHDS_Mesh* meshDS = GetMeshDS();
87   // we can create quadratic elements only if all elements
88   // created on subshapes of given shape are quadratic
89   // also we have to fill myTLinkNodeMap
90   myCreateQuadratic = true;
91   mySeamShapeIds.clear();
92   myDegenShapeIds.clear();
93   TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
94   SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
95
96   int nbOldLinks = myTLinkNodeMap.size();
97
98   TopExp_Explorer exp( aSh, subType );
99   for (; exp.More() && myCreateQuadratic; exp.Next()) {
100     if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
101       if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
102         while(it->more()) {
103           const SMDS_MeshElement* e = it->next();
104           if ( e->GetType() != elemType || !e->IsQuadratic() ) {
105             myCreateQuadratic = false;
106             break;
107           }
108           else {
109             // fill TLinkNodeMap
110             switch ( e->NbNodes() ) {
111             case 3:
112               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
113             case 6:
114               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
115               AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
116               AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
117             case 8:
118               AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
119               AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
120               AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
121               AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
122               break;
123             default:
124               myCreateQuadratic = false;
125               break;
126             }
127           }
128         }
129       }
130     }
131   }
132
133   if ( nbOldLinks == myTLinkNodeMap.size() )
134     myCreateQuadratic = false;
135
136   if(!myCreateQuadratic) {
137     myTLinkNodeMap.clear();
138   }
139   SetSubShape( aSh );
140
141   return myCreateQuadratic;
142 }
143
144 //================================================================================
145 /*!
146  * \brief Set geomerty to make elements on
147   * \param aSh - geomertic shape
148  */
149 //================================================================================
150
151 void SMESH_MesherHelper::SetSubShape(const int aShID)
152 {
153   if ( aShID == myShapeID )
154     return;
155   if ( aShID > 1 )
156     SetSubShape( GetMeshDS()->IndexToShape( aShID ));
157   else
158     SetSubShape( TopoDS_Shape() );
159 }
160
161 //================================================================================
162 /*!
163  * \brief Set geomerty to make elements on
164   * \param aSh - geomertic shape
165  */
166 //================================================================================
167
168 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
169 {
170   if ( myShape.IsSame( aSh ))
171     return;
172
173   myShape = aSh;
174   mySeamShapeIds.clear();
175   myDegenShapeIds.clear();
176
177   if ( myShape.IsNull() ) {
178     myShapeID  = 0;
179     return;
180   }
181   SMESHDS_Mesh* meshDS = GetMeshDS();
182   myShapeID = meshDS->ShapeToIndex(aSh);
183
184   // treatment of periodic faces
185   for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
186   {
187     const TopoDS_Face& face = TopoDS::Face( eF.Current() );
188     BRepAdaptor_Surface surface( face );
189     if ( surface.IsUPeriodic() || surface.IsVPeriodic() )
190     {
191       for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
192       {
193         // look for a seam edge
194         const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
195         if ( BRep_Tool::IsClosed( edge, face )) {
196           // initialize myPar1, myPar2 and myParIndex
197           if ( mySeamShapeIds.empty() ) {
198             gp_Pnt2d uv1, uv2;
199             BRep_Tool::UVPoints( edge, face, uv1, uv2 );
200             if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
201             {
202               myParIndex = 1; // U periodic
203               myPar1 = surface.FirstUParameter();
204               myPar2 = surface.LastUParameter();
205             }
206             else {
207               myParIndex = 2;  // V periodic
208               myPar1 = surface.FirstVParameter();
209               myPar2 = surface.LastVParameter();
210             }
211           }
212           // store seam shape indices, negative if shape encounters twice
213           int edgeID = meshDS->ShapeToIndex( edge );
214           mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
215           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
216             int vertexID = meshDS->ShapeToIndex( v.Current() );
217             mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
218           }
219         }
220
221         // look for a degenerated edge
222         if ( BRep_Tool::Degenerated( edge )) {
223           myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
224           for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
225             myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
226         }
227       }
228     }
229   }
230 }
231
232 //================================================================================
233   /*!
234    * \brief Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
235     * \param F - the face
236     * \retval bool - return true if the face is periodic
237    */
238 //================================================================================
239
240 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
241 {
242   if ( F.IsNull() ) return !mySeamShapeIds.empty();
243
244   if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
245     return !mySeamShapeIds.empty();
246
247   TopLoc_Location loc;
248   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
249   if ( !aSurface.IsNull() )
250     return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
251
252   return false;
253 }
254
255 //=======================================================================
256 //function : IsMedium
257 //purpose  : 
258 //=======================================================================
259
260 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode*      node,
261                                   const SMDSAbs_ElementType typeToCheck)
262 {
263   return SMESH_MeshEditor::IsMedium( node, typeToCheck );
264 }
265
266 //=======================================================================
267 /*!
268  * \brief Return support shape of a node
269  * \param node - the node
270  * \param meshDS - mesh DS
271  * \retval TopoDS_Shape - found support shape
272  */
273 //=======================================================================
274
275 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
276                                                    SMESHDS_Mesh*        meshDS)
277 {
278   int shapeID = node->GetPosition()->GetShapeId();
279   if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
280     return meshDS->IndexToShape( shapeID );
281   else
282     return TopoDS_Shape();
283 }
284
285
286 //=======================================================================
287 //function : AddTLinkNode
288 //purpose  : 
289 //=======================================================================
290 /*!
291  * Auxilary function for filling myTLinkNodeMap
292  */
293 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
294                                       const SMDS_MeshNode* n2,
295                                       const SMDS_MeshNode* n12)
296 {
297   // add new record to map
298   SMESH_TLink link( n1, n2 );
299   myTLinkNodeMap.insert( make_pair(link,n12));
300 }
301
302 //=======================================================================
303 /*!
304  * \brief Select UV on either of 2 pcurves of a seam edge, closest to the given UV
305  * \param uv1 - UV on the seam
306  * \param uv2 - UV within a face
307  * \retval gp_Pnt2d - selected UV
308  */
309 //=======================================================================
310
311 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
312 {
313   double p1 = uv1.Coord( myParIndex );
314   double p2 = uv2.Coord( myParIndex );
315   double p3 = ( Abs( p1 - myPar1 ) < Abs( p1 - myPar2 )) ? myPar2 : myPar1;
316   if ( Abs( p2 - p1 ) > Abs( p2 - p3 ))
317     p1 = p3;
318   gp_Pnt2d result = uv1;
319   result.SetCoord( myParIndex, p1 );
320   return result;
321 }
322
323 //=======================================================================
324 /*!
325  * \brief Return node UV on face
326  * \param F - the face
327  * \param n - the node
328  * \param n2 - a node of element being created located inside a face
329  * \param check - optional flag returing false if found UV are invalid
330  * \retval gp_XY - resulting UV
331  */
332 //=======================================================================
333
334 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face&   F,
335                                     const SMDS_MeshNode* n,
336                                     const SMDS_MeshNode* n2,
337                                     bool*                check) const
338 {
339   gp_Pnt2d uv( 1e100, 1e100 );
340   const SMDS_PositionPtr Pos = n->GetPosition();
341   bool uvOK = false;
342   if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
343   {
344     // node has position on face
345     const SMDS_FacePosition* fpos =
346       static_cast<const SMDS_FacePosition*>(n->GetPosition().get());
347     uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
348     uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), BRep_Tool::Tolerance( F ));
349   }
350   else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
351   {
352     // node has position on edge => it is needed to find
353     // corresponding edge from face, get pcurve for this
354     // edge and retrieve value from this pcurve
355     const SMDS_EdgePosition* epos =
356       static_cast<const SMDS_EdgePosition*>(n->GetPosition().get());
357     int edgeID = Pos->GetShapeId();
358     TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
359     double f, l, u = epos->GetUParameter();
360     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
361     if ( f < u && u < l )
362       uv = C2d->Value( u );
363     else
364       uv.SetCoord(0.,0.);
365     uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), BRep_Tool::Tolerance( E ));
366
367     // for a node on a seam edge select one of UVs on 2 pcurves
368     if ( n2 && IsSeamShape( edgeID ) )
369     {
370       uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
371     }
372     else
373     { // adjust uv to period
374       TopLoc_Location loc;
375       Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
376       Standard_Boolean isUPeriodic = S->IsUPeriodic();
377       Standard_Boolean isVPeriodic = S->IsVPeriodic();
378       if ( isUPeriodic || isVPeriodic ) {
379         Standard_Real UF,UL,VF,VL;
380         S->Bounds(UF,UL,VF,VL);
381         if(isUPeriodic)
382           uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
383         if(isVPeriodic)
384           uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
385       }
386     }
387   }
388   else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
389   {
390     if ( int vertexID = n->GetPosition()->GetShapeId() ) {
391       const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
392       try {
393         uv = BRep_Tool::Parameters( V, F );
394         uvOK = true;
395       }
396       catch (Standard_Failure& exc) {
397       }
398       if ( !uvOK ) {
399         for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
400           uvOK = ( V == vert.Current() );
401         if ( !uvOK ) {
402 #ifdef _DEBUG_
403           MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
404                << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
405 #endif
406           // get UV of a vertex closest to the node
407           double dist = 1e100;
408           gp_Pnt pn = XYZ( n );
409           for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
410             TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
411             gp_Pnt p = BRep_Tool::Pnt( curV );
412             double curDist = p.SquareDistance( pn );
413             if ( curDist < dist ) {
414               dist = curDist;
415               uv = BRep_Tool::Parameters( curV, F );
416               uvOK = ( dist < DBL_MIN );
417             }
418           }
419         }
420         else {
421           TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
422           for ( ; it.More(); it.Next() ) {
423             if ( it.Value().ShapeType() == TopAbs_EDGE ) {
424               const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
425               double f,l;
426               Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
427               if ( !C2d.IsNull() ) {
428                 double u = ( V == TopExp::FirstVertex( edge ) ) ?  f : l;
429                 uv = C2d->Value( u );
430                 break;
431               }
432             }
433           }
434         }
435       }
436       if ( n2 && IsSeamShape( vertexID ) )
437         uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
438     }
439   }
440
441   if ( check )
442     *check = uvOK;
443
444   return uv.XY();
445 }
446
447 //=======================================================================
448 /*!
449  * \brief Check and fix node UV on a face
450  *  \retval bool - false if UV is bad and could not be fixed
451  */
452 //=======================================================================
453
454 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face&   F,
455                                      const SMDS_MeshNode* n,
456                                      gp_XY&               uv,
457                                      const double         tol) const
458 {
459   if ( !myOkNodePosShapes.count( n->GetPosition()->GetShapeId() ))
460   {
461     // check that uv is correct
462     TopLoc_Location loc;
463     Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
464     gp_Pnt nodePnt = XYZ( n );
465     if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
466     if ( nodePnt.Distance( surface->Value( uv.X(), uv.Y() )) > tol )
467     {
468       // uv incorrect, project the node to surface
469       GeomAPI_ProjectPointOnSurf projector( nodePnt, surface, tol );
470       if ( !projector.IsDone() || projector.NbPoints() < 1 )
471       {
472         MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
473         return false;
474       }
475       Quantity_Parameter U,V;
476       projector.LowerDistanceParameters(U,V);
477       if ( nodePnt.Distance( surface->Value( U, V )) > tol )
478       {
479         MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
480         return false;
481       }
482       uv.SetCoord( U,V );
483     }
484     else if ( uv.Modulus() > numeric_limits<double>::min() )
485     {
486       ((SMESH_MesherHelper*) this)->myOkNodePosShapes.insert( n->GetPosition()->GetShapeId() );
487     }
488   }
489   return true;
490 }
491
492 //=======================================================================
493 /*!
494  * \brief Return middle UV taking in account surface period
495  */
496 //=======================================================================
497
498 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
499                                       const gp_XY&                p1,
500                                       const gp_XY&                p2)
501 {
502   if ( surface.IsNull() )
503     return 0.5 * ( p1 + p2 );
504   //checking if surface is periodic
505   Standard_Real UF,UL,VF,VL;
506   surface->Bounds(UF,UL,VF,VL);
507
508   Standard_Real u,v;
509   Standard_Boolean isUPeriodic = surface->IsUPeriodic();
510   if(isUPeriodic) {
511     Standard_Real UPeriod = surface->UPeriod();
512     Standard_Real p2x = p2.X()+ShapeAnalysis::AdjustByPeriod(p2.X(),p1.X(),UPeriod);
513     Standard_Real pmid = (p1.X()+p2x)/2.;
514     u = pmid+ShapeAnalysis::AdjustToPeriod(pmid,UF,UL);
515   }
516   else {
517     u= (p1.X()+p2.X())/2.;
518   }
519   Standard_Boolean isVPeriodic = surface->IsVPeriodic();
520   if(isVPeriodic) {
521     Standard_Real VPeriod = surface->VPeriod();
522     Standard_Real p2y = p2.Y()+ShapeAnalysis::AdjustByPeriod(p2.Y(),p1.Y(),VPeriod);
523     Standard_Real pmid = (p1.Y()+p2y)/2.;
524     v = pmid+ShapeAnalysis::AdjustToPeriod(pmid,VF,VL);
525   }
526   else {
527     v = (p1.Y()+p2.Y())/2.;
528   }
529   return gp_XY( u,v );
530 }
531
532 //=======================================================================
533 /*!
534  * \brief Return node U on edge
535  * \param E - the Edge
536  * \param n - the node
537  * \retval double - resulting U
538  * 
539  * Auxilary function called form GetMediumNode()
540  */
541 //=======================================================================
542
543 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge&   E,
544                                     const SMDS_MeshNode* n,
545                                     bool*                check)
546 {
547   double param = 0;
548   const SMDS_PositionPtr Pos = n->GetPosition();
549   if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE) {
550     const SMDS_EdgePosition* epos =
551       static_cast<const SMDS_EdgePosition*>(n->GetPosition().get());
552     param =  epos->GetUParameter();
553   }
554   else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX) {
555     SMESHDS_Mesh * meshDS = GetMeshDS();
556     int vertexID = n->GetPosition()->GetShapeId();
557     const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
558     param =  BRep_Tool::Parameter( V, E );
559   }
560   return param;
561 }
562
563 //================================================================================
564 /*!
565  * \brief Return existing or create new medium nodes between given ones
566  *  \param force3d - if true, new node is the middle of n1 and n2,
567  *                   else is located on geom face or geom edge
568  */
569 //================================================================================
570
571 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
572                                                        const SMDS_MeshNode* n2,
573                                                        bool force3d)
574 {
575   SMESH_TLink link(n1,n2);
576   ItTLinkNode itLN = myTLinkNodeMap.find( link );
577   if ( itLN != myTLinkNodeMap.end() ) {
578     return (*itLN).second;
579   }
580   // create medium node
581   SMDS_MeshNode* n12;
582   SMESHDS_Mesh* meshDS = GetMeshDS();
583   int faceID = -1, edgeID = -1;
584   const SMDS_PositionPtr Pos1 = n1->GetPosition();
585   const SMDS_PositionPtr Pos2 = n2->GetPosition();
586
587   if( myShape.IsNull() )
588   {
589     if( Pos1->GetTypeOfPosition()==SMDS_TOP_FACE ) {
590       faceID = Pos1->GetShapeId();
591     }
592     else if( Pos2->GetTypeOfPosition()==SMDS_TOP_FACE ) {
593       faceID = Pos2->GetShapeId();
594     }
595
596     if( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
597       edgeID = Pos1->GetShapeId();
598     }
599     if( Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE ) {
600       edgeID = Pos2->GetShapeId();
601     }
602   }
603   if(!force3d)
604   {
605     // we try to create medium node using UV parameters of
606     // nodes, else - medium between corresponding 3d points
607
608     TopAbs_ShapeEnum shapeType = myShape.IsNull() ? TopAbs_SHAPE : myShape.ShapeType();
609     if(faceID>0 || shapeType == TopAbs_FACE) {
610       // obtaining a face and 2d points for nodes
611       TopoDS_Face F;
612       if( myShape.IsNull() )
613         F = TopoDS::Face(meshDS->IndexToShape(faceID));
614       else {
615         F = TopoDS::Face(myShape);
616         faceID = myShapeID;
617       }
618       bool uvOK1, uvOK2;
619       gp_XY p1 = GetNodeUV(F,n1,n2, &uvOK1);
620       gp_XY p2 = GetNodeUV(F,n2,n1, &uvOK2);
621
622       if ( uvOK1 && uvOK2 )
623       {
624         if ( IsDegenShape( Pos1->GetShapeId() ))
625           p1.SetCoord( myParIndex, p2.Coord( myParIndex ));
626         else if ( IsDegenShape( Pos2->GetShapeId() ))
627           p2.SetCoord( myParIndex, p1.Coord( myParIndex ));
628
629         TopLoc_Location loc;
630         Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
631         gp_XY uv = GetMiddleUV( S, p1, p2 );
632         gp_Pnt P = S->Value( uv.X(), uv.Y() ).Transformed(loc);
633         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
634         meshDS->SetNodeOnFace(n12, faceID, uv.X(), uv.Y());
635         myTLinkNodeMap.insert(make_pair(link,n12));
636         return n12;
637       }
638     }
639     if (edgeID>0 || shapeType == TopAbs_EDGE) {
640
641       TopoDS_Edge E;
642       if( myShape.IsNull() )
643         E = TopoDS::Edge(meshDS->IndexToShape(edgeID));
644       else {
645         E = TopoDS::Edge(myShape);
646         edgeID = myShapeID;
647       }
648
649       double p1 = GetNodeU(E,n1);
650       double p2 = GetNodeU(E,n2);
651
652       double f,l;
653       Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
654       if(!C.IsNull()) {
655
656         Standard_Boolean isPeriodic = C->IsPeriodic();
657         double u;
658         if(isPeriodic) {
659           Standard_Real Period = C->Period();
660           Standard_Real p = p2+ShapeAnalysis::AdjustByPeriod(p2,p1,Period);
661           Standard_Real pmid = (p1+p)/2.;
662           u = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
663         }
664         else
665           u = (p1+p2)/2.;
666
667         gp_Pnt P = C->Value( u );
668         n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
669         meshDS->SetNodeOnEdge(n12, edgeID, u);
670         myTLinkNodeMap.insert(make_pair(link,n12));
671         return n12;
672       }
673     }
674   }
675   // 3d variant
676   double x = ( n1->X() + n2->X() )/2.;
677   double y = ( n1->Y() + n2->Y() )/2.;
678   double z = ( n1->Z() + n2->Z() )/2.;
679   n12 = meshDS->AddNode(x,y,z);
680   if(edgeID>0)
681     meshDS->SetNodeOnEdge(n12, edgeID);
682   else if(faceID>0)
683     meshDS->SetNodeOnFace(n12, faceID);
684   else
685     meshDS->SetNodeInVolume(n12, myShapeID);
686   myTLinkNodeMap.insert( make_pair( link, n12 ));
687   return n12;
688 }
689
690 //=======================================================================
691 /*!
692  * Creates a node
693  */
694 //=======================================================================
695
696 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID)
697 {
698   SMESHDS_Mesh * meshDS = GetMeshDS();
699   SMDS_MeshNode* node = 0;
700   if ( ID )
701     node = meshDS->AddNodeWithID( x, y, z, ID );
702   else
703     node = meshDS->AddNode( x, y, z );
704   if ( mySetElemOnShape && myShapeID > 0 ) {
705     switch ( myShape.ShapeType() ) {
706     case TopAbs_SOLID:  meshDS->SetNodeInVolume( node, myShapeID); break;
707     case TopAbs_SHELL:  meshDS->SetNodeInVolume( node, myShapeID); break;
708     case TopAbs_FACE:   meshDS->SetNodeOnFace(   node, myShapeID); break;
709     case TopAbs_EDGE:   meshDS->SetNodeOnEdge(   node, myShapeID); break;
710     case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
711     default: ;
712     }
713   }
714   return node;
715 }
716
717 //=======================================================================
718 /*!
719  * Creates quadratic or linear edge
720  */
721 //=======================================================================
722
723 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
724                                                 const SMDS_MeshNode* n2,
725                                                 const int id,
726                                                 const bool force3d)
727 {
728   SMESHDS_Mesh * meshDS = GetMeshDS();
729   
730   SMDS_MeshEdge* edge = 0;
731   if (myCreateQuadratic) {
732     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
733     if(id)
734       edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
735     else
736       edge = meshDS->AddEdge(n1, n2, n12);
737   }
738   else {
739     if(id)
740       edge = meshDS->AddEdgeWithID(n1, n2, id);
741     else
742       edge = meshDS->AddEdge(n1, n2);
743   }
744
745   if ( mySetElemOnShape && myShapeID > 0 )
746     meshDS->SetMeshElementOnShape( edge, myShapeID );
747
748   return edge;
749 }
750
751 //=======================================================================
752 /*!
753  * Creates quadratic or linear triangle
754  */
755 //=======================================================================
756
757 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
758                                            const SMDS_MeshNode* n2,
759                                            const SMDS_MeshNode* n3,
760                                            const int id,
761                                            const bool force3d)
762 {
763   SMESHDS_Mesh * meshDS = GetMeshDS();
764   SMDS_MeshFace* elem = 0;
765
766   if( n1==n2 || n2==n3 || n3==n1 )
767     return elem;
768
769   if(!myCreateQuadratic) {
770     if(id)
771       elem = meshDS->AddFaceWithID(n1, n2, n3, id);
772     else
773       elem = meshDS->AddFace(n1, n2, n3);
774   }
775   else {
776     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
777     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
778     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
779
780     if(id)
781       elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
782     else
783       elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
784   }
785   if ( mySetElemOnShape && myShapeID > 0 )
786     meshDS->SetMeshElementOnShape( elem, myShapeID );
787
788   return elem;
789 }
790
791 //=======================================================================
792 /*!
793  * Creates quadratic or linear quadrangle
794  */
795 //=======================================================================
796
797 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
798                                            const SMDS_MeshNode* n2,
799                                            const SMDS_MeshNode* n3,
800                                            const SMDS_MeshNode* n4,
801                                            const int id,
802                                            const bool force3d)
803 {
804   SMESHDS_Mesh * meshDS = GetMeshDS();
805   SMDS_MeshFace* elem = 0;
806
807   if( n1==n2 ) {
808     return AddFace(n1,n3,n4,id,force3d);
809   }
810   if( n1==n3 ) {
811     return AddFace(n1,n2,n4,id,force3d);
812   }
813   if( n1==n4 ) {
814     return AddFace(n1,n2,n3,id,force3d);
815   }
816   if( n2==n3 ) {
817     return AddFace(n1,n2,n4,id,force3d);
818   }
819   if( n2==n4 ) {
820     return AddFace(n1,n2,n3,id,force3d);
821   }
822   if( n3==n4 ) {
823     return AddFace(n1,n2,n3,id,force3d);
824   }
825
826   if(!myCreateQuadratic) {
827     if(id)
828       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
829     else
830       elem = meshDS->AddFace(n1, n2, n3, n4);
831   }
832   else {
833     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
834     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
835     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
836     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
837
838     if(id)
839       elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
840     else
841       elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
842   }
843   if ( mySetElemOnShape && myShapeID > 0 )
844     meshDS->SetMeshElementOnShape( elem, myShapeID );
845
846   return elem;
847 }
848
849 //=======================================================================
850 /*!
851  * Creates quadratic or linear volume
852  */
853 //=======================================================================
854
855 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
856                                                const SMDS_MeshNode* n2,
857                                                const SMDS_MeshNode* n3,
858                                                const SMDS_MeshNode* n4,
859                                                const SMDS_MeshNode* n5,
860                                                const SMDS_MeshNode* n6,
861                                                const int id,
862                                                const bool force3d)
863 {
864   SMESHDS_Mesh * meshDS = GetMeshDS();
865   SMDS_MeshVolume* elem = 0;
866   if(!myCreateQuadratic) {
867     if(id)
868       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
869     else
870       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
871   }
872   else {
873     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
874     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
875     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
876
877     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
878     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
879     const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
880
881     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
882     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
883     const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
884
885     if(id)
886       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, 
887                                      n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
888     else
889       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
890                                n12, n23, n31, n45, n56, n64, n14, n25, n36);
891   }
892   if ( mySetElemOnShape && myShapeID > 0 )
893     meshDS->SetMeshElementOnShape( elem, myShapeID );
894
895   return elem;
896 }
897
898 //=======================================================================
899 /*!
900  * Creates quadratic or linear volume
901  */
902 //=======================================================================
903
904 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
905                                                const SMDS_MeshNode* n2,
906                                                const SMDS_MeshNode* n3,
907                                                const SMDS_MeshNode* n4,
908                                                const int id, 
909                                                const bool force3d)
910 {
911   SMESHDS_Mesh * meshDS = GetMeshDS();
912   SMDS_MeshVolume* elem = 0;
913   if(!myCreateQuadratic) {
914     if(id)
915       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
916     else
917       elem = meshDS->AddVolume(n1, n2, n3, n4);
918   }
919   else {
920     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
921     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
922     const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
923
924     const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
925     const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
926     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
927
928     if(id)
929       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
930     else
931       elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
932   }
933   if ( mySetElemOnShape && myShapeID > 0 )
934     meshDS->SetMeshElementOnShape( elem, myShapeID );
935
936   return elem;
937 }
938
939 //=======================================================================
940 /*!
941  * Creates quadratic or linear pyramid
942  */
943 //=======================================================================
944
945 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
946                                                const SMDS_MeshNode* n2,
947                                                const SMDS_MeshNode* n3,
948                                                const SMDS_MeshNode* n4,
949                                                const SMDS_MeshNode* n5,
950                                                const int id, 
951                                                const bool force3d)
952 {
953   SMDS_MeshVolume* elem = 0;
954   if(!myCreateQuadratic) {
955     if(id)
956       elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
957     else
958       elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
959   }
960   else {
961     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
962     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
963     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
964     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
965
966     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
967     const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
968     const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
969     const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
970
971     if(id)
972       elem = GetMeshDS()->AddVolumeWithID ( n1,  n2,  n3,  n4,  n5,
973                                             n12, n23, n34, n41,
974                                             n15, n25, n35, n45,
975                                             id);
976     else
977       elem = GetMeshDS()->AddVolume( n1,  n2,  n3,  n4,  n5,
978                                      n12, n23, n34, n41,
979                                      n15, n25, n35, n45);
980   }
981   if ( mySetElemOnShape && myShapeID > 0 )
982     GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
983
984   return elem;
985 }
986
987 //=======================================================================
988 /*!
989  * Creates quadratic or linear hexahedron
990  */
991 //=======================================================================
992
993 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
994                                                const SMDS_MeshNode* n2,
995                                                const SMDS_MeshNode* n3,
996                                                const SMDS_MeshNode* n4,
997                                                const SMDS_MeshNode* n5,
998                                                const SMDS_MeshNode* n6,
999                                                const SMDS_MeshNode* n7,
1000                                                const SMDS_MeshNode* n8,
1001                                                const int id,
1002                                                const bool force3d)
1003 {
1004   SMESHDS_Mesh * meshDS = GetMeshDS();
1005   SMDS_MeshVolume* elem = 0;
1006   if(!myCreateQuadratic) {
1007     if(id)
1008       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1009     else
1010       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1011   }
1012   else {
1013     const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1014     const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1015     const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1016     const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1017
1018     const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1019     const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1020     const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1021     const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1022
1023     const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1024     const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1025     const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1026     const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1027
1028     if(id)
1029       elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1030                                      n12, n23, n34, n41, n56, n67,
1031                                      n78, n85, n15, n26, n37, n48, id);
1032     else
1033       elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1034                                n12, n23, n34, n41, n56, n67,
1035                                n78, n85, n15, n26, n37, n48);
1036   }
1037   if ( mySetElemOnShape && myShapeID > 0 )
1038     meshDS->SetMeshElementOnShape( elem, myShapeID );
1039
1040   return elem;
1041 }
1042
1043 //=======================================================================
1044 /*!
1045  * \brief Load nodes bound to face into a map of node columns
1046  * \param theParam2ColumnMap - map of node columns to fill
1047  * \param theFace - the face on which nodes are searched for
1048  * \param theBaseEdge - the edge nodes of which are columns' bases
1049  * \param theMesh - the mesh containing nodes
1050  * \retval bool - false if something is wrong
1051  * 
1052  * The key of the map is a normalized parameter of each
1053  * base node on theBaseEdge.
1054  * This method works in supposition that nodes on the face
1055  * forms a rectangular grid and elements can be quardrangles or triangles
1056  */
1057 //=======================================================================
1058
1059 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1060                                          const TopoDS_Face& theFace,
1061                                          const TopoDS_Edge& theBaseEdge,
1062                                          SMESHDS_Mesh*      theMesh)
1063 {
1064   // get vertices of theBaseEdge
1065   TopoDS_Vertex vfb, vlb, vft; // first and last, bottom and top vertices
1066   TopoDS_Edge eFrw = TopoDS::Edge( theBaseEdge.Oriented( TopAbs_FORWARD ));
1067   TopExp::Vertices( eFrw, vfb, vlb );
1068
1069   // find the other edges of theFace and orientation of e1
1070   TopoDS_Edge e1, e2, eTop;
1071   bool rev1, CumOri = false;
1072   TopExp_Explorer exp( theFace, TopAbs_EDGE );
1073   int nbEdges = 0;
1074   for ( ; exp.More(); exp.Next() ) {
1075     if ( ++nbEdges > 4 ) {
1076       return false; // more than 4 edges in theFace
1077     }
1078     TopoDS_Edge e = TopoDS::Edge( exp.Current() );
1079     if ( theBaseEdge.IsSame( e ))
1080       continue;
1081     TopoDS_Vertex vCommon;
1082     if ( !TopExp::CommonVertex( theBaseEdge, e, vCommon ))
1083       eTop = e;
1084     else if ( vCommon.IsSame( vfb )) {
1085       e1 = e;
1086       vft = TopExp::LastVertex( e1, CumOri );
1087       rev1 = vfb.IsSame( vft );
1088       if ( rev1 )
1089         vft = TopExp::FirstVertex( e1, CumOri );
1090     }
1091     else
1092       e2 = e;
1093   }
1094   if ( nbEdges < 4 ) {
1095     return false; // less than 4 edges in theFace
1096   }
1097   if ( e2.IsNull() && vfb.IsSame( vlb ))
1098     e2 = e1;
1099
1100   // submeshes corresponding to shapes
1101   SMESHDS_SubMesh* smFace = theMesh->MeshElements( theFace );
1102   SMESHDS_SubMesh* smb = theMesh->MeshElements( theBaseEdge );
1103   SMESHDS_SubMesh* smt = theMesh->MeshElements( eTop );
1104   SMESHDS_SubMesh* sm1 = theMesh->MeshElements( e1 );
1105   SMESHDS_SubMesh* sm2 = theMesh->MeshElements( e2 );
1106   SMESHDS_SubMesh* smVfb = theMesh->MeshElements( vfb );
1107   SMESHDS_SubMesh* smVlb = theMesh->MeshElements( vlb );
1108   SMESHDS_SubMesh* smVft = theMesh->MeshElements( vft );
1109   if (!smFace || !smb || !smt || !sm1 || !sm2 || !smVfb || !smVlb || !smVft ) {
1110     RETURN_BAD_RESULT( "NULL submesh " <<smFace<<" "<<smb<<" "<<smt<<" "<<
1111                        sm1<<" "<<sm2<<" "<<smVfb<<" "<<smVlb<<" "<<smVft);
1112   }
1113   if ( smb->NbNodes() != smt->NbNodes() || sm1->NbNodes() != sm2->NbNodes() ) {
1114     RETURN_BAD_RESULT(" Diff nb of nodes on opposite edges" );
1115   }
1116   if (smVfb->NbNodes() != 1 || smVlb->NbNodes() != 1 || smVft->NbNodes() != 1) {
1117     RETURN_BAD_RESULT("Empty submesh of vertex");
1118   }
1119   // define whether mesh is quadratic
1120   bool isQuadraticMesh = false;
1121   SMDS_ElemIteratorPtr eIt = smFace->GetElements();
1122   if ( !eIt->more() ) {
1123     RETURN_BAD_RESULT("No elements on the face");
1124   }
1125   const SMDS_MeshElement* e = eIt->next();
1126   isQuadraticMesh = e->IsQuadratic();
1127   
1128   if ( sm1->NbNodes() * smb->NbNodes() != smFace->NbNodes() ) {
1129     // check quadratic case
1130     if ( isQuadraticMesh ) {
1131       // what if there are quadrangles and triangles mixed?
1132 //       int n1 = sm1->NbNodes()/2;
1133 //       int n2 = smb->NbNodes()/2;
1134 //       int n3 = sm1->NbNodes() - n1;
1135 //       int n4 = smb->NbNodes() - n2;
1136 //       int nf = sm1->NbNodes()*smb->NbNodes() - n3*n4;
1137 //       if( nf != smFace->NbNodes() ) {
1138 //         MESSAGE( "Wrong nb face nodes: " <<
1139 //                 sm1->NbNodes()<<" "<<smb->NbNodes()<<" "<<smFace->NbNodes());
1140 //         return false;
1141 //       }
1142     }
1143     else {
1144       RETURN_BAD_RESULT( "Wrong nb face nodes: " <<
1145                          sm1->NbNodes()<<" "<<smb->NbNodes()<<" "<<smFace->NbNodes());
1146     }
1147   }
1148   // IJ size
1149   int vsize = sm1->NbNodes() + 2;
1150   int hsize = smb->NbNodes() + 2;
1151   if(isQuadraticMesh) {
1152     vsize = vsize - sm1->NbNodes()/2 -1;
1153     hsize = hsize - smb->NbNodes()/2 -1;
1154   }
1155
1156   // load nodes from theBaseEdge
1157
1158   std::set<const SMDS_MeshNode*> loadedNodes;
1159   const SMDS_MeshNode* nullNode = 0;
1160
1161   std::vector<const SMDS_MeshNode*> & nVecf = theParam2ColumnMap[ 0.];
1162   nVecf.resize( vsize, nullNode );
1163   loadedNodes.insert( nVecf[ 0 ] = smVfb->GetNodes()->next() );
1164
1165   std::vector<const SMDS_MeshNode*> & nVecl = theParam2ColumnMap[ 1.];
1166   nVecl.resize( vsize, nullNode );
1167   loadedNodes.insert( nVecl[ 0 ] = smVlb->GetNodes()->next() );
1168
1169   double f, l;
1170   BRep_Tool::Range( eFrw, f, l );
1171   double range = l - f;
1172   SMDS_NodeIteratorPtr nIt = smb->GetNodes();
1173   const SMDS_MeshNode* node;
1174   while ( nIt->more() ) {
1175     node = nIt->next();
1176     if(IsMedium(node, SMDSAbs_Edge))
1177       continue;
1178     const SMDS_EdgePosition* pos =
1179       dynamic_cast<const SMDS_EdgePosition*>( node->GetPosition().get() );
1180     if ( !pos ) {
1181       return false;
1182     }
1183     double u = ( pos->GetUParameter() - f ) / range;
1184     std::vector<const SMDS_MeshNode*> & nVec = theParam2ColumnMap[ u ];
1185     nVec.resize( vsize, nullNode );
1186     loadedNodes.insert( nVec[ 0 ] = node );
1187   }
1188   if ( theParam2ColumnMap.size() != hsize ) {
1189     RETURN_BAD_RESULT( "Wrong node positions on theBaseEdge" );
1190   }
1191
1192   // load nodes from e1
1193
1194   std::map< double, const SMDS_MeshNode*> sortedNodes; // sort by param on edge
1195   nIt = sm1->GetNodes();
1196   while ( nIt->more() ) {
1197     node = nIt->next();
1198     if(IsMedium(node))
1199       continue;
1200     const SMDS_EdgePosition* pos =
1201       dynamic_cast<const SMDS_EdgePosition*>( node->GetPosition().get() );
1202     if ( !pos ) {
1203       return false;
1204     }
1205     sortedNodes.insert( std::make_pair( pos->GetUParameter(), node ));
1206   }
1207   loadedNodes.insert( nVecf[ vsize - 1 ] = smVft->GetNodes()->next() );
1208   std::map< double, const SMDS_MeshNode*>::iterator u_n = sortedNodes.begin();
1209   int row  = rev1 ? vsize - 1 : 0;
1210   int dRow = rev1 ? -1 : +1;
1211   for ( ; u_n != sortedNodes.end(); u_n++ ) {
1212     row += dRow;
1213     loadedNodes.insert( nVecf[ row ] = u_n->second );
1214   }
1215
1216   // try to load the rest nodes
1217
1218   // get all faces from theFace
1219   TIDSortedElemSet allFaces, foundFaces;
1220   eIt = smFace->GetElements();
1221   while ( eIt->more() ) {
1222     const SMDS_MeshElement* e = eIt->next();
1223     if ( e->GetType() == SMDSAbs_Face )
1224       allFaces.insert( e );
1225   }
1226   // Starting from 2 neighbour nodes on theBaseEdge, look for a face
1227   // the nodes belong to, and between the nodes of the found face,
1228   // look for a not loaded node considering this node to be the next
1229   // in a column of the starting second node. Repeat, starting
1230   // from nodes next to the previous starting nodes in their columns,
1231   // and so on while a face can be found. Then go the the next pair
1232   // of nodes on theBaseEdge.
1233   TParam2ColumnMap::iterator par_nVec_1 = theParam2ColumnMap.begin();
1234   TParam2ColumnMap::iterator par_nVec_2 = par_nVec_1;
1235   // loop on columns
1236   int col = 0;
1237   for ( par_nVec_2++; par_nVec_2 != theParam2ColumnMap.end(); par_nVec_1++, par_nVec_2++ ) {
1238     col++;
1239     row = 0;
1240     const SMDS_MeshNode* n1 = par_nVec_1->second[ row ];
1241     const SMDS_MeshNode* n2 = par_nVec_2->second[ row ];
1242     const SMDS_MeshElement* face = 0;
1243     bool lastColOnClosedFace = ( nVecf[ row ] == n2 );
1244     do {
1245       // look for a face by 2 nodes
1246       face = SMESH_MeshEditor::FindFaceInSet( n1, n2, allFaces, foundFaces );
1247       if ( face ) {
1248         int nbFaceNodes = face->NbNodes();
1249         if ( face->IsQuadratic() )
1250           nbFaceNodes /= 2;
1251         if ( nbFaceNodes>4 ) {
1252           RETURN_BAD_RESULT(" Too many nodes in a face: " << nbFaceNodes );
1253         }
1254         // look for a not loaded node of the <face>
1255         bool found = false;
1256         const SMDS_MeshNode* n3 = 0; // a node defferent from n1 and n2
1257         for ( int i = 0; i < nbFaceNodes && !found; ++i ) {
1258           node = face->GetNode( i );
1259           found = loadedNodes.insert( node ).second;
1260           if ( !found && node != n1 && node != n2 )
1261             n3 = node;
1262         }
1263         if ( lastColOnClosedFace && row + 1 < vsize ) {
1264           node = nVecf[ row + 1 ];
1265           found = ( face->GetNodeIndex( node ) >= 0 );
1266         }
1267         if ( found ) {
1268           if ( ++row > vsize - 1 ) {
1269             RETURN_BAD_RESULT( "Too many nodes in column "<< col <<": "<< row+1);
1270           }
1271           par_nVec_2->second[ row ] = node;
1272           foundFaces.insert( face );
1273           n2 = node;
1274           if ( nbFaceNodes==4 ) {
1275             n1 = par_nVec_1->second[ row ];
1276           }
1277         }
1278         else if ( nbFaceNodes==3 && n3 == par_nVec_1->second[ row + 1 ] ) {
1279           n1 = n3;
1280         }
1281         else  {
1282           RETURN_BAD_RESULT( "Not quad mesh, column "<< col );
1283         }
1284       }
1285     }
1286     while ( face && n1 && n2 );
1287
1288     if ( row < vsize - 1 ) {
1289       MESSAGE( "Too few nodes in column "<< col <<": "<< row+1);
1290       MESSAGE( "Base node 1: "<< par_nVec_1->second[0]);
1291       MESSAGE( "Base node 2: "<< par_nVec_2->second[0]);
1292       if ( n1 ) { MESSAGE( "Current node 1: "<< n1); }
1293       else      { MESSAGE( "Current node 1: NULL");  }
1294       if ( n2 ) { MESSAGE( "Current node 2: "<< n2); }
1295       else      { MESSAGE( "Current node 2: NULL");  }
1296       MESSAGE( "first base node: "<< theParam2ColumnMap.begin()->second[0]);
1297       MESSAGE( "last base node: "<< theParam2ColumnMap.rbegin()->second[0]);
1298       return false;
1299     }
1300   } // loop on columns
1301
1302   return true;
1303 }
1304
1305 //=======================================================================
1306 /*!
1307  * \brief Return number of unique ancestors of the shape
1308  */
1309 //=======================================================================
1310
1311 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1312                                     const SMESH_Mesh&   mesh,
1313                                     TopAbs_ShapeEnum    ancestorType/*=TopAbs_SHAPE*/)
1314 {
1315   TopTools_MapOfShape ancestors;
1316   TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1317   for ( ; ansIt.More(); ansIt.Next() ) {
1318     if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1319       ancestors.Add( ansIt.Value() );
1320   }
1321   return ancestors.Extent();
1322 }
1323
1324 //=======================================================================
1325 /**
1326  * Check mesh without geometry for: if all elements on this shape are quadratic,
1327  * quadratic elements will be created.
1328  * Used then generated 3D mesh without geometry.
1329  */
1330 //=======================================================================
1331
1332 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
1333 {
1334   int NbAllEdgsAndFaces=0;
1335   int NbQuadFacesAndEdgs=0;
1336   int NbFacesAndEdges=0;
1337   //All faces and edges
1338   NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
1339   
1340   //Quadratic faces and edges
1341   NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
1342
1343   //Linear faces and edges
1344   NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
1345   
1346   if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
1347     //Quadratic mesh
1348     return SMESH_MesherHelper::QUADRATIC;
1349   }
1350   else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
1351     //Linear mesh
1352     return SMESH_MesherHelper::LINEAR;
1353   }
1354   else
1355     //Mesh with both type of elements
1356     return SMESH_MesherHelper::COMP;
1357 }
1358
1359 //=======================================================================
1360 /*!
1361  * \brief Return an alternative parameter for a node on seam
1362  */
1363 //=======================================================================
1364
1365 double SMESH_MesherHelper::GetOtherParam(const double param) const
1366 {
1367   return fabs(param-myPar1) < fabs(param-myPar2) ? myPar2 : myPar1;
1368 }
1369
1370 //=======================================================================
1371 namespace { // Structures used by FixQuadraticElements()
1372 //=======================================================================
1373
1374 #define __DMP__(txt) \
1375 //cout << txt
1376 #define MSG(txt) __DMP__(txt<<endl)
1377 #define MSGBEG(txt) __DMP__(txt)
1378
1379   const double straightTol2 = 1e-33; // to detect straing links
1380
1381   struct QFace;
1382   // ---------------------------------------
1383   /*!
1384    * \brief Quadratic link knowing its faces
1385    */
1386   struct QLink: public SMESH_TLink
1387   {
1388     const SMDS_MeshNode*          _mediumNode;
1389     mutable vector<const QFace* > _faces;
1390     mutable gp_Vec                _nodeMove;
1391     mutable int                   _nbMoves;
1392
1393     QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
1394       SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
1395       _faces.reserve(4);
1396       //if ( MediumPos() != SMDS_TOP_3DSPACE )
1397         _nodeMove = MediumPnt() - MiddlePnt();
1398     }
1399     void SetContinuesFaces() const;
1400     const QFace* GetContinuesFace( const QFace* face ) const;
1401     bool OnBoundary() const;
1402     gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
1403     gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
1404
1405     SMDS_TypeOfPosition MediumPos() const
1406     { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
1407     SMDS_TypeOfPosition EndPos(bool isSecond) const
1408     { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
1409     const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
1410     { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
1411
1412     void Move(const gp_Vec& move, bool sum=false) const
1413     { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
1414     gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
1415     bool IsMoved() const { return (_nbMoves > 0 && !IsStraight()); }
1416     bool IsStraight() const { return _nodeMove.SquareMagnitude() <= straightTol2; }
1417
1418     bool operator<(const QLink& other) const {
1419       return (node1()->GetID() == other.node1()->GetID() ?
1420               node2()->GetID() < other.node2()->GetID() :
1421               node1()->GetID() < other.node1()->GetID());
1422     }
1423     struct PtrComparator {
1424       bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
1425     };
1426   };
1427   // ---------------------------------------------------------
1428   /*!
1429    * \brief Link in the chain of links; it connects two faces
1430    */
1431   struct TChainLink
1432   {
1433     const QLink*         _qlink;
1434     mutable const QFace* _qfaces[2];
1435
1436     TChainLink(const QLink* qlink=0):_qlink(qlink) {
1437       _qfaces[0] = _qfaces[1] = 0;
1438     }
1439     void SetFace(const QFace* face) { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
1440
1441     bool IsBoundary() const { return !_qfaces[1]; }
1442
1443     void RemoveFace( const QFace* face ) const
1444     { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
1445
1446     const QFace* NextFace( const QFace* f ) const
1447     { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
1448
1449     const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
1450     { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
1451
1452     bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
1453
1454     operator bool() const { return (_qlink); }
1455
1456     const QLink* operator->() const { return _qlink; }
1457
1458     gp_Vec Normal() const;
1459   };
1460   // --------------------------------------------------------------------
1461   typedef list< TChainLink > TChain;
1462   typedef set < TChainLink > TLinkSet;
1463   typedef TLinkSet::const_iterator TLinkInSet;
1464
1465   const int theFirstStep = 5;
1466
1467   enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
1468   // --------------------------------------------------------------------
1469   /*!
1470    * \brief Face shared by two volumes and bound by QLinks
1471    */
1472   struct QFace: public TIDSortedElemSet
1473   {
1474     mutable const SMDS_MeshElement* _volumes[2];
1475     mutable vector< const QLink* >  _sides;
1476     mutable bool                    _sideIsAdded[4]; // added in chain of links
1477     gp_Vec                          _normal;
1478
1479     QFace( const vector< const QLink*>& links );
1480
1481     void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
1482
1483     int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
1484
1485     void AddSelfToLinks() const {
1486       for ( int i = 0; i < _sides.size(); ++i )
1487         _sides[i]->_faces.push_back( this );
1488     }
1489     int LinkIndex( const QLink* side ) const {
1490       for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
1491       return -1;
1492     }
1493     bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const;
1494
1495     bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
1496     {
1497       int i = LinkIndex( link._qlink );
1498       if ( i < 0 ) return true;
1499       _sideIsAdded[i] = true;
1500       link.SetFace( this );
1501       // continue from opposite link
1502       return GetLinkChain( (i+2)%_sides.size(), chain, pos, error );
1503     }
1504     bool IsBoundary() const { return !_volumes[1]; }
1505
1506     bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
1507
1508     TLinkInSet GetBoundaryLink( const TLinkSet&      links,
1509                                 const TChainLink&    avoidLink,
1510                                 TLinkInSet *         notBoundaryLink = 0,
1511                                 const SMDS_MeshNode* nodeToContain = 0,
1512                                 bool *               isAdjacentUsed = 0) const;
1513
1514     TLinkInSet GetLinkByNode( const TLinkSet&      links,
1515                               const TChainLink&    avoidLink,
1516                               const SMDS_MeshNode* nodeToContain) const;
1517
1518     const SMDS_MeshNode* GetNodeInFace() const {
1519       for ( int iL = 0; iL < _sides.size(); ++iL )
1520         if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
1521       return 0;
1522     }
1523
1524     gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
1525
1526     double MoveByBoundary( const TChainLink&   theLink,
1527                            const gp_Vec&       theRefVec,
1528                            const TLinkSet&     theLinks,
1529                            SMESH_MesherHelper* theFaceHelper=0,
1530                            const double        thePrevLen=0,
1531                            const int           theStep=theFirstStep,
1532                            gp_Vec*             theLinkNorm=0,
1533                            double              theSign=1.0) const;
1534   };
1535
1536   //================================================================================
1537   /*!
1538    * \brief Dump QLink and QFace
1539    */
1540   ostream& operator << (ostream& out, const QLink& l)
1541   {
1542     out <<"QLink nodes: "
1543         << l.node1()->GetID() << " - "
1544         << l._mediumNode->GetID() << " - "
1545         << l.node2()->GetID() << endl;
1546     return out;
1547   }
1548   ostream& operator << (ostream& out, const QFace& f)
1549   {
1550     out <<"QFace nodes: "/*<< &f << "  "*/;
1551     for ( TIDSortedElemSet::const_iterator n = f.begin(); n != f.end(); ++n )
1552       out << (*n)->GetID() << " ";
1553     out << " \tvolumes: "
1554         << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
1555         << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
1556     out << "  \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
1557     return out;
1558   }
1559
1560   //================================================================================
1561   /*!
1562    * \brief Construct QFace from QLinks 
1563    */
1564   //================================================================================
1565
1566   QFace::QFace( const vector< const QLink*>& links )
1567   {
1568     _volumes[0] = _volumes[1] = 0;
1569     _sides = links;
1570     _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
1571     _normal.SetCoord(0,0,0);
1572     for ( int i = 1; i < _sides.size(); ++i ) {
1573       const QLink *l1 = _sides[i-1], *l2 = _sides[i];
1574       insert( l1->node1() ); insert( l1->node2() );
1575       // compute normal
1576       gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
1577       gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
1578       if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
1579         v1.Reverse(); 
1580       _normal += v1 ^ v2;
1581     }
1582     double normSqSize = _normal.SquareMagnitude();
1583     if ( normSqSize > numeric_limits<double>::min() )
1584       _normal /= sqrt( normSqSize );
1585     else
1586       _normal.SetCoord(1e-33,0,0);
1587   }
1588   //================================================================================
1589   /*!
1590    * \brief Make up chain of links
1591    *  \param iSide - link to add first
1592    *  \param chain - chain to fill in
1593    *  \param pos   - postion of medium nodes the links should have
1594    *  \param error - out, specifies what is wrong
1595    *  \retval bool - false if valid chain can't be built; "valid" means that links
1596    *                 of the chain belongs to rectangles bounding hexahedrons
1597    */
1598   //================================================================================
1599
1600   bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
1601   {
1602     if ( iSide >= _sides.size() ) // wrong argument iSide
1603       return false;
1604     if ( _sideIsAdded[ iSide ]) // already in chain
1605       return true;
1606
1607     if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
1608       MSGBEG( *this );
1609       for ( int i = 0; i < _sides.size(); ++i ) {
1610         if ( !_sideIsAdded[i] && _sides[i] ) {
1611           _sideIsAdded[i]=true;
1612           TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(_sides[i]));
1613           chLink->SetFace( this );
1614           if ( _sides[i]->MediumPos() >= pos )
1615             if ( const QFace* f = _sides[i]->GetContinuesFace( this ))
1616               f->GetLinkChain( *chLink, chain, pos, error );
1617         }
1618       }
1619       if ( error < ERR_TRI )
1620         error = ERR_TRI;
1621       return false;
1622     }
1623     _sideIsAdded[iSide] = true; // not to add this link to chain again
1624     const QLink* link = _sides[iSide];
1625     if ( !link)
1626       return true;
1627
1628     // add link into chain
1629     TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
1630     chLink->SetFace( this );
1631     MSGBEG( *this );
1632
1633     // propagate from rectangle to neighbour faces
1634     if ( link->MediumPos() >= pos ) {
1635       int nbLinkFaces = link->_faces.size();
1636       if ( nbLinkFaces == 4 || nbLinkFaces < 4 && link->OnBoundary()) {
1637         // hexahedral mesh or boundary quadrangles - goto a continous face
1638         if ( const QFace* f = link->GetContinuesFace( this ))
1639           return f->GetLinkChain( *chLink, chain, pos, error );
1640       }
1641       else {
1642         TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
1643         for ( int i = 0; i < nbLinkFaces; ++i )
1644           if ( link->_faces[i] )
1645             link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
1646         if ( error < ERR_PRISM )
1647           error = ERR_PRISM;
1648         return false;
1649       }
1650     }
1651     return true;
1652   }
1653
1654   //================================================================================
1655   /*!
1656    * \brief Return a boundary link of the triangle face
1657    *  \param links - set of all links
1658    *  \param avoidLink - link not to return
1659    *  \param notBoundaryLink - out, neither the returned link nor avoidLink
1660    *  \param nodeToContain - node the returned link must contain; if provided, search
1661    *                         also performed on adjacent faces
1662    *  \param isAdjacentUsed - returns true if link is found in adjacent faces
1663    */
1664   //================================================================================
1665
1666   TLinkInSet QFace::GetBoundaryLink( const TLinkSet&      links,
1667                                      const TChainLink&    avoidLink,
1668                                      TLinkInSet *         notBoundaryLink,
1669                                      const SMDS_MeshNode* nodeToContain,
1670                                      bool *               isAdjacentUsed) const
1671   {
1672     TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
1673
1674     typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
1675     TFaceLinkList adjacentFaces;
1676
1677     for ( int iL = 0; iL < _sides.size(); ++iL )
1678     {
1679       if ( avoidLink._qlink == _sides[iL] )
1680         continue;
1681       TLinkInSet link = links.find( _sides[iL] );
1682       if ( link == linksEnd ) continue;
1683
1684       // check link
1685       if ( link->IsBoundary() ) {
1686         if ( !nodeToContain ||
1687              (*link)->node1() == nodeToContain ||
1688              (*link)->node2() == nodeToContain )
1689         {
1690           boundaryLink = link;
1691           if ( !notBoundaryLink ) break;
1692         }
1693       }
1694       else if ( notBoundaryLink ) {
1695         *notBoundaryLink = link;
1696         if ( boundaryLink != linksEnd ) break;
1697       }
1698
1699       if ( boundaryLink == linksEnd && nodeToContain ) // cellect adjacent faces
1700         if ( const QFace* adj = link->NextFace( this ))
1701           if ( adj->Contains( nodeToContain ))
1702             adjacentFaces.push_back( make_pair( adj, link ));
1703     }
1704
1705     if ( isAdjacentUsed ) *isAdjacentUsed = false;
1706     if ( boundaryLink == linksEnd && nodeToContain ) // check adjacent faces
1707     {
1708       TFaceLinkList::iterator adj = adjacentFaces.begin();
1709       for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
1710         boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second),
1711                                                     0, nodeToContain, isAdjacentUsed);
1712       if ( isAdjacentUsed ) *isAdjacentUsed = true;
1713     }
1714     return boundaryLink;
1715   }
1716   //================================================================================
1717   /*!
1718    * \brief Return a link ending at the given node but not avoidLink
1719    */
1720   //================================================================================
1721
1722   TLinkInSet QFace::GetLinkByNode( const TLinkSet&      links,
1723                                    const TChainLink&    avoidLink,
1724                                    const SMDS_MeshNode* nodeToContain) const
1725   {
1726     for ( int i = 0; i < _sides.size(); ++i )
1727       if ( avoidLink._qlink != _sides[i] &&
1728            (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
1729         return links.find( _sides[ i ]);
1730     return links.end();
1731   }
1732
1733   //================================================================================
1734   /*!
1735    * \brief Return normal to the i-th side pointing outside the face
1736    */
1737   //================================================================================
1738
1739   gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
1740   {
1741     gp_Vec norm, vecOut;
1742 //     if ( uvHelper ) {
1743 //       TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
1744 //       const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
1745 //       gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
1746 //       gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
1747 //       norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
1748
1749 //       const QLink* otherLink = _sides[(i + 1) % _sides.size()];
1750 //       const SMDS_MeshNode* otherNode =
1751 //         otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
1752 //       gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
1753 //       vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
1754 //     }
1755 //     else {
1756       norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
1757       gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
1758                      XYZ( _sides[0]->node2() ) +
1759                      XYZ( _sides[1]->node1() )) / 3.;
1760       vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
1761       //}
1762     if ( norm * vecOut < 0 )
1763       norm.Reverse();
1764     double mag2 = norm.SquareMagnitude();
1765     if ( mag2 > numeric_limits<double>::min() )
1766       norm /= sqrt( mag2 );
1767     return norm;
1768   }
1769   //================================================================================
1770   /*!
1771    * \brief Move medium node of theLink according to its distance from boundary
1772    *  \param theLink - link to fix
1773    *  \param theRefVec - movement of boundary
1774    *  \param theLinks - all adjacent links of continous triangles
1775    *  \param theFaceHelper - helper is not used so far
1776    *  \param thePrevLen - distance from the boundary
1777    *  \param theStep - number of steps till movement propagation limit
1778    *  \param theLinkNorm - out normal to theLink
1779    *  \param theSign - 1 or -1 depending on movement of boundary
1780    *  \retval double - distance from boundary to propagation limit or other boundary
1781    */
1782   //================================================================================
1783
1784   double QFace::MoveByBoundary( const TChainLink&   theLink,
1785                                 const gp_Vec&       theRefVec,
1786                                 const TLinkSet&     theLinks,
1787                                 SMESH_MesherHelper* theFaceHelper,
1788                                 const double        thePrevLen,
1789                                 const int           theStep,
1790                                 gp_Vec*             theLinkNorm,
1791                                 double              theSign) const
1792   {
1793     if ( !theStep )
1794       return thePrevLen; // propagation limit reached
1795
1796     int iL; // index of theLink
1797     for ( iL = 0; iL < _sides.size(); ++iL )
1798       if ( theLink._qlink == _sides[ iL ])
1799         break;
1800
1801     MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
1802         <<" thePrevLen " << thePrevLen);
1803     MSG(string(theStep,'.')<<" "<<*theLink._qlink);
1804
1805     gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
1806     double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
1807     if ( theStep == theFirstStep )
1808       theSign = refProj < 0. ? -1. : 1.;
1809     else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
1810       return thePrevLen; // to propagate movement forward only, not in side dir or backward
1811
1812     int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
1813     TLinkInSet link1 = theLinks.find( _sides[iL1] );
1814     TLinkInSet link2 = theLinks.find( _sides[iL2] );
1815     const QFace* f1 = link1->NextFace( this ); // adjacent faces
1816     const QFace* f2 = link2->NextFace( this );
1817
1818     // propagate to adjacent faces till limit step or boundary
1819     double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
1820     double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
1821     gp_Vec linkDir1, linkDir2;
1822     try {
1823       OCC_CATCH_SIGNALS;
1824       if ( f1 )
1825         len1 = f1->MoveByBoundary
1826           ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
1827       else
1828         linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
1829     } catch (...) {
1830       MSG( " --------------- EXCEPTION");
1831       return thePrevLen;
1832     }
1833     try {
1834       OCC_CATCH_SIGNALS;
1835       if ( f2 )
1836         len2 = f2->MoveByBoundary
1837           ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
1838       else
1839         linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
1840     } catch (...) {
1841       MSG( " --------------- EXCEPTION");
1842       return thePrevLen;
1843     }
1844
1845     double fullLen = 0;
1846     if ( theStep != theFirstStep )
1847     {
1848       // choose chain length by direction of propagation most codirected with theRefVec
1849       bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
1850       fullLen = choose1 ? len1 : len2;
1851       double r = thePrevLen / fullLen;
1852
1853       gp_Vec move = linkNorm * refProj * ( 1 - r );
1854       theLink->Move( move, true );
1855
1856       MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
1857           " by " << refProj * ( 1 - r ) << " following " <<
1858           (choose1 ? *link1->_qlink : *link2->_qlink));
1859
1860       if ( theLinkNorm ) *theLinkNorm = linkNorm;
1861     }
1862     return fullLen;
1863   }
1864
1865   //================================================================================
1866   /*!
1867    * \brief Find pairs of continues faces 
1868    */
1869   //================================================================================
1870
1871   void QLink::SetContinuesFaces() const
1872   {
1873     //       x0         x - QLink, [-|] - QFace, v - volume
1874     //   v0  |   v1   
1875     //       |          Between _faces of link x2 two vertical faces are continues
1876     // x1----x2-----x3  and two horizontal faces are continues. We set vertical faces
1877     //       |          to _faces[0] and _faces[1] and horizontal faces to
1878     //   v2  |   v3     _faces[2] and _faces[3] (or vise versa).
1879     //       x4
1880
1881     if ( _faces.empty() )
1882       return;
1883     int iFaceCont = -1;
1884     for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
1885     {
1886       // look for a face bounding none of volumes bound by _faces[0]
1887       bool sameVol = false;
1888       int nbVol = _faces[iF]->NbVolumes();
1889       for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
1890         sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
1891                     _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
1892       if ( !sameVol )
1893         iFaceCont = iF;
1894     }
1895     if ( iFaceCont > 0 ) // continues faces found, set one by the other
1896     {
1897       if ( iFaceCont != 1 )
1898         std::swap( _faces[1], _faces[iFaceCont] );
1899     }
1900     else if ( _faces.size() > 1 ) // not found, set NULL by the first face
1901     {
1902       _faces.insert( ++_faces.begin(), 0 );
1903     }
1904   }
1905   //================================================================================
1906   /*!
1907    * \brief Return a face continues to the given one
1908    */
1909   //================================================================================
1910
1911   const QFace* QLink::GetContinuesFace( const QFace* face ) const
1912   {
1913     for ( int i = 0; i < _faces.size(); ++i ) {
1914       if ( _faces[i] == face ) {
1915         int iF = i < 2 ? 1-i : 5-i;
1916         return iF < _faces.size() ? _faces[iF] : 0;
1917       }
1918     }
1919     return 0;
1920   }
1921   //================================================================================
1922   /*!
1923    * \brief True if link is on mesh boundary
1924    */
1925   //================================================================================
1926
1927   bool QLink::OnBoundary() const
1928   {
1929     for ( int i = 0; i < _faces.size(); ++i )
1930       if (_faces[i] && _faces[i]->IsBoundary()) return true;
1931     return false;
1932   }
1933   //================================================================================
1934   /*!
1935    * \brief Return normal of link of the chain
1936    */
1937   //================================================================================
1938
1939   gp_Vec TChainLink::Normal() const {
1940     gp_Vec norm;
1941     if (_qfaces[0]) norm  = _qfaces[0]->_normal;
1942     if (_qfaces[1]) norm += _qfaces[1]->_normal;
1943     return norm;
1944   }
1945   //================================================================================
1946   /*!
1947    * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
1948    */
1949   //================================================================================
1950
1951   void fixPrism( TChain& allLinks )
1952   {
1953     // separate boundary links from internal ones
1954     typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
1955     QLinkSet interLinks, bndLinks1, bndLink2;
1956
1957     bool isCurved = false;
1958     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
1959       if ( (*lnk)->OnBoundary() )
1960         bndLinks1.insert( lnk->_qlink );
1961       else
1962         interLinks.insert( lnk->_qlink );
1963       isCurved = isCurved || !(*lnk)->IsStraight();
1964     }
1965     if ( !isCurved )
1966       return; // no need to move
1967
1968     QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
1969
1970     while ( !interLinks.empty() && !curBndLinks->empty() )
1971     {
1972       // propagate movement from boundary links to connected internal links
1973       QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
1974       for ( ; bnd != bndEnd; ++bnd )
1975       {
1976         const QLink* bndLink = *bnd;
1977         for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
1978         {
1979           const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
1980           if ( !face ) continue;
1981           // find and move internal link opposite to bndLink within the face
1982           int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
1983           const QLink* interLink = face->_sides[ interInd ];
1984           QLinkSet::iterator pInterLink = interLinks.find( interLink );
1985           if ( pInterLink == interLinks.end() ) continue; // not internal link
1986           interLink->Move( bndLink->_nodeMove );
1987           // treated internal links become new boundary ones
1988           interLinks. erase( pInterLink );
1989           newBndLinks->insert( interLink );
1990         }
1991       }
1992       curBndLinks->clear();
1993       std::swap( curBndLinks, newBndLinks );
1994     }
1995   }
1996
1997   //================================================================================
1998   /*!
1999    * \brief Fix links of continues triangles near curved boundary
2000    */
2001   //================================================================================
2002
2003   void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
2004   {
2005     if ( allLinks.empty() ) return;
2006
2007     TLinkSet linkSet( allLinks.begin(), allLinks.end());
2008     TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
2009
2010     // move in 2d if we are on geom face
2011 //     TopoDS_Face face;
2012 //     TopLoc_Location loc;
2013 //     SMESH_MesherHelper faceHelper( *helper.GetMesh());
2014 //     while ( linkIt->IsBoundary()) ++linkIt;
2015 //     if ( linkIt == linksEnd ) return;
2016 //     if ( (*linkIt)->MediumPos() == SMDS_TOP_FACE ) {
2017 //       bool checkPos = true;
2018 //       TopoDS_Shape f = helper.GetSubShapeByNode( (*linkIt)->_mediumNode, helper.GetMeshDS() );
2019 //       if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE ) {
2020 //         face = TopoDS::Face( f );
2021 //         helper.GetNodeUV( face, (*linkIt)->_mediumNode, 0, &checkPos);
2022 //         if (checkPos)
2023 //           face.Nullify();
2024 //         else
2025 //           faceHelper.SetSubShape( face );
2026 //       }
2027 //     }
2028     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
2029     {
2030       if ( linkIt->IsBoundary() && !(*linkIt)->IsStraight() && linkIt->_qfaces[0])
2031       {
2032 //         if ( !face.IsNull() ) {
2033 //           const SMDS_MeshNode* inFaceNode =
2034 //             faceHelper.GetNodeUVneedInFaceNode() ? linkIt->_qfaces[0]->GetNodeInFace() : 0;
2035 //           gp_XY uvm = helper.GetNodeUV( face, (*linkIt)->_mediumNode, inFaceNode );
2036 //           gp_XY uv1 = helper.GetNodeUV( face, (*linkIt)->node1(), inFaceNode);
2037 //           gp_XY uv2 = helper.GetNodeUV( face, (*linkIt)->node2(), inFaceNode);
2038 //           gp_XY uvMove = uvm - helper.GetMiddleUV( BRep_Tool::Surface(face,loc), uv1, uv2);
2039 //           gp_Vec move( uvMove.X(), uvMove.Y(), 0 );
2040 //           linkIt->_qfaces[0]->MoveByBoundary( *linkIt, move, linkSet, &faceHelper );
2041 //         }
2042 //         else {
2043           linkIt->_qfaces[0]->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
2044           //}
2045       }
2046     }
2047   }
2048
2049   //================================================================================
2050   /*!
2051    * \brief Detect rectangular structure of links and build chains from them
2052    */
2053   //================================================================================
2054
2055   enum TSplitTriaResult {
2056     _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
2057     _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK };
2058
2059   TSplitTriaResult splitTrianglesIntoChains( TChain &            allLinks,
2060                                              vector< TChain> &   resultChains,
2061                                              SMDS_TypeOfPosition pos )
2062   {
2063     // put links in the set and evalute number of result chains by number of boundary links
2064     TLinkSet linkSet;
2065     int nbBndLinks = 0;
2066     for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2067       linkSet.insert( *lnk );
2068       nbBndLinks += lnk->IsBoundary();
2069     }
2070     resultChains.clear();
2071     resultChains.reserve( nbBndLinks / 2 );
2072
2073     TLinkInSet linkIt, linksEnd = linkSet.end();
2074
2075     // find a boundary link with corner node; corner node has position pos-2
2076     // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2077     // links in volume
2078     SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2079     const SMDS_MeshNode* corner = 0;
2080     for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2081       if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2082         break;
2083     if ( !corner)
2084       return _NO_CORNERS;
2085
2086     TLinkInSet           startLink = linkIt;
2087     const SMDS_MeshNode* startCorner = corner;
2088     vector< TChain* >    rowChains;
2089     int iCol = 0;
2090
2091     while ( startLink != linksEnd) // loop on columns
2092     {
2093       // We suppose we have a rectangular structure like shown here. We have found a
2094       //               corner of the rectangle (startCorner) and a boundary link sharing  
2095       //    |/  |/  |  the startCorner (startLink). We are going to loop on rows of the   
2096       //  --o---o---o  structure making several chains at once. One chain (columnChain)   
2097       //    |\  |  /|  starts at startLink and continues upward (we look at the structure 
2098       //  \ | \ | / |  from such point that startLink is on the bottom of the structure). 
2099       //   \|  \|/  |  While going upward we also fill horizontal chains (rowChains) we   
2100       //  --o---o---o  encounter.                                                         
2101       //   /|\  |\  |
2102       //  / | \ | \ |  startCorner
2103       //    |  \|  \|,'
2104       //  --o---o---o
2105       //          `.startLink
2106
2107       if ( resultChains.size() == nbBndLinks / 2 )
2108         return _NOT_RECT;
2109       resultChains.push_back( TChain() );
2110       TChain& columnChain = resultChains.back();
2111
2112       TLinkInSet botLink = startLink; // current horizontal link to go up from
2113       corner = startCorner; // current corner the botLink ends at
2114       int iRow = 0;
2115       while ( botLink != linksEnd ) // loop on rows
2116       {
2117         // add botLink to the columnChain
2118         columnChain.push_back( *botLink );
2119
2120         const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2121         if ( !botTria )
2122         { // the column ends
2123           linkSet.erase( botLink );
2124           if ( iRow != rowChains.size() )
2125             return _FEW_ROWS; // different nb of rows in columns
2126           break;
2127         }
2128         // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2129         // link ending at <corner> (sideLink); there are two cases:
2130         // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2131         //   since midQuadLink is not at boundary while sideLink is.
2132         // 2) midQuadLink ends at <corner>
2133         bool isCase2;
2134         TLinkInSet midQuadLink = linksEnd;
2135         TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2136                                                         corner, &isCase2 );
2137         if ( isCase2 ) { // find midQuadLink among links of botTria
2138           midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
2139           if ( midQuadLink->IsBoundary() )
2140             return _BAD_MIDQUAD;
2141         }
2142         if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
2143           return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
2144
2145         // fill chains
2146         columnChain.push_back( *midQuadLink );
2147         if ( iRow >= rowChains.size() ) {
2148           if ( iCol > 0 )
2149             return _MANY_ROWS; // different nb of rows in columns
2150           if ( resultChains.size() == nbBndLinks / 2 )
2151             return _NOT_RECT;
2152           resultChains.push_back( TChain() );
2153           rowChains.push_back( & resultChains.back() );
2154         }
2155         rowChains[iRow]->push_back( *sideLink );
2156         rowChains[iRow]->push_back( *midQuadLink );
2157
2158         const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
2159         if ( !upTria)
2160           return _NO_UPTRIA;
2161         if ( iRow == 0 ) {
2162           // prepare startCorner and startLink for the next column
2163           startCorner = startLink->NextNode( startCorner );
2164           if (isCase2)
2165             startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
2166           else
2167             startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
2168           // check if no more columns remains
2169           if ( startLink != linksEnd ) {
2170             const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
2171             if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
2172               startLink = linksEnd; // startLink bounds upTria or botTria
2173             else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
2174               return _BAD_START;
2175           }
2176         }
2177         // find bottom link and corner for the next row
2178         corner = sideLink->NextNode( corner );
2179         // next bottom link ends at the new corner
2180         linkSet.erase( botLink );
2181         botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
2182         if ( botLink == linksEnd || botLink == (isCase2 ? midQuadLink : sideLink))
2183           return _NO_BOTLINK;
2184         linkSet.erase( midQuadLink );
2185         linkSet.erase( sideLink );
2186
2187         // make faces neighboring the found ones be boundary
2188         if ( startLink != linksEnd ) {
2189           const QFace* tria = isCase2 ? botTria : upTria;
2190           for ( int iL = 0; iL < 3; ++iL ) {
2191             linkIt = linkSet.find( tria->_sides[iL] );
2192             if ( linkIt != linksEnd )
2193               linkIt->RemoveFace( tria );
2194           }
2195         }
2196         if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
2197           botLink->RemoveFace( upTria ); // make next botTria first in vector
2198
2199         iRow++;
2200       } // loop on rows
2201
2202       iCol++;
2203     }
2204     // In the linkSet, there must remain the last links of rowChains; add them
2205     if ( linkSet.size() != rowChains.size() )
2206       return _BAD_SET_SIZE;
2207     for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
2208       // find the link (startLink) ending at startCorner
2209       corner = 0;
2210       for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
2211         if ( (*startLink)->node1() == startCorner ) {
2212           corner = (*startLink)->node2(); break;
2213         }
2214         else if ( (*startLink)->node2() == startCorner) {
2215           corner = (*startLink)->node1(); break;
2216         }
2217       }
2218       if ( startLink == linksEnd )
2219         return _BAD_CORNER;
2220       rowChains[ iRow ]->push_back( *startLink );
2221       linkSet.erase( startLink );
2222       startCorner = corner;
2223     }
2224
2225     return _OK;
2226   }
2227 }
2228
2229 //=======================================================================
2230 /*!
2231  * \brief Move medium nodes of faces and volumes to fix distorted elements
2232  * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
2233  * 
2234  * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
2235  */
2236 //=======================================================================
2237
2238 void SMESH_MesherHelper::FixQuadraticElements(bool volumeOnly)
2239 {
2240   // apply algorithm to solids or geom faces
2241   // ----------------------------------------------
2242   if ( myShape.IsNull() ) {
2243     if ( !myMesh->HasShapeToMesh() ) return;
2244     SetSubShape( myMesh->GetShapeToMesh() );
2245
2246     TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
2247     for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
2248       faces.Add( f.Current() );
2249     }
2250     for ( TopExp_Explorer v(myShape,TopAbs_SOLID); v.More(); v.Next() ) {
2251       if ( myMesh->GetSubMesh( v.Current() )->IsEmpty() ) { // get faces of solid
2252         for ( TopExp_Explorer f( v.Current(), TopAbs_FACE); f.More(); f.Next() )
2253           faces.Add( f.Current() );
2254       }
2255       else { // fix nodes in the solid and its faces
2256         SMESH_MesherHelper h(*myMesh);
2257         h.SetSubShape( v.Current() );
2258         h.FixQuadraticElements(false);
2259       }
2260     }
2261     // fix nodes on geom faces
2262     for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
2263       SMESH_MesherHelper h(*myMesh);
2264       h.SetSubShape( fIt.Key() );
2265       h.FixQuadraticElements();
2266     }
2267     return;
2268   }
2269
2270   // Find out type of elements and get iterator on them
2271   // ---------------------------------------------------
2272
2273   SMDS_ElemIteratorPtr elemIt;
2274   SMDSAbs_ElementType elemType = SMDSAbs_All;
2275
2276   SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
2277   if ( !submesh )
2278     return;
2279   if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
2280     elemIt = smDS->GetElements();
2281     if ( elemIt->more() ) {
2282       elemType = elemIt->next()->GetType();
2283       elemIt = smDS->GetElements();
2284     }
2285   }
2286   if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
2287     return;
2288
2289   // Fill in auxiliary data structures
2290   // ----------------------------------
2291
2292   set< QLink > links;
2293   set< QFace > faces;
2294   set< QLink >::iterator pLink;
2295   set< QFace >::iterator pFace;
2296
2297   bool isCurved = false;
2298   bool hasRectFaces = false;
2299   set<int> nbElemNodeSet;
2300
2301   if ( elemType == SMDSAbs_Volume )
2302   {
2303     SMDS_VolumeTool volTool;
2304     while ( elemIt->more() ) // loop on volumes
2305     {
2306       const SMDS_MeshElement* vol = elemIt->next();
2307       if ( !vol->IsQuadratic() || !volTool.Set( vol ))
2308         return; //continue;
2309       for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
2310       {
2311         int nbN = volTool.NbFaceNodes( iF );
2312         nbElemNodeSet.insert( nbN );
2313         const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
2314         vector< const QLink* > faceLinks( nbN/2 );
2315         for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
2316         {
2317           // store QLink
2318           QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
2319           pLink = links.insert( link ).first;
2320           faceLinks[ iN/2 ] = & *pLink;
2321           if ( !isCurved )
2322             isCurved = !link.IsStraight();
2323           if ( link.MediumPos() == SMDS_TOP_3DSPACE && !link.IsStraight() )
2324             return; // already fixed
2325         }
2326         // store QFace
2327         pFace = faces.insert( QFace( faceLinks )).first;
2328         if ( pFace->NbVolumes() == 0 )
2329           pFace->AddSelfToLinks();
2330         pFace->SetVolume( vol );
2331         hasRectFaces = hasRectFaces ||
2332           ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
2333             volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
2334       }
2335     }
2336     set< QLink >::iterator pLink = links.begin();
2337     for ( ; pLink != links.end(); ++pLink )
2338       pLink->SetContinuesFaces();
2339   }
2340   else
2341   {
2342     while ( elemIt->more() ) // loop on faces
2343     {
2344       const SMDS_MeshElement* face = elemIt->next();
2345       if ( !face->IsQuadratic() )
2346         continue;
2347       nbElemNodeSet.insert( face->NbNodes() );
2348       int nbN = face->NbNodes()/2;
2349       vector< const QLink* > faceLinks( nbN );
2350       for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
2351       {
2352         // store QLink
2353         QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
2354         pLink = links.insert( link ).first;
2355         faceLinks[ iN ] = & *pLink;
2356         if ( !isCurved )
2357           isCurved = !link.IsStraight();
2358       }
2359       // store QFace
2360       pFace = faces.insert( QFace( faceLinks )).first;
2361       pFace->AddSelfToLinks();
2362       hasRectFaces = ( hasRectFaces || nbN == 4 );
2363     }
2364   }
2365   if ( !isCurved )
2366     return; // no curved edges of faces
2367
2368   // Compute displacement of medium nodes
2369   // -------------------------------------
2370
2371   // two loops on faces: the first is to treat boundary links, the second is for internal ones
2372   TopLoc_Location loc;
2373   // not treat boundary of volumic submesh
2374   int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
2375   for ( ; isInside < 2; ++isInside ) {
2376     MSG( "--------------- LOOP " << isInside << " ------------------");
2377     SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
2378
2379     for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
2380       if ( bool(isInside) == pFace->IsBoundary() )
2381         continue;
2382       for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from quadrangle
2383       {
2384         MSG( "CHAIN");
2385         // make chain of links connected via continues faces
2386         int error = ERR_OK;
2387         TChain rawChain;
2388         if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
2389         rawChain.reverse();
2390         if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
2391
2392         vector< TChain > chains;
2393         if ( error == ERR_OK ) { // chains contains continues rectangles
2394           chains.resize(1);
2395           chains[0].splice( chains[0].begin(), rawChain );
2396         }
2397         else if ( error == ERR_TRI ) {  // chains contains continues triangles
2398           TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
2399           if ( res != _OK ) { // not rectangles split into triangles
2400             fixTriaNearBoundary( rawChain, *this );
2401             break;
2402           }
2403         }
2404         else if ( error == ERR_PRISM ) { // side faces of prisms
2405           fixPrism( rawChain );
2406           break;
2407         }
2408         else {
2409           continue;
2410         }
2411         for ( int iC = 0; iC < chains.size(); ++iC )
2412         {
2413           TChain& chain = chains[iC];
2414           if ( chain.empty() ) continue;
2415           if ( chain.front()->IsStraight() && chain.back()->IsStraight() ) {
2416             MSG("3D straight");
2417             continue;
2418           }
2419           // mesure chain length and compute link position along the chain
2420           double chainLen = 0;
2421           vector< double > linkPos;
2422           MSGBEG( "Link medium nodes: ");
2423           TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
2424           for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
2425             MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
2426             double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2427             while ( len < numeric_limits<double>::min() ) { // remove degenerated link
2428               link1 = chain.erase( link1 );
2429               if ( link1 == chain.end() )
2430                 break;
2431               len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
2432             }
2433             chainLen += len;
2434             linkPos.push_back( chainLen );
2435           }
2436           MSG("");
2437           if ( linkPos.size() < 2 )
2438             continue;
2439
2440           gp_Vec move0 = chain.front()->_nodeMove;
2441           gp_Vec move1 = chain.back ()->_nodeMove;
2442
2443           TopoDS_Face face;
2444           bool checkUV = true;
2445           if ( !isInside ) {
2446             // compute node displacement of end links in parametric space of face
2447             const SMDS_MeshNode* nodeOnFace = (*(++chain.begin()))->_mediumNode;
2448             TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
2449             if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE ) {
2450               face = TopoDS::Face( f );
2451               for ( int is1 = 0; is1 < 2; ++is1 ) { // move0 or move1
2452                 TChainLink& link = is1 ? chain.back() : chain.front();
2453                 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
2454                 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
2455                 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
2456                 gp_XY uvMove = uvm - GetMiddleUV( BRep_Tool::Surface(face,loc), uv1, uv2);
2457                 if ( is1 ) move1.SetCoord( uvMove.X(), uvMove.Y(), 0 );
2458                 else       move0.SetCoord( uvMove.X(), uvMove.Y(), 0 );
2459               }
2460               if ( move0.SquareMagnitude() < straightTol2 &&
2461                    move1.SquareMagnitude() < straightTol2 ) {
2462                 MSG("2D straight");
2463                 continue; // straight - no need to move nodes of internal links
2464               }
2465             }
2466           }
2467           gp_Trsf trsf;
2468           if ( isInside || face.IsNull() )
2469           {
2470             // compute node displacement of end links in their local coord systems
2471             {
2472               TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
2473               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
2474                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2475               move0.Transform(trsf);
2476             }
2477             {
2478               TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
2479               trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
2480                                               gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
2481               move1.Transform(trsf);
2482             }
2483           }
2484           // compute displacement of medium nodes
2485           link2 = chain.begin();
2486           link0 = link2++;
2487           link1 = link2++;
2488           for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
2489           {
2490             double r = linkPos[i] / chainLen;
2491             // displacement in local coord system
2492             gp_Vec move = (1. - r) * move0 + r * move1;
2493             if ( isInside || face.IsNull()) {
2494               // transform to global
2495               gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
2496               gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
2497               gp_Vec x = x01.Normalized() + x12.Normalized();
2498               trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
2499               move.Transform(trsf);
2500             }
2501             else {
2502               // compute 3D displacement by 2D one
2503               gp_XY oldUV   = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
2504               gp_XY newUV   = oldUV + gp_XY( move.X(), move.Y() );
2505               gp_Pnt newPnt = BRep_Tool::Surface(face,loc)->Value( newUV.X(), newUV.Y());
2506               move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
2507 #ifdef _DEBUG_
2508               if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
2509                    move.SquareMagnitude())
2510               {
2511                 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
2512                 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
2513                 MSG( "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
2514                      "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
2515                      "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
2516                      "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
2517               }
2518 #endif
2519             }
2520             (*link1)->Move( move );
2521             MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
2522                  << chain.front()->_mediumNode->GetID() <<"-"
2523                  << chain.back ()->_mediumNode->GetID() <<
2524                  " by " << move.Magnitude());
2525           }
2526         } // loop on chains of links
2527       } // loop on 2 directions of propagation from quadrangle
2528     } // loop on faces
2529   }
2530
2531   // Move nodes
2532   // -----------
2533
2534   for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
2535     if ( pLink->IsMoved() ) {
2536       //gp_Pnt p = pLink->MediumPnt() + pLink->Move();
2537       gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
2538       GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
2539     }
2540   }
2541 }