Salome HOME
PAL16567
[modules/smesh.git] / src / SMESH / SMESH_Pattern.cxx
1 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
3 // 
4 //  This library is free software; you can redistribute it and/or 
5 //  modify it under the terms of the GNU Lesser General Public 
6 //  License as published by the Free Software Foundation; either 
7 //  version 2.1 of the License. 
8 // 
9 //  This library is distributed in the hope that it will be useful, 
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 //  Lesser General Public License for more details. 
13 // 
14 //  You should have received a copy of the GNU Lesser General Public 
15 //  License along with this library; if not, write to the Free Software 
16 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
17 // 
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19
20 // File      : SMESH_Pattern.hxx
21 // Created   : Mon Aug  2 10:30:00 2004
22 // Author    : Edward AGAPOV (eap)
23
24 #include "SMESH_Pattern.hxx"
25
26 #include <BRepAdaptor_Curve.hxx>
27 #include <BRepTools.hxx>
28 #include <BRepTools_WireExplorer.hxx>
29 #include <BRep_Tool.hxx>
30 #include <Bnd_Box.hxx>
31 #include <Bnd_Box2d.hxx>
32 #include <ElSLib.hxx>
33 #include <Extrema_GenExtPS.hxx>
34 #include <Extrema_POnSurf.hxx>
35 #include <Geom2d_Curve.hxx>
36 #include <GeomAdaptor_Surface.hxx>
37 #include <Geom_Curve.hxx>
38 #include <Geom_Surface.hxx>
39 #include <IntAna2d_AnaIntersection.hxx>
40 #include <TopAbs_ShapeEnum.hxx>
41 #include <TopExp.hxx>
42 #include <TopLoc_Location.hxx>
43 #include <TopoDS.hxx>
44 #include <TopoDS_Edge.hxx>
45 #include <TopoDS_Face.hxx>
46 #include <TopoDS_Iterator.hxx>
47 #include <TopoDS_Shell.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
50 #include <TopTools_ListIteratorOfListOfShape.hxx>
51 #include <gp_Ax2.hxx>
52 #include <gp_Lin2d.hxx>
53 #include <gp_Pnt2d.hxx>
54 #include <gp_Trsf.hxx>
55 #include <gp_XY.hxx>
56 #include <gp_XYZ.hxx>
57
58 #include "SMDS_EdgePosition.hxx"
59 #include "SMDS_FacePosition.hxx"
60 #include "SMDS_MeshElement.hxx"
61 #include "SMDS_MeshFace.hxx"
62 #include "SMDS_MeshNode.hxx"
63 #include "SMDS_VolumeTool.hxx"
64 #include "SMESHDS_Group.hxx"
65 #include "SMESHDS_Mesh.hxx"
66 #include "SMESHDS_SubMesh.hxx"
67 #include "SMESH_Block.hxx"
68 #include "SMESH_Mesh.hxx"
69 #include "SMESH_MeshEditor.hxx"
70 #include "SMESH_subMesh.hxx"
71
72 #include "utilities.h"
73
74 using namespace std;
75
76 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
77
78 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
79
80 //=======================================================================
81 //function : SMESH_Pattern
82 //purpose  : 
83 //=======================================================================
84
85 SMESH_Pattern::SMESH_Pattern ()
86 {
87 }
88 //=======================================================================
89 //function : getInt
90 //purpose  : 
91 //=======================================================================
92
93 static inline int getInt( const char * theSring )
94 {
95   if ( *theSring < '0' || *theSring > '9' )
96     return -1;
97
98   char *ptr;
99   int val = strtol( theSring, &ptr, 10 );
100   if ( ptr == theSring ||
101       // there must not be neither '.' nor ',' nor 'E' ...
102       (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
103     return -1;
104
105   return val;
106 }
107
108 //=======================================================================
109 //function : getDouble
110 //purpose  : 
111 //=======================================================================
112
113 static inline double getDouble( const char * theSring )
114 {
115   char *ptr;
116   return strtod( theSring, &ptr );
117 }
118
119 //=======================================================================
120 //function : readLine
121 //purpose  : Put token starting positions in theFields until '\n' or '\0'
122 //           Return the number of the found tokens
123 //=======================================================================
124
125 static int readLine (list <const char*> & theFields,
126                      const char*        & theLineBeg,
127                      const bool           theClearFields )
128 {
129   if ( theClearFields )
130     theFields.clear();
131
132   //  algo:
133   /*  loop                                                       */
134   /*    switch ( symbol ) {                                      */
135   /*    case white-space:                                        */
136   /*      look for a non-space symbol;                           */
137   /*    case string-end:                                         */
138   /*    case line-end:                                           */
139   /*      exit;                                                  */
140   /*    case comment beginning:                                  */
141   /*      skip all till a line-end;                              */
142   /*    case a number                                            */
143   /*      put its position in theFields, skip till a white-space;*/
144   /*    default:                                                 */
145   /*      abort;                                                 */
146   /*  till line-end                                              */
147
148   int nbRead = 0;
149   bool stopReading = false;
150   do {
151     bool goOn = true;
152     bool isNumber = false;
153     switch ( *theLineBeg )
154     {
155     case ' ':  // white space
156     case '\t': // tab
157     case 13:   // ^M
158       break;
159
160     case '\n': // a line ends
161       stopReading = ( nbRead > 0 );
162       break;
163
164     case '!':  // comment
165       do theLineBeg++;
166       while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
167       goOn = false;
168       break;
169
170     case '\0': // file ends
171       return nbRead;
172
173     case '-': // real number
174     case '+':
175     case '.':
176       isNumber = true;
177     default: // data
178       isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
179       if ( isNumber ) {
180         theFields.push_back( theLineBeg );
181         nbRead++;
182         do theLineBeg++;
183         while (*theLineBeg != ' ' &&
184                *theLineBeg != '\n' &&
185                *theLineBeg != '\0');
186         goOn = false;
187       }
188       else
189         return 0; // incorrect file format
190     }
191
192     if ( goOn )
193       theLineBeg++;
194
195   } while ( !stopReading );
196
197   return nbRead;
198 }
199
200 //=======================================================================
201 //function : Load
202 //purpose  : Load a pattern from <theFile>
203 //=======================================================================
204
205 bool SMESH_Pattern::Load (const char* theFileContents)
206 {
207   MESSAGE("Load( file ) ");
208
209   // file structure:
210
211   // ! This is a comment
212   // NB_POINTS               ! 1 integer - the number of points in the pattern.
213   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
214   //   X2 Y2 [Z2]            ! the pattern dimention is defined by the number of coordinates
215   //   ...
216   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
217   // ! elements description goes after all
218   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
219   // ...
220
221   Clear();
222
223   const char* lineBeg = theFileContents;
224   list <const char*> fields;
225   const bool clearFields = true;
226
227   // NB_POINTS               ! 1 integer - the number of points in the pattern.
228
229   if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
230     MESSAGE("Error reading NB_POINTS");
231     return setErrorCode( ERR_READ_NB_POINTS );
232   }
233   int nbPoints = getInt( fields.front() );
234
235   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
236
237   // read the first point coordinates to define pattern dimention
238   int dim = readLine( fields, lineBeg, clearFields );
239   if ( dim == 2 )
240     myIs2D = true;
241   else if ( dim == 3 )
242     myIs2D = false;
243   else {
244     MESSAGE("Error reading points: wrong nb of coordinates");
245     return setErrorCode( ERR_READ_POINT_COORDS );
246   }
247   if ( nbPoints <= dim ) {
248     MESSAGE(" Too few points ");
249     return setErrorCode( ERR_READ_TOO_FEW_POINTS );
250   }
251     
252   // read the rest points
253   int iPoint;
254   for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
255     if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
256       MESSAGE("Error reading  points : wrong nb of coordinates ");
257       return setErrorCode( ERR_READ_POINT_COORDS );
258     }
259   // store point coordinates
260   myPoints.resize( nbPoints );
261   list <const char*>::iterator fIt = fields.begin();
262   for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
263   {
264     TPoint & p = myPoints[ iPoint ];
265     for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
266     {
267       double coord = getDouble( *fIt );
268       if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
269         MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
270         Clear();
271         return setErrorCode( ERR_READ_3D_COORD );
272       }
273       p.myInitXYZ.SetCoord( iCoord, coord );
274       if ( myIs2D )
275         p.myInitUV.SetCoord( iCoord, coord );
276     }
277   }
278
279   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
280   if ( myIs2D )
281   {
282     if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
283       MESSAGE("Error: missing key-points");
284       Clear();
285       return setErrorCode( ERR_READ_NO_KEYPOINT );
286     }
287     set<int> idSet;
288     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
289     {
290       int pointIndex = getInt( *fIt );
291       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
292         MESSAGE("Error: invalid point index " << pointIndex );
293         Clear();
294         return setErrorCode( ERR_READ_BAD_INDEX );
295       }
296       if ( idSet.insert( pointIndex ).second ) // unique?
297         myKeyPointIDs.push_back( pointIndex );
298     }
299   }
300
301   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
302
303   while ( readLine( fields, lineBeg, clearFields ))
304   {
305     myElemPointIDs.push_back( TElemDef() );
306     TElemDef& elemPoints = myElemPointIDs.back();
307     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
308     {
309       int pointIndex = getInt( *fIt );
310       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
311         MESSAGE("Error: invalid point index " << pointIndex );
312         Clear();
313         return setErrorCode( ERR_READ_BAD_INDEX );
314       }
315       elemPoints.push_back( pointIndex );
316     }
317     // check the nb of nodes in element
318     bool Ok = true;
319     switch ( elemPoints.size() ) {
320     case 3: if ( !myIs2D ) Ok = false; break;
321     case 4: break;
322     case 5:
323     case 6:
324     case 8: if ( myIs2D ) Ok = false; break;
325     default: Ok = false;
326     }
327     if ( !Ok ) {
328       MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
329       Clear();
330       return setErrorCode( ERR_READ_ELEM_POINTS );
331     }
332   }
333   if ( myElemPointIDs.empty() ) {
334     MESSAGE("Error: no elements");
335     Clear();
336     return setErrorCode( ERR_READ_NO_ELEMS );
337   }
338
339   findBoundaryPoints(); // sort key-points
340
341   return setErrorCode( ERR_OK );
342 }
343
344 //=======================================================================
345 //function : Save
346 //purpose  : Save the loaded pattern into the file <theFileName>
347 //=======================================================================
348
349 bool SMESH_Pattern::Save (ostream& theFile)
350 {
351   MESSAGE(" ::Save(file) " );
352   if ( !IsLoaded() ) {
353     MESSAGE(" Pattern not loaded ");
354     return setErrorCode( ERR_SAVE_NOT_LOADED );
355   }
356
357   theFile << "!!! SALOME Mesh Pattern file" << endl;
358   theFile << "!!!" << endl;
359   theFile << "!!! Nb of points:" << endl;
360   theFile << myPoints.size() << endl;
361
362   // point coordinates
363   const int width = 8;
364 //  theFile.width( 8 );
365 //  theFile.setf(ios::fixed);// use 123.45 floating notation
366 //  theFile.setf(ios::right);
367 //  theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
368 //   theFile.setf(ios::showpoint); // do not show trailing zeros
369   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
370   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
371     const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
372     theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
373     if ( !myIs2D ) theFile  << " " << setw( width ) << xyz.Z();
374     theFile  << "  !- " << i << endl; // point id to ease reading by a human being
375   }
376   // key-points
377   if ( myIs2D ) {
378     theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
379     list< int >::const_iterator kpIt = myKeyPointIDs.begin();
380     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
381       theFile << " " << *kpIt;
382     if ( !myKeyPointIDs.empty() )
383       theFile << endl;
384   }
385   // elements
386   theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
387   list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
388   for ( ; epIt != myElemPointIDs.end(); epIt++ )
389   {
390     const TElemDef & elemPoints = *epIt;
391     TElemDef::const_iterator iIt = elemPoints.begin();
392     for ( ; iIt != elemPoints.end(); iIt++ )
393       theFile << " " << *iIt;
394     theFile << endl;
395   }
396
397   theFile << endl;
398   
399   return setErrorCode( ERR_OK );
400 }
401
402 //=======================================================================
403 //function : sortBySize
404 //purpose  : sort theListOfList by size
405 //=======================================================================
406
407 template<typename T> struct TSizeCmp {
408   bool operator ()( const list < T > & l1, const list < T > & l2 )
409     const { return l1.size() < l2.size(); }
410 };
411
412 template<typename T> void sortBySize( list< list < T > > & theListOfList )
413 {
414   if ( theListOfList.size() > 2 ) {
415     TSizeCmp< T > SizeCmp;
416     theListOfList.sort( SizeCmp );
417   }
418 }
419
420 //=======================================================================
421 //function : project
422 //purpose  : 
423 //=======================================================================
424
425 static gp_XY project (const SMDS_MeshNode* theNode,
426                       Extrema_GenExtPS &   theProjectorPS)
427 {
428   gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
429   theProjectorPS.Perform( P );
430   if ( !theProjectorPS.IsDone() ) {
431     MESSAGE( "SMESH_Pattern: point projection FAILED");
432     return gp_XY(0.,0.);
433   }
434   double u, v, minVal = DBL_MAX;
435   for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
436     if ( theProjectorPS.Value( i ) < minVal ) {
437       minVal = theProjectorPS.Value( i );
438       theProjectorPS.Point( i ).Parameter( u, v );
439     }
440   return gp_XY( u, v );
441 }
442
443 //=======================================================================
444 //function : areNodesBound
445 //purpose  : true if all nodes of faces are bound to shapes
446 //=======================================================================
447
448 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
449 {
450   while ( faceItr->more() )
451   {
452     SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
453     while ( nIt->more() )
454     {
455       const SMDS_MeshNode* node = smdsNode( nIt->next() );
456       SMDS_PositionPtr pos = node->GetPosition();
457       if ( !pos || !pos->GetShapeId() ) {
458         return false;
459       }
460     }
461   }
462   return true;
463 }
464
465 //=======================================================================
466 //function : isMeshBoundToShape
467 //purpose  : return true if all 2d elements are bound to shape
468 //           if aFaceSubmesh != NULL, then check faces bound to it
469 //           else check all faces in aMeshDS
470 //=======================================================================
471
472 static bool isMeshBoundToShape(SMESHDS_Mesh *     aMeshDS,
473                                SMESHDS_SubMesh *  aFaceSubmesh,
474                                const bool         isMainShape)
475 {
476   if ( isMainShape ) {
477     // check that all faces are bound to aFaceSubmesh
478     if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
479       return false;
480   }
481
482   // check face nodes binding
483   if ( aFaceSubmesh ) {
484     SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
485     return areNodesBound( fIt );
486   }
487   SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
488   return areNodesBound( fIt );
489 }
490
491 //=======================================================================
492 //function : Load
493 //purpose  : Create a pattern from the mesh built on <theFace>.
494 //           <theProject>==true makes override nodes positions
495 //           on <theFace> computed by mesher
496 //=======================================================================
497
498 bool SMESH_Pattern::Load (SMESH_Mesh*        theMesh,
499                           const TopoDS_Face& theFace,
500                           bool               theProject)
501 {
502   MESSAGE(" ::Load(face) " );
503   Clear();
504   myIs2D = true;
505
506   SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
507   SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
508   SMESH_MesherHelper helper( *theMesh );
509   helper.SetSubShape( theFace );
510
511   int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
512   int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
513   if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
514   {
515     MESSAGE( "No elements bound to the face");
516     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
517   }
518
519   TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
520
521   // check that face is not closed
522   bool isClosed = helper.HasSeam();
523   TopoDS_Vertex bidon;
524   list<TopoDS_Edge> eList;
525   list<TopoDS_Edge>::iterator elIt;
526   SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
527
528   // check that requested or needed projection is possible
529   bool isMainShape = theMesh->IsMainShape( face );
530   bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
531   bool canProject  = ( nbElems ? true : isMainShape );
532   if ( isClosed )
533     canProject = false; // so far
534
535   if ( ( theProject || needProject ) && !canProject )
536     return setErrorCode( ERR_LOADF_CANT_PROJECT );
537
538   Extrema_GenExtPS projector;
539   GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
540   if ( theProject || needProject )
541     projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
542
543   int iPoint = 0;
544   TNodePointIDMap nodePointIDMap;
545   TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
546
547   if ( needProject )
548   {
549     MESSAGE("Project the submesh");
550     // ---------------------------------------------------------------
551     // The case where the submesh is projected to theFace
552     // ---------------------------------------------------------------
553
554     // get all faces
555     list< const SMDS_MeshElement* > faces;
556     if ( nbElems > 0 ) {
557       SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
558       while ( fIt->more() ) {
559         const SMDS_MeshElement* f = fIt->next();
560         if ( f && f->GetType() == SMDSAbs_Face )
561           faces.push_back( f );
562       }
563     }
564     else {
565       SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
566       while ( fIt->more() )
567         faces.push_back( fIt->next() );
568     }
569
570     // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
571     list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
572     for ( ; fIt != faces.end(); ++fIt )
573     {
574       myElemPointIDs.push_back( TElemDef() );
575       TElemDef& elemPoints = myElemPointIDs.back();
576       SMDS_ElemIteratorPtr nIt = (*fIt)->nodesIterator();
577       while ( nIt->more() )
578       {
579         const SMDS_MeshElement* node = nIt->next();
580         TNodePointIDMap::iterator nIdIt = nodePointIDMap.find( node );
581         if ( nIdIt == nodePointIDMap.end() )
582         {
583           elemPoints.push_back( iPoint );
584           nodePointIDMap.insert( make_pair( node, iPoint++ ));
585         }
586         else
587           elemPoints.push_back( (*nIdIt).second );
588       }
589     }
590     myPoints.resize( iPoint );
591
592     // project all nodes of 2d elements to theFace
593     TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
594     for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
595     {
596       const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
597       TPoint * p = & myPoints[ (*nIdIt).second ];
598       p->myInitUV = project( node, projector );
599       p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
600     }
601     // find key-points: the points most close to UV of vertices
602     TopExp_Explorer vExp( face, TopAbs_VERTEX );
603     set<int> foundIndices;
604     for ( ; vExp.More(); vExp.Next() ) {
605       const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
606       gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
607       double minDist = DBL_MAX;
608       int index;
609       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
610       for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
611         double dist = uv.SquareDistance( (*pVecIt).myInitUV );
612         if ( dist < minDist ) {
613           minDist = dist;
614           index = iPoint;
615         }
616       }
617       if ( foundIndices.insert( index ).second ) // unique?
618         myKeyPointIDs.push_back( index );
619     }
620     myIsBoundaryPointsFound = false;
621
622   }
623   else
624   {
625     // ---------------------------------------------------------------------
626     // The case where a pattern is being made from the mesh built by mesher
627     // ---------------------------------------------------------------------
628
629     // Load shapes in the consequent order and count nb of points
630
631     // vertices
632     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
633       myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
634       if ( BRep_Tool::IsClosed( *elIt, theFace ) )
635         myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));
636       SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt );
637       if ( eSubMesh )
638         nbNodes += eSubMesh->NbNodes() + 1;
639     }
640     // edges
641     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
642       myShapeIDMap.Add( *elIt );
643     // the face
644     myShapeIDMap.Add( face );
645
646     myPoints.resize( nbNodes );
647
648     // Load U of points on edges
649
650     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
651     {
652       TopoDS_Edge & edge = *elIt;
653       list< TPoint* > & ePoints = getShapePoints( edge );
654       double f, l;
655       Handle(Geom2d_Curve) C2d;
656       if ( !theProject )
657         C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
658       bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
659
660       TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
661       TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
662       // to make adjacent edges share key-point, we make v2 FORWARD too
663       // (as we have different points for same shape with different orienation)
664       v2.Reverse();
665
666       // on closed face we must have REVERSED some of seam vertices
667       bool isSeam = helper.IsSeamShape( edge );
668       if ( isClosed ) {
669         if ( isSeam ) { // reverse on reversed SEAM edge
670           if ( !isForward ) {
671             v1.Reverse();
672             v2.Reverse();
673           }
674         }
675         else { // on CLOSED edge
676           for ( int is2 = 0; is2 < 2; ++is2 ) {
677             TopoDS_Shape & v = is2 ? v2 : v1;
678             if ( helper.IsSeamShape( v ) ) {
679               // reverse or not depending on orientation of adjacent seam
680               TopoDS_Edge seam;
681               list<TopoDS_Edge>::iterator eIt2 = elIt;
682               if ( is2 )
683                 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
684               else
685                 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
686               if ( seam.Orientation() == TopAbs_REVERSED )
687                 v.Reverse();
688             }
689           }
690         }
691       }
692
693       // the forward key-point
694       list< TPoint* > * vPoint = & getShapePoints( v1 );
695       if ( vPoint->empty() )
696       {
697         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
698         if ( vSubMesh && vSubMesh->NbNodes() ) {
699           myKeyPointIDs.push_back( iPoint );
700           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
701           const SMDS_MeshNode* node = nIt->next();
702           if ( v1.Orientation() == TopAbs_REVERSED )
703             closeNodePointIDMap.insert( make_pair( node, iPoint ));
704           else
705             nodePointIDMap.insert( make_pair( node, iPoint ));
706
707           TPoint* keyPoint = &myPoints[ iPoint++ ];
708           vPoint->push_back( keyPoint );
709           if ( theProject )
710             keyPoint->myInitUV = project( node, projector );
711           else
712             keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
713           keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
714         }
715       }
716       if ( !vPoint->empty() )
717         ePoints.push_back( vPoint->front() );
718
719       // on-edge points
720       SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
721       if ( eSubMesh && eSubMesh->NbNodes() )
722       {
723         // loop on nodes of an edge: sort them by param on edge
724         typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
725         TParamNodeMap paramNodeMap;
726         SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
727         while ( nIt->more() )
728         {
729           const SMDS_MeshNode* node = smdsNode( nIt->next() );
730           const SMDS_EdgePosition* epos =
731             static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
732           double u = epos->GetUParameter();
733           paramNodeMap.insert( TParamNodeMap::value_type( u, node ));
734         }
735         // put U in [0,1] so that the first key-point has U==0
736         double du = l - f;
737         TParamNodeMap::iterator         unIt  = paramNodeMap.begin();
738         TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
739         while ( unIt != paramNodeMap.end() )
740         {
741           TPoint* p = & myPoints[ iPoint ];
742           ePoints.push_back( p );
743           const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
744           if ( isSeam && !isForward )
745             closeNodePointIDMap.insert( make_pair( node, iPoint ));
746           else
747             nodePointIDMap.insert ( make_pair( node, iPoint ));
748
749           if ( theProject )
750             p->myInitUV = project( node, projector );
751           else {
752             double u = isForward ? (*unIt).first : (*unRIt).first;
753             p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
754             p->myInitUV = C2d->Value( u ).XY();
755           }
756           p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
757           unIt++; unRIt++;
758           iPoint++;
759         }
760       }
761       // the reverse key-point
762       vPoint = & getShapePoints( v2 );
763       if ( vPoint->empty() )
764       {
765         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
766         if ( vSubMesh && vSubMesh->NbNodes() ) {
767           myKeyPointIDs.push_back( iPoint );
768           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
769           const SMDS_MeshNode* node = nIt->next();
770           if ( v2.Orientation() == TopAbs_REVERSED )
771             closeNodePointIDMap.insert( make_pair( node, iPoint ));
772           else
773             nodePointIDMap.insert( make_pair( node, iPoint ));
774
775           TPoint* keyPoint = &myPoints[ iPoint++ ];
776           vPoint->push_back( keyPoint );
777           if ( theProject )
778             keyPoint->myInitUV = project( node, projector );
779           else
780             keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
781           keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
782         }
783       }
784       if ( !vPoint->empty() )
785         ePoints.push_back( vPoint->front() );
786
787       // compute U of edge-points
788       if ( theProject )
789       {
790         double totalDist = 0;
791         list< TPoint* >::iterator pIt = ePoints.begin();
792         TPoint* prevP = *pIt;
793         prevP->myInitU = totalDist;
794         for ( pIt++; pIt != ePoints.end(); pIt++ ) {
795           TPoint* p = *pIt;
796           totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
797           p->myInitU = totalDist;
798           prevP = p;
799         }
800         if ( totalDist > DBL_MIN)
801           for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
802             TPoint* p = *pIt;
803             p->myInitU /= totalDist;
804           }
805       }
806     } // loop on edges of a wire
807
808     // Load in-face points and elements
809
810     if ( fSubMesh && fSubMesh->NbElements() )
811     {
812       list< TPoint* > & fPoints = getShapePoints( face );
813       SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
814       while ( nIt->more() )
815       {
816         const SMDS_MeshNode* node = smdsNode( nIt->next() );
817         nodePointIDMap.insert( make_pair( node, iPoint ));
818         TPoint* p = &myPoints[ iPoint++ ];
819         fPoints.push_back( p );
820         if ( theProject )
821           p->myInitUV = project( node, projector );
822         else {
823           const SMDS_FacePosition* pos =
824             static_cast<const SMDS_FacePosition*>(node->GetPosition().get());
825           p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
826         }
827         p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
828       }
829       // load elements
830       SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
831       while ( elemIt->more() )
832       {
833         const SMDS_MeshElement* elem = elemIt->next();
834         SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
835         myElemPointIDs.push_back( TElemDef() );
836         TElemDef& elemPoints = myElemPointIDs.back();
837         // find point indices corresponding to element nodes
838         while ( nIt->more() )
839         {
840           const SMDS_MeshNode* node = smdsNode( nIt->next() );
841           iPoint = nodePointIDMap[ node ]; // point index of interest
842           // for a node on a seam edge there are two points
843           TNodePointIDMap::iterator n_id = closeNodePointIDMap.end();
844           if ( helper.IsSeamShape( node->GetPosition()->GetShapeId() ))
845             n_id = closeNodePointIDMap.find( node );
846           if ( n_id != closeNodePointIDMap.end() )
847           {
848             TPoint & p1 = myPoints[ iPoint ];
849             TPoint & p2 = myPoints[ n_id->second ];
850             // Select point closest to the rest nodes of element in UV space
851             SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
852             const SMDS_MeshNode* notSeamNode = 0;
853             // find node not on a seam edge
854             while ( nIt2->more() && !notSeamNode ) {
855               const SMDS_MeshNode* n = smdsNode( nIt2->next() );
856               if ( !helper.IsSeamShape( n->GetPosition()->GetShapeId() ))
857                 notSeamNode = n;
858             }
859             gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
860             double dist1 = uv.SquareDistance( p1.myInitUV );
861             double dist2 = uv.SquareDistance( p2.myInitUV );
862             if ( dist2 < dist1 )
863               iPoint = n_id->second;
864           }
865           elemPoints.push_back( iPoint );
866         }
867       }
868     }
869
870     myIsBoundaryPointsFound = true;
871   }
872
873   // Assure that U range is proportional to V range
874
875   Bnd_Box2d bndBox;
876   vector< TPoint >::iterator pVecIt = myPoints.begin();
877   for ( ; pVecIt != myPoints.end(); pVecIt++ )
878     bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
879   double minU, minV, maxU, maxV;
880   bndBox.Get( minU, minV, maxU, maxV );
881   double dU = maxU - minU, dV = maxV - minV;
882   if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
883     Clear();
884     bndBox.SetVoid();
885     // define where is the problem, in the face or in the mesh
886     TopExp_Explorer vExp( face, TopAbs_VERTEX );
887     for ( ; vExp.More(); vExp.Next() ) {
888       gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
889       bndBox.Add( uv );
890     }
891     bndBox.Get( minU, minV, maxU, maxV );
892     dU = maxU - minU, dV = maxV - minV;
893     if ( dU <= DBL_MIN || dV <= DBL_MIN )
894       // face problem
895       return setErrorCode( ERR_LOADF_NARROW_FACE );
896     else
897       // mesh is projected onto a line, e.g.
898       return setErrorCode( ERR_LOADF_CANT_PROJECT );
899   }
900   double ratio = dU / dV, maxratio = 3, scale;
901   int iCoord = 0;
902   if ( ratio > maxratio ) {
903     scale = ratio / maxratio;
904     iCoord = 2;
905   }
906   else if ( ratio < 1./maxratio ) {
907     scale = maxratio / ratio;
908     iCoord = 1;
909   }
910   if ( iCoord ) {
911     SCRUTE( scale );
912     for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
913       TPoint & p = *pVecIt;
914       p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
915       p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
916     }
917   }
918   if ( myElemPointIDs.empty() ) {
919     MESSAGE( "No elements bound to the face");
920     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
921   }
922
923   return setErrorCode( ERR_OK );
924 }
925
926 //=======================================================================
927 //function : computeUVOnEdge
928 //purpose  : compute coordinates of points on theEdge
929 //=======================================================================
930
931 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge&      theEdge,
932                                      const list< TPoint* > & ePoints )
933 {
934   bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
935   double f, l;
936   Handle(Geom2d_Curve) C2d =
937     BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
938
939   ePoints.back()->myInitU = 1.0;
940   list< TPoint* >::const_iterator pIt = ePoints.begin();
941   for ( pIt++; pIt != ePoints.end(); pIt++ )
942   {
943     TPoint* point = *pIt;
944     // U
945     double du = ( isForward ? point->myInitU : 1 - point->myInitU );
946     point->myU = ( f * ( 1 - du ) + l * du );
947     // UV
948     point->myUV = C2d->Value( point->myU ).XY();
949   }
950 }
951
952 //=======================================================================
953 //function : intersectIsolines
954 //purpose  : 
955 //=======================================================================
956
957 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
958                               const gp_XY& uv21, const gp_XY& uv22, const double r2,
959                               gp_XY& resUV,
960                               bool& isDeformed)
961 {
962   gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
963   gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
964   resUV = 0.5 * ( loc1 + loc2 );
965   isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
966 //   double len1 = ( uv11 - uv12 ).Modulus();
967 //   double len2 = ( uv21 - uv22 ).Modulus();
968 //   resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
969 //  return true;
970
971   
972 //   gp_Lin2d line1( uv11, uv12 - uv11 );
973 //   gp_Lin2d line2( uv21, uv22 - uv21 );
974 //   double angle = Abs( line1.Angle( line2 ) );
975
976 //     IntAna2d_AnaIntersection inter;
977 //     inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
978 //     if ( inter.IsDone() && inter.NbPoints() == 1 )
979 //     {
980 //       gp_Pnt2d interUV = inter.Point(1).Value();
981 //       resUV += interUV.XY();
982 //   inter.Perform( line1, line2 );
983 //   interUV = inter.Point(1).Value();
984 //   resUV += interUV.XY();
985   
986 //   resUV /= 2.;
987 //     }
988   return true;
989 }
990
991 //=======================================================================
992 //function : compUVByIsoIntersection
993 //purpose  : 
994 //=======================================================================
995
996 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
997                                              const gp_XY&                   theInitUV,
998                                              gp_XY&                         theUV,
999                                              bool &                         theIsDeformed )
1000 {
1001   // compute UV by intersection of 2 iso lines
1002   //gp_Lin2d isoLine[2];
1003   gp_XY uv1[2], uv2[2];
1004   double ratio[2];
1005   const double zero = DBL_MIN;
1006   for ( int iIso = 0; iIso < 2; iIso++ )
1007   {
1008     // to build an iso line:
1009     // find 2 pairs of consequent edge-points such that the range of their
1010     // initial parameters encloses the in-face point initial parameter
1011     gp_XY UV[2], initUV[2];
1012     int nbUV = 0, iCoord = iIso + 1;
1013     double initParam = theInitUV.Coord( iCoord );
1014
1015     list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1016     for ( ; bndIt != theBndPoints.end(); bndIt++ )
1017     {
1018       const list< TPoint* > & bndPoints = * bndIt;
1019       TPoint* prevP = bndPoints.back(); // this is the first point
1020       list< TPoint* >::const_iterator pIt = bndPoints.begin();
1021       bool coincPrev = false; 
1022       // loop on the edge-points
1023       for ( ; pIt != bndPoints.end(); pIt++ )
1024       {
1025         double paramDiff     = initParam - (*pIt)->myInitUV.Coord( iCoord );
1026         double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1027         double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1028         if (!coincPrev && // ignore if initParam coincides with prev point param
1029             sumOfDiff > zero && // ignore if both points coincide with initParam
1030             prevParamDiff * paramDiff <= zero )
1031         {
1032           // find UV in parametric space of theFace
1033           double r = Abs(prevParamDiff) / sumOfDiff;
1034           gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1035           int i = nbUV++;
1036           if ( i >= 2 ) {
1037             // throw away uv most distant from <theInitUV>
1038             gp_XY vec0 = initUV[0] - theInitUV;
1039             gp_XY vec1 = initUV[1] - theInitUV;
1040             gp_XY vec  = uvInit    - theInitUV;
1041             bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1042             double dist0 = vec0.SquareModulus();
1043             double dist1 = vec1.SquareModulus();
1044             double dist  = vec .SquareModulus();
1045             if ( !isBetween || dist < dist0 || dist < dist1 ) {
1046               i = ( dist0 < dist1 ? 1 : 0 );
1047               if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1048                 i = 3; // theInitUV must remain between
1049             }
1050           }
1051           if ( i < 2 ) {
1052             initUV[ i ] = uvInit;
1053             UV[ i ]     = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1054           }
1055           coincPrev = ( Abs(paramDiff) <= zero );
1056         }
1057         else
1058           coincPrev = false;
1059         prevP = *pIt;
1060       }
1061     }
1062     if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1063       MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1064               ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1065       return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1066     }
1067     // an iso line should be normal to UV[0] - UV[1] direction
1068     // and be located at the same relative distance as from initial ends
1069     //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1070     double r =
1071       (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1072     //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1073     //isoLine[ iIso ] = iso.Normal( isoLoc );
1074     uv1[ iIso ] = UV[0];
1075     uv2[ iIso ] = UV[1];
1076     ratio[ iIso ] = r;
1077   }
1078   if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1079                           uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1080     MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1081     return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1082   }
1083
1084   return true;
1085 }
1086
1087
1088 // ==========================================================
1089 // structure representing a node of a grid of iso-poly-lines
1090 // ==========================================================
1091
1092 struct TIsoNode {
1093   bool   myIsMovable;
1094   gp_XY  myInitUV;
1095   gp_XY  myUV;
1096   double myRatio[2];
1097   gp_Dir2d  myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1098   TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1099   TIsoNode* myBndNodes[4];     // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1100   TIsoNode(double initU, double initV):
1101     myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1102   { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1103   bool IsUVComputed() const
1104   { return myUV.X() != 1e100; }
1105   bool IsMovable() const
1106   { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1107   void SetNotMovable()
1108   { myIsMovable = false; }
1109   void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1110   { myBndNodes[ iDir + i * 2 ] = node; }
1111   TIsoNode* GetBoundaryNode(int iDir, int i)
1112   { return myBndNodes[ iDir + i * 2 ]; }
1113   void SetNext(TIsoNode* node, int iDir, int isForward)
1114   { myNext[ iDir + isForward  * 2 ] = node; }
1115   TIsoNode* GetNext(int iDir, int isForward)
1116   { return myNext[ iDir + isForward * 2 ]; }
1117 };
1118
1119 //=======================================================================
1120 //function : getNextNode
1121 //purpose  : 
1122 //=======================================================================
1123
1124 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1125 {
1126   TIsoNode* n = node->myNext[ dir ];
1127   if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1128     n = 0;//node->myBndNodes[ dir ];
1129 //     MESSAGE("getNextNode: use bnd for node "<<
1130 //             node->myInitUV.X()<<" "<<node->myInitUV.Y());
1131   }
1132   return n;
1133 }
1134 //=======================================================================
1135 //function : checkQuads
1136 //purpose  : check if newUV destortes quadrangles around node,
1137 //           and if ( crit == FIX_OLD ) fix newUV in this case
1138 //=======================================================================
1139
1140 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1141
1142 static bool checkQuads (const TIsoNode* node,
1143                         gp_XY&          newUV,
1144                         const bool      reversed,
1145                         const int       crit = FIX_OLD,
1146                         double          fixSize = 0.)
1147 {
1148   gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1149   int nbOldFix = 0, nbOldImpr = 0;
1150   double newBadRate = 0, oldBadRate = 0;
1151   bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1152   int i, dir1 = 0, dir2 = 3;
1153   for ( ; dir1 < 4; dir1++, dir2++ )  // loop on 4 quadrangles around <node>
1154   {
1155     if ( dir2 > 3 ) dir2 = 0;
1156     TIsoNode* n[3];
1157     // walking counterclockwise around a quad,
1158     // nodes are in the order: node, n[0], n[1], n[2]
1159     n[0] = getNextNode( node, dir1 );
1160     n[2] = getNextNode( node, dir2 );
1161     if ( !n[0] || !n[2] ) continue;
1162     n[1] = getNextNode( n[0], dir2 );
1163     if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1164     bool isTriangle = ( !n[1] );
1165     if ( reversed ) {
1166       TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1167     }
1168 //     if ( fixSize != 0 ) {
1169 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1170 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1171 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1172 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1173 // }
1174     // check if a quadrangle is degenerated
1175     if ( !isTriangle &&
1176         ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1177          (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1178       isTriangle = true;
1179     if ( isTriangle &&
1180         ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1181       continue;
1182
1183     // find min size of the diagonal node-n[1]
1184     double minDiag = fixSize;
1185     if ( minDiag == 0. ) {
1186       double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1187       if ( !isTriangle ) {
1188         maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1189         maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1190       }
1191       maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1192       minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1193     }
1194
1195     // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1196     // ( behind means "to the right of")
1197     // it is OK if
1198     // 1. newUV is not behind 01 and 12 dirs
1199     // 2. or newUV is not behind 02 dir and n[2] is convex
1200     bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1201     bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1202     gp_Vec2d moveVec[3], outVec[3];
1203     for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1204     {
1205       bool isDiag = ( i == 2 );
1206       if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1207         break;
1208       gp_Vec2d sideDir;
1209       if ( isDiag )
1210         sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1211       else
1212         sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1213
1214       gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1215       outDir.Normalize();
1216       gp_Vec2d newDir( n[i]->myUV, newUV );
1217       gp_Vec2d oldDir( n[i]->myUV, oldUV );
1218       outVec[i] = outDir;
1219       if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1220       if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1221       if ( crit == FIX_OLD ) {
1222         wasIn[i] = ( outDir * oldDir < 0 );
1223         wasOk[i] = ( outDir * oldDir < -minDiag );
1224         if ( !newOk[i] )
1225           newBadRate += outDir * newDir;
1226         if ( !wasOk[i] )
1227           oldBadRate += outDir * oldDir;
1228         // push node inside
1229         if ( !wasOk[i] ) {
1230           double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1231           //               double r = ( l1 - minDiag ) / ( l1 + l2 );
1232           //               moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1233           moveVec[i] = ( oldDist - minDiag ) * outDir;
1234         }
1235       }
1236     }
1237
1238     // check if n[2] is convex
1239     bool convex = true;
1240     if ( !isTriangle )
1241       convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1242
1243     bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1244     bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1245     newIsOk = ( newIsOk && isNewOk );
1246     newIsIn = ( newIsIn && isNewIn );
1247
1248     if ( crit != FIX_OLD ) {
1249       if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1250       if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1251       continue;
1252     }
1253
1254     bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1255     bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1256     oldIsIn = ( oldIsIn && isOldIn );
1257     oldIsOk = ( oldIsOk && isOldIn );
1258
1259
1260     if ( !isOldIn ) { // node is outside a quadrangle
1261       // move newUV inside a quadrangle
1262 //MESSAGE("Quad "<< dir1 << "  WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1263       // node and newUV are outside: push newUV inside
1264       gp_XY uv;
1265       if ( convex || isTriangle ) {
1266         uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1267       }
1268       else {
1269         gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1270         double outSize = out.Magnitude();
1271         if ( outSize > DBL_MIN )
1272           out /= outSize;
1273         else
1274           out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1275         uv = n[1]->myUV - minDiag * out.XY();
1276       }
1277       oldUVFixed[ nbOldFix++ ] = uv;
1278       //node->myUV = newUV;
1279     }
1280     else if ( !isOldOk )  {
1281       // try to fix old UV: move node inside as less as possible
1282 //MESSAGE("Quad "<< dir1 << "  old is BAD, try to fix old, minDiag: "<< minDiag);
1283       gp_XY uv1, uv2 = node->myUV;
1284       for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1285         if ( wasOk[i] )
1286           moveVec[ i ].SetCoord( 1, 2e100); // not use this vector 
1287       while ( !isOldOk ) {
1288         // find the least moveVec
1289         int i, iMin = 4;
1290         double minMove2 = 1e100;
1291         for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1292         {
1293           if ( moveVec[i].Coord(1) < 1e100 ) {
1294             double move2 = moveVec[i].SquareMagnitude();
1295             if ( move2 < minMove2 ) {
1296               minMove2 = move2;
1297               iMin = i;
1298             }
1299           }
1300         }
1301         if ( iMin == 4 ) {
1302           break;
1303         }
1304         // move node to newUV
1305         uv1 = node->myUV + moveVec[ iMin ].XY();
1306         uv2 += moveVec[ iMin ].XY();
1307         moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1308         // check if uv1 is ok
1309         for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1310           wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1311         isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1312         if ( isOldOk )
1313           oldUVImpr[ nbOldImpr++ ] = uv1;
1314         else {
1315           // check if uv2 is ok
1316           for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1317             wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1318           isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1319           if ( isOldOk )
1320             oldUVImpr[ nbOldImpr++ ] = uv2;
1321         }
1322       }
1323     }
1324
1325   } // loop on 4 quadrangles around <node>
1326
1327   if ( crit == CHECK_NEW_OK  )
1328     return newIsOk;
1329   if ( crit == CHECK_NEW_IN  )
1330     return newIsIn;
1331
1332   if ( newIsOk )
1333     return true;
1334
1335   if ( oldIsOk )
1336     newUV = oldUV;
1337   else {
1338     if ( oldIsIn && nbOldImpr ) {
1339 //       MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1340 //               " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1341       gp_XY uv = oldUVImpr[ 0 ];
1342       for ( int i = 1; i < nbOldImpr; i++ )
1343         uv += oldUVImpr[ i ];
1344       uv /= nbOldImpr;
1345       if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1346         newUV = uv;
1347         return false;
1348       }
1349       else {
1350         //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1351       }
1352     }
1353     if ( !oldIsIn && nbOldFix ) {
1354 //       MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1355 //               " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1356       gp_XY uv = oldUVFixed[ 0 ];
1357       for ( int i = 1; i < nbOldFix; i++ )
1358         uv += oldUVFixed[ i ];
1359       uv /= nbOldFix;
1360       if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1361         newUV = uv;
1362         return false;
1363       }
1364       else {
1365         //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1366       }
1367     }
1368     if ( newIsIn && oldIsIn )
1369       newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1370     else if ( !newIsIn )
1371       newUV = oldUV;
1372   }
1373
1374   return false;
1375 }
1376
1377 //=======================================================================
1378 //function : compUVByElasticIsolines
1379 //purpose  : compute UV as nodes of iso-poly-lines consisting of
1380 //           segments keeping relative size as in the pattern
1381 //=======================================================================
1382 //#define DEB_COMPUVBYELASTICISOLINES
1383 bool SMESH_Pattern::
1384   compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1385                           const list< TPoint* >&         thePntToCompute)
1386 {
1387   //return false;
1388 //cout << "============================== KEY POINTS =============================="<<endl;
1389 //   list< int >::iterator kpIt = myKeyPointIDs.begin();
1390 //   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1391 //     TPoint& p = myPoints[ *kpIt ];
1392 //     cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1393 //       " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1394 //  }
1395 //cout << "=============================="<<endl;
1396
1397   // Define parameters of iso-grid nodes in U and V dir
1398
1399   set< double > paramSet[ 2 ];
1400   list< list< TPoint* > >::const_iterator pListIt;
1401   list< TPoint* >::const_iterator pIt;
1402   for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1403     const list< TPoint* > & pList = * pListIt;
1404     for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1405       paramSet[0].insert( (*pIt)->myInitUV.X() );
1406       paramSet[1].insert( (*pIt)->myInitUV.Y() );
1407     }
1408   }
1409   for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1410     paramSet[0].insert( (*pIt)->myInitUV.X() );
1411     paramSet[1].insert( (*pIt)->myInitUV.Y() );
1412   }
1413   // unite close parameters and split too long segments
1414   int iDir;
1415   double tol[ 2 ];
1416   for ( iDir = 0; iDir < 2; iDir++ )
1417   {
1418     set< double > & params = paramSet[ iDir ];
1419     double range = ( *params.rbegin() - *params.begin() );
1420     double toler = range / 1e6;
1421     tol[ iDir ] = toler;
1422 //    double maxSegment = range / params.size() / 2.;
1423 //
1424 //     set< double >::iterator parIt = params.begin();
1425 //     double prevPar = *parIt;
1426 //     for ( parIt++; parIt != params.end(); parIt++ )
1427 //     {
1428 //       double segLen = (*parIt) - prevPar;
1429 //       if ( segLen < toler )
1430 //         ;//params.erase( prevPar ); // unite
1431 //       else if ( segLen > maxSegment )
1432 //         params.insert( prevPar + 0.5 * segLen ); // split
1433 //       prevPar = (*parIt);
1434 //     }
1435   }
1436
1437   // Make nodes of a grid of iso-poly-lines
1438
1439   list < TIsoNode > nodes;
1440   typedef list < TIsoNode *> TIsoLine;
1441   map < double, TIsoLine > isoMap[ 2 ];
1442
1443   set< double > & params0 = paramSet[ 0 ];
1444   set< double >::iterator par0It = params0.begin();
1445   for ( ; par0It != params0.end(); par0It++ )
1446   {
1447     TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1448     set< double > & params1 = paramSet[ 1 ];
1449     set< double >::iterator par1It = params1.begin();
1450     for ( ; par1It != params1.end(); par1It++ )
1451     {
1452       nodes.push_back( TIsoNode( *par0It, *par1It ) );
1453       isoLine0.push_back( & nodes.back() );
1454       isoMap[1][ *par1It ].push_back( & nodes.back() );
1455     }
1456   }
1457
1458   // Compute intersections of boundaries with iso-lines:
1459   // only boundary nodes will have computed UV so far
1460
1461   Bnd_Box2d uvBnd;
1462   list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1463   list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1464   for ( ; bndIt != theBndPoints.end(); bndIt++ )
1465   {
1466     const list< TPoint* > & bndPoints = * bndIt;
1467     TPoint* prevP = bndPoints.back(); // this is the first point
1468     list< TPoint* >::const_iterator pIt = bndPoints.begin();
1469     // loop on the edge-points
1470     for ( ; pIt != bndPoints.end(); pIt++ )
1471     {
1472       TPoint* point = *pIt;
1473       for ( iDir = 0; iDir < 2; iDir++ )
1474       {
1475         const int iCoord = iDir + 1;
1476         const int iOtherCoord = 2 - iDir;
1477         double par1 = prevP->myInitUV.Coord( iCoord );
1478         double par2 = point->myInitUV.Coord( iCoord );
1479         double parDif = par2 - par1;
1480         if ( Abs( parDif ) <= DBL_MIN )
1481           continue;
1482         // find iso-lines intersecting a bounadry
1483         double toler = tol[ 1 - iDir ];
1484         double minPar = Min ( par1, par2 );
1485         double maxPar = Max ( par1, par2 );
1486         map < double, TIsoLine >& isos = isoMap[ iDir ];
1487         map < double, TIsoLine >::iterator isoIt = isos.begin();
1488         for ( ; isoIt != isos.end(); isoIt++ )
1489         {
1490           double isoParam = (*isoIt).first;
1491           if ( isoParam < minPar || isoParam > maxPar )
1492             continue;
1493           double r = ( isoParam - par1 ) / parDif;
1494           gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1495           gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1496           double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1497           // find existing node with otherPar or insert a new one
1498           TIsoLine & isoLine = (*isoIt).second;
1499           double nodePar;
1500           TIsoLine::iterator nIt = isoLine.begin();
1501           for ( ; nIt != isoLine.end(); nIt++ ) {
1502             nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1503             if ( nodePar >= otherPar )
1504               break;
1505           }
1506           TIsoNode * node;
1507           if ( Abs( nodePar - otherPar ) <= toler )
1508             node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1509           else {
1510             nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1511             node = & nodes.back();
1512             isoLine.insert( nIt, node );
1513           }
1514           node->SetNotMovable();
1515           node->myUV = uv;
1516           uvBnd.Add( gp_Pnt2d( uv ));
1517 //  cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1518           // tangent dir
1519           gp_XY tgt( point->myUV - prevP->myUV );
1520           if ( ::IsEqual( r, 1. ))
1521             node->myDir[ 0 ] = tgt;
1522           else if ( ::IsEqual( r, 0. ))
1523             node->myDir[ 1 ] = tgt;
1524           else
1525             node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1526           // keep boundary nodes corresponding to boundary points
1527           if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1528             if ( bndNodes.empty() || bndNodes.back() != node )
1529               bndNodes.push_back( node );
1530         } // loop on isolines
1531       } // loop on 2 directions
1532       prevP = point;
1533     } // loop on boundary points
1534   } // loop on boundaries
1535
1536   // Define orientation
1537
1538   // find the point with the least X
1539   double leastX = DBL_MAX;
1540   TIsoNode * leftNode;
1541   list < TIsoNode >::iterator nodeIt = nodes.begin();
1542   for ( ; nodeIt != nodes.end(); nodeIt++  ) {
1543     TIsoNode & node = *nodeIt;
1544     if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1545       leastX = node.myUV.X();
1546       leftNode = &node;
1547     }
1548 // if ( node.IsUVComputed() ) {
1549 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1550 //   node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1551 //    " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1552 //      " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1553 // }
1554   }
1555   bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1556   //SCRUTE( reversed );
1557
1558   // Prepare internal nodes:
1559   // 1. connect nodes
1560   // 2. compute ratios
1561   // 3. find boundary nodes for each node
1562   // 4. remove nodes out of the boundary
1563   for ( iDir = 0; iDir < 2; iDir++ )
1564   {
1565     const int iCoord = 2 - iDir; // coord changing along an isoline
1566     map < double, TIsoLine >& isos = isoMap[ iDir ];
1567     map < double, TIsoLine >::iterator isoIt = isos.begin();
1568     for ( ; isoIt != isos.end(); isoIt++ )
1569     {
1570       TIsoLine & isoLine = (*isoIt).second;
1571       bool firstCompNodeFound = false;
1572       TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1573       nPrevIt = nIt = nNextIt = isoLine.begin();
1574       nIt++;
1575       nNextIt++; nNextIt++;
1576       while ( nIt != isoLine.end() )
1577       {
1578         // 1. connect prev - cur
1579         TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1580         if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1581           firstCompNodeFound = true;
1582           lastCompNodePos = nPrevIt;
1583         }
1584         if ( firstCompNodeFound ) {
1585           node->SetNext( prevNode, iDir, 0 );
1586           prevNode->SetNext( node, iDir, 1 );
1587         }
1588         // 2. compute ratio
1589         if ( nNextIt != isoLine.end() ) {
1590           double par1 = prevNode->myInitUV.Coord( iCoord );
1591           double par2 = node->myInitUV.Coord( iCoord );
1592           double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1593           node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1594         }
1595         // 3. find boundary nodes
1596         if ( node->IsUVComputed() )
1597           lastCompNodePos = nIt;
1598         else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1599           TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1600           for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1601             if ( (*nIt2)->IsUVComputed() )
1602               break;
1603           if ( nIt2 != isoLine.end() ) {
1604             bndNode2 = *nIt2;
1605             node->SetBoundaryNode( bndNode1, iDir, 0 );
1606             node->SetBoundaryNode( bndNode2, iDir, 1 );
1607 // cout << "--------------------------------------------------"<<endl;
1608 //  cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1609 //   " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1610 //     " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1611 //  cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1612 //   " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1613 //     " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1614           }
1615           else {
1616             /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1617             node->SetBoundaryNode( 0, iDir, 0 );
1618             node->SetBoundaryNode( 0, iDir, 1 );
1619           }
1620         }
1621         nIt++; nPrevIt++;
1622         if ( nNextIt != isoLine.end() ) nNextIt++;
1623         // 4. remove nodes out of the boundary
1624         if ( !firstCompNodeFound )
1625           isoLine.pop_front();
1626       } // loop on isoLine nodes
1627
1628       // remove nodes after the boundary
1629 //       for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1630 //         (*nIt)->SetNotMovable();
1631       isoLine.erase( ++lastCompNodePos, isoLine.end() );
1632     } // loop on isolines
1633   } // loop on 2 directions
1634
1635   // Compute local isoline direction for internal nodes
1636
1637   /*
1638   map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1639   map < double, TIsoLine >::iterator isoIt = isos.begin();
1640   for ( ; isoIt != isos.end(); isoIt++ )
1641   {
1642     TIsoLine & isoLine = (*isoIt).second;
1643     TIsoLine::iterator nIt = isoLine.begin();
1644     for ( ; nIt != isoLine.end(); nIt++ )
1645     {
1646       TIsoNode* node = *nIt;
1647       if ( node->IsUVComputed() || !node->IsMovable() )
1648         continue;
1649       gp_Vec2d aTgt[2], aNorm[2];
1650       double ratio[2];
1651       bool OK = true;
1652       for ( iDir = 0; iDir < 2; iDir++ )
1653       {
1654         TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1655         TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1656         if ( !bndNode1 || !bndNode2 ) {
1657           OK = false;
1658           break;
1659         }
1660         const int iCoord = 2 - iDir; // coord changing along an isoline
1661         double par1 = bndNode1->myInitUV.Coord( iCoord );
1662         double par2 = node->myInitUV.Coord( iCoord );
1663         double par3 = bndNode2->myInitUV.Coord( iCoord );
1664         ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1665
1666         gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1667         gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1668         if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1669         else                            tgt1.Reverse();
1670 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1671
1672         if ( ratio[ iDir ] < 0.5 )
1673           aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1674         else
1675           aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1676         if ( iDir == 1 )
1677           aNorm[ iDir ].Reverse();  // along iDir isoline
1678
1679         double angle = tgt1.Angle( tgt2 ); //  [-PI, PI]
1680         // maybe angle is more than |PI|
1681         if ( Abs( angle ) > PI / 2. ) {
1682           // check direction of the last but one perpendicular isoline
1683           TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1684           bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1685           bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1686           gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1687           if ( isoDir * tgt2 < 0 )
1688             isoDir.Reverse();
1689           double angle2 = tgt1.Angle( isoDir );
1690           //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1691           if (angle2 * angle < 0 && // check the sign of an angle close to PI
1692               Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1693             //MESSAGE("REVERSE ANGLE");
1694             angle = -angle;
1695           }
1696           if ( Abs( angle2 ) > Abs( angle ) ||
1697               ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1698             //MESSAGE("Add PI");
1699             // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1700             // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1701             // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1702             // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1703             // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<"  "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1704             angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1705           }
1706         }
1707         aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1708       } // loop on 2 dir
1709
1710       if ( OK ) {
1711         for ( iDir = 0; iDir < 2; iDir++ )
1712         {
1713           aTgt[iDir].Normalize();
1714           aNorm[1-iDir].Normalize();
1715           double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1716           r *= r;
1717           
1718           node->myDir[iDir] = //aTgt[iDir];
1719             aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1720         }
1721 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1722 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1723 //  cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<"  |  "
1724 //    << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1725       }
1726     } // loop on iso nodes
1727   } // loop on isolines
1728 */
1729   // Find nodes to start computing UV from
1730
1731   list< TIsoNode* > startNodes;
1732   list< TIsoNode* >::iterator nIt = bndNodes.end();
1733   TIsoNode* node = *(--nIt);
1734   TIsoNode* prevNode = *(--nIt);
1735   for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1736   {
1737     TIsoNode* nextNode = *nIt;
1738     gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1739     gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1740     double initAngle = initTgt1.Angle( initTgt2 );
1741     double angle = node->myDir[0].Angle( node->myDir[1] );
1742     if ( reversed ) angle = -angle;
1743     if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1744       // find a close internal node
1745       TIsoNode* nClose = 0;
1746       list< TIsoNode* > testNodes;
1747       testNodes.push_back( node );
1748       list< TIsoNode* >::iterator it = testNodes.begin();
1749       for ( ; !nClose && it != testNodes.end(); it++ )
1750       {
1751         for (int i = 0; i < 4; i++ )
1752         {
1753           nClose = (*it)->myNext[ i ];
1754           if ( nClose ) {
1755             if ( !nClose->IsUVComputed() )
1756               break;
1757             else {
1758               testNodes.push_back( nClose );
1759               nClose = 0;
1760             }
1761           }
1762         }
1763       }
1764       startNodes.push_back( nClose );
1765 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1766 //   node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1767 //   "initAngle: " << initAngle << " angle: " << angle << endl;
1768 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1769 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1770 //    node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1771 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1772     }
1773     prevNode = node;
1774     node = nextNode;
1775   }
1776
1777   // Compute starting UV of internal nodes
1778
1779   list < TIsoNode* > internNodes;
1780   bool needIteration = true;
1781   if ( startNodes.empty() ) {
1782     MESSAGE( " Starting UV by compUVByIsoIntersection()");
1783     needIteration = false;
1784     map < double, TIsoLine >& isos = isoMap[ 0 ];
1785     map < double, TIsoLine >::iterator isoIt = isos.begin();
1786     for ( ; isoIt != isos.end(); isoIt++ )
1787     {
1788       TIsoLine & isoLine = (*isoIt).second;
1789       TIsoLine::iterator nIt = isoLine.begin();
1790       for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1791       {
1792         TIsoNode* node = *nIt;
1793         if ( !node->IsUVComputed() && node->IsMovable() ) {
1794           internNodes.push_back( node );
1795           //bool isDeformed;
1796           if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1797                                         node->myUV, needIteration ))
1798             node->myUV = node->myInitUV;
1799         }
1800       }
1801     }
1802     if ( needIteration )
1803       for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1804       {
1805         TIsoNode* node = *nIt, *nClose = 0;
1806         list< TIsoNode* > testNodes;
1807         testNodes.push_back( node );
1808         list< TIsoNode* >::iterator it = testNodes.begin();
1809         for ( ; !nClose && it != testNodes.end(); it++ )
1810         {
1811           for (int i = 0; i < 4; i++ )
1812           {
1813             nClose = (*it)->myNext[ i ];
1814             if ( nClose ) {
1815               if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1816                 break;
1817               else {
1818                 testNodes.push_back( nClose );
1819                 nClose = 0;
1820               }
1821             }
1822           }
1823         }
1824         startNodes.push_back( nClose );
1825       }
1826   }
1827
1828   double aMin[2], aMax[2], step[2];
1829   uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1830   double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1831   step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1832   step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1833 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1834
1835   for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1836   {
1837     TIsoNode* prevN[2], *node = *nIt;
1838     if ( node->IsUVComputed() || !node->IsMovable() )
1839       continue;
1840     gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1841     int nbComp = 0, nbPrev = 0;
1842     for ( iDir = 0; iDir < 2; iDir++ )
1843     {
1844       TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1845       TIsoNode* n = node->GetNext( iDir, 0 );
1846       if ( n->IsUVComputed() )
1847         prevNode1 = n;
1848       else
1849         startNodes.push_back( n );
1850       n = node->GetNext( iDir, 1 );
1851       if ( n->IsUVComputed() )
1852         prevNode2 = n;
1853       else
1854         startNodes.push_back( n );
1855       if ( !prevNode1 ) {
1856         prevNode1 = prevNode2;
1857         prevNode2 = 0;
1858       }
1859       if ( prevNode1 ) nbPrev++;
1860       if ( prevNode2 ) nbPrev++;
1861       if ( prevNode1 ) {
1862         gp_XY dir;
1863           double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1864           double par = node->myInitUV.Coord( 2 - iDir );
1865           bool isEnd = ( prevPar > par );
1866 //          dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1867         //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1868           TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1869           if ( !bndNode ) {
1870             MESSAGE("Why we are here?");
1871             continue;
1872           }
1873           gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1874           dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1875           dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1876         //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1877           //  cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1878           //     bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1879           //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1880             //" par: " << prevPar << endl;
1881           //           cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1882         //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1883         if ( prevNode2 ) {
1884           //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1885           gp_XY & uv1 = prevNode1->myUV;
1886           gp_XY & uv2 = prevNode2->myUV;
1887 //           dir = ( uv2 - uv1 );
1888 //           double len = dir.Modulus();
1889 //           if ( len > DBL_MIN )
1890 //             dir /= len * 0.5;
1891           double r = node->myRatio[ iDir ];
1892           newUV += uv1 * ( 1 - r ) + uv2 * r;
1893         }
1894         else {
1895           newUV += prevNode1->myUV + dir * step[ iDir ];
1896         }
1897         sumDir += dir;
1898         prevN[ iDir ] = prevNode1;
1899         nbComp++;
1900       }
1901     }
1902     if ( !nbComp ) continue;
1903     newUV /= nbComp;
1904     node->myUV = newUV;
1905     //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1906
1907     // check if a quadrangle is not distorted
1908     if ( nbPrev > 1 ) {
1909       //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1910       if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1911       //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1912       //  cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1913         node->myUV = newUV;
1914       }
1915     }
1916     internNodes.push_back( node );
1917   }
1918   
1919   // Move nodes
1920
1921   static int maxNbIter = 100;
1922 #ifdef DEB_COMPUVBYELASTICISOLINES
1923 //   maxNbIter++;
1924   bool useNbMoveNode = 0;
1925   static int maxNbNodeMove = 100;
1926   maxNbNodeMove++;
1927   int nbNodeMove = 0;
1928   if ( !useNbMoveNode )
1929     maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1930 #endif    
1931   double maxMove;
1932   int nbIter = 0;
1933   do {
1934     if ( !needIteration) break;
1935 #ifdef DEB_COMPUVBYELASTICISOLINES
1936     if ( nbIter >= maxNbIter ) break;
1937 #endif
1938     maxMove = 0.0;
1939     list < TIsoNode* >::iterator nIt = internNodes.begin();
1940     for ( ; nIt != internNodes.end(); nIt++  ) {
1941 #ifdef DEB_COMPUVBYELASTICISOLINES
1942       if (useNbMoveNode )
1943         cout << nbNodeMove <<" =================================================="<<endl;
1944 #endif
1945       TIsoNode * node = *nIt;
1946       // make lines
1947       //gp_Lin2d line[2];
1948       gp_XY loc[2];
1949       for ( iDir = 0; iDir < 2; iDir++ )
1950       {
1951         gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
1952         gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
1953         double r = node->myRatio[ iDir ];
1954         loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
1955 //         line[ iDir ].SetLocation( loc[ iDir ] );
1956 //         line[ iDir ].SetDirection( node->myDir[ iDir ] );
1957       }
1958       // define ratio
1959       bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
1960       double locR[2] = { 0, 0 };
1961       for ( iDir = 0; iDir < 2; iDir++ )
1962       {
1963         const int iCoord = 2 - iDir; // coord changing along an isoline
1964         TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1965         TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1966         if ( !bndNode1 || !bndNode2 ) {
1967           ok = false; break;
1968         }
1969         double par1 = bndNode1->myInitUV.Coord( iCoord );
1970         double par2 = node->myInitUV.Coord( iCoord );
1971         double par3 = bndNode2->myInitUV.Coord( iCoord );
1972         double r = ( par2 - par1 ) / ( par3 - par1 );
1973         r = Abs ( r - 0.5 ) * 2.0;  // [0,1] - distance from the middle
1974         locR[ iDir ] = ( 1 - r * r ) * 0.25;
1975       }
1976       //locR[0] = locR[1] = 0.25;
1977       // intersect the 2 lines and move a node
1978       //IntAna2d_AnaIntersection inter( line[0], line[1] );
1979       if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
1980       {
1981 //         double intR = 1 - locR[0] - locR[1];
1982 //         gp_XY newUV = inter.Point(1).Value().XY();
1983 //         if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
1984 //           newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
1985 //         else
1986 //           newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
1987         gp_XY newUV = 0.5 * ( loc[0] +  loc[1] );
1988         // avoid parallel isolines intersection
1989         checkQuads( node, newUV, reversed );
1990
1991         maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
1992         node->myUV = newUV;
1993       } // intersection found
1994 #ifdef DEB_COMPUVBYELASTICISOLINES
1995       if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
1996 #endif
1997     } // loop on internal nodes
1998 #ifdef DEB_COMPUVBYELASTICISOLINES
1999     if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2000 #endif
2001   } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2002
2003   MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2004
2005   if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2006     MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2007 #ifndef DEB_COMPUVBYELASTICISOLINES
2008     return false;
2009 #endif
2010   }
2011
2012   // Set computed UV to points
2013
2014   for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2015     TPoint* point = *pIt;
2016     //gp_XY oldUV = point->myUV;
2017     double minDist = DBL_MAX;
2018     list < TIsoNode >::iterator nIt = nodes.begin();
2019     for ( ; nIt != nodes.end(); nIt++ ) {
2020       double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2021       if ( dist < minDist ) {
2022         minDist = dist;
2023         point->myUV = (*nIt).myUV;
2024       }
2025     }
2026   }
2027       
2028     
2029   return true;
2030 }
2031
2032
2033 //=======================================================================
2034 //function : setFirstEdge
2035 //purpose  : choose the best first edge of theWire; return the summary distance
2036 //           between point UV computed by isolines intersection and
2037 //           eventual UV got from edge p-curves
2038 //=======================================================================
2039
2040 //#define DBG_SETFIRSTEDGE
2041 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2042 {
2043   int iE, nbEdges = theWire.size();
2044   if ( nbEdges == 1 )
2045     return 0;
2046
2047   // Transform UVs computed by iso to fit bnd box of a wire
2048
2049   // max nb of points on an edge
2050   int maxNbPnt = 0;
2051   int eID = theFirstEdgeID;
2052   for ( iE = 0; iE < nbEdges; iE++ )
2053     maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2054   
2055   // compute bnd boxes
2056   TopoDS_Face face = TopoDS::Face( myShape );
2057   Bnd_Box2d bndBox, eBndBox;
2058   eID = theFirstEdgeID;
2059   list< TopoDS_Edge >::iterator eIt;
2060   list< TPoint* >::iterator pIt;
2061   for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2062   {
2063     // UV by isos stored in TPoint.myXYZ
2064     list< TPoint* > & ePoints = getShapePoints( eID++ );
2065     for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2066       TPoint* p = (*pIt);
2067       bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2068     }
2069     // UV by an edge p-curve
2070     double f, l;
2071     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2072     double dU = ( l - f ) / ( maxNbPnt - 1 );
2073     for ( int i = 0; i < maxNbPnt; i++ )
2074       eBndBox.Add( C2d->Value( f + i * dU ));
2075   }
2076
2077   // transform UVs by isos
2078   double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2079   bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2080   eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2081 #ifdef DBG_SETFIRSTEDGE
2082   cout << "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2083     << eMinPar[1] << " - " << eMaxPar[1] << endl;
2084 #endif
2085   for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2086   {
2087     double dMin = eMinPar[i] - minPar[i];
2088     double dMax = eMaxPar[i] - maxPar[i];
2089     double dPar = maxPar[i] - minPar[i];
2090     eID = theFirstEdgeID;
2091     for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2092     {
2093       list< TPoint* > & ePoints = getShapePoints( eID++ );
2094       for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2095       {
2096         double par = (*pIt)->myXYZ.Coord( iC );
2097         double r = ( par - minPar[i] ) / dPar;
2098         par += ( 1 - r ) * dMin + r * dMax;
2099         (*pIt)->myXYZ.SetCoord( iC, par );
2100       }
2101     }
2102   }
2103
2104   TopoDS_Edge eBest;
2105   double minDist = DBL_MAX;
2106   for ( iE = 0 ; iE < nbEdges; iE++ )
2107   {
2108 #ifdef DBG_SETFIRSTEDGE
2109     cout << " VARIANT " << iE << endl;
2110 #endif
2111     // evaluate the distance between UV computed by the 2 methods:
2112     // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2113     double dist = 0;
2114     int eID = theFirstEdgeID;
2115     for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2116     {
2117       list< TPoint* > & ePoints = getShapePoints( eID++ );
2118       computeUVOnEdge( *eIt, ePoints );
2119       for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2120         TPoint* p = (*pIt);
2121         dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2122 #ifdef DBG_SETFIRSTEDGE
2123         cout << " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2124           p->myUV.X() << ", " << p->myUV.Y() << ") " << endl;
2125 #endif
2126       }
2127     }
2128 #ifdef DBG_SETFIRSTEDGE
2129     cout << "dist -- " << dist << endl;
2130 #endif
2131     if ( dist < minDist ) {
2132       minDist = dist;
2133       eBest = theWire.front();
2134     }
2135     // check variant with another first edge
2136     theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2137   }
2138   // put the best first edge to the theWire front
2139   if ( eBest != theWire.front() ) {
2140     eIt = find ( theWire.begin(), theWire.end(), eBest );
2141     theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2142   }
2143
2144   return minDist;
2145 }
2146
2147 //=======================================================================
2148 //function : sortSameSizeWires
2149 //purpose  : sort wires in theWireList from theFromWire until theToWire,
2150 //           the wires are set in the order to correspond to the order
2151 //           of boundaries; after sorting, edges in the wires are put
2152 //           in a good order, point UVs on edges are computed and points
2153 //           are appended to theEdgesPointsList
2154 //=======================================================================
2155
2156 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList &                theWireList,
2157                                        const TListOfEdgesList::iterator& theFromWire,
2158                                        const TListOfEdgesList::iterator& theToWire,
2159                                        const int                         theFirstEdgeID,
2160                                        list< list< TPoint* > >&          theEdgesPointsList )
2161 {
2162   TopoDS_Face F = TopoDS::Face( myShape );
2163   int iW, nbWires = 0;
2164   TListOfEdgesList::iterator wlIt = theFromWire;
2165   while ( wlIt++ != theToWire )
2166     nbWires++;
2167
2168   // Recompute key-point UVs by isolines intersection,
2169   // compute CG of key-points for each wire and bnd boxes of GCs
2170
2171   bool aBool;
2172   gp_XY orig( gp::Origin2d().XY() );
2173   vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2174   Bnd_Box2d bndBox, vBndBox;
2175   int eID = theFirstEdgeID;
2176   list< TopoDS_Edge >::iterator eIt;
2177   for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2178   {
2179     list< TopoDS_Edge > & wire = *wlIt;
2180     for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2181     {
2182       list< TPoint* > & ePoints = getShapePoints( eID++ );
2183       TPoint* p = ePoints.front();
2184       if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2185         MESSAGE("cant sortSameSizeWires()");
2186         return false;
2187       }
2188       gcVec[iW] += p->myUV;
2189       bndBox.Add( gp_Pnt2d( p->myUV ));
2190       TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2191       gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2192       vGcVec[iW] += vXY.XY();
2193       vBndBox.Add( vXY );
2194       // keep the computed UV to compare against by setFirstEdge()
2195       p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2196     }
2197     gcVec[iW] /= nbWires;
2198     vGcVec[iW] /= nbWires;
2199 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2200 //   " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2201   }
2202
2203   // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2204
2205   double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2206   bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2207   vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2208   for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2209   {
2210     double dMin = vMinPar[i] - minPar[i];
2211     double dMax = vMaxPar[i] - maxPar[i];
2212     double dPar = maxPar[i] - minPar[i];
2213     if ( Abs( dPar ) <= DBL_MIN )
2214       continue;
2215     for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2216       double par = gcVec[iW].Coord( iC );
2217       double r = ( par - minPar[i] ) / dPar;
2218       par += ( 1 - r ) * dMin + r * dMax;
2219       gcVec[iW].SetCoord( iC, par );
2220     }
2221   }
2222
2223   // Define boundary - wire correspondence by GC closeness
2224
2225   TListOfEdgesList tmpWList;
2226   tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2227   typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2228   TIntWirePosMap bndIndWirePosMap;
2229   vector< bool > bndFound( nbWires, false );
2230   for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2231   {
2232 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2233 //   " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2234     double minDist = DBL_MAX;
2235     gp_XY & wGc = vGcVec[ iW ];
2236     int bIndex;
2237     for ( int iB = 0; iB < nbWires; iB++ ) {
2238       if ( bndFound[ iB ] ) continue;
2239       double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2240       if ( dist < minDist ) {
2241         minDist = dist;
2242         bIndex = iB;
2243       }
2244     }
2245     bndFound[ bIndex ] = true;
2246     bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2247   }
2248
2249   // Treat each wire  
2250
2251   TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2252   eID = theFirstEdgeID;
2253   for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2254   {
2255     TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2256     list < TopoDS_Edge > & wire = ( *wirePos );
2257
2258     // choose the best first edge of a wire
2259     setFirstEdge( wire, eID );
2260     
2261     // compute eventual UV and fill theEdgesPointsList
2262     theEdgesPointsList.push_back( list< TPoint* >() );
2263     list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2264     for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2265     {
2266       list< TPoint* > & ePoints = getShapePoints( eID++ );
2267       computeUVOnEdge( *eIt, ePoints );
2268       edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2269     }
2270     // put wire back to theWireList
2271     wlIt = wirePos++;
2272     theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2273   }
2274
2275   return true;
2276 }
2277
2278 //=======================================================================
2279 //function : Apply
2280 //purpose  : Compute  nodes coordinates applying
2281 //           the loaded pattern to <theFace>. The first key-point
2282 //           will be mapped into <theVertexOnKeyPoint1>
2283 //=======================================================================
2284
2285 bool SMESH_Pattern::Apply (const TopoDS_Face&   theFace,
2286                            const TopoDS_Vertex& theVertexOnKeyPoint1,
2287                            const bool           theReverse)
2288 {
2289   MESSAGE(" ::Apply(face) " );
2290   TopoDS_Face face  = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2291   if ( !setShapeToMesh( face ))
2292     return false;
2293
2294   // find points on edges, it fills myNbKeyPntInBoundary
2295   if ( !findBoundaryPoints() )
2296     return false;
2297
2298   // Define the edges order so that the first edge starts at
2299   // theVertexOnKeyPoint1
2300
2301   list< TopoDS_Edge > eList;
2302   list< int >         nbVertexInWires;
2303   int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2304   if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2305   {
2306     MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2307     return setErrorCode( ERR_APPLF_BAD_VERTEX );
2308   }
2309   // check nb wires and edges
2310   list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2311   l1.sort(); l2.sort();
2312   if ( l1 != l2 )
2313   {
2314     MESSAGE( "Wrong nb vertices in wires" );
2315     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2316   }
2317
2318   // here shapes get IDs, for the outer wire IDs are OK
2319   list<TopoDS_Edge>::iterator elIt = eList.begin();
2320   for ( ; elIt != eList.end(); elIt++ ) {
2321     myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2322     if ( BRep_Tool::IsClosed( *elIt, theFace ) )
2323       myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));
2324   }
2325   int nbVertices = myShapeIDMap.Extent();
2326
2327   for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2328     myShapeIDMap.Add( *elIt );
2329
2330   myShapeIDMap.Add( face );
2331
2332   if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent()/* + nbSeamShapes*/ ) {
2333     MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2334     return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2335   }
2336
2337   // points on edges to be used for UV computation of in-face points
2338   list< list< TPoint* > > edgesPointsList;
2339   edgesPointsList.push_back( list< TPoint* >() );
2340   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2341   list< TPoint* >::iterator pIt;
2342
2343   // compute UV of points on the outer wire
2344   int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2345   for (iE = 0, elIt = eList.begin();
2346        iE < nbEdgesInOuterWire && elIt != eList.end();
2347        iE++, elIt++ )
2348   {
2349     list< TPoint* > & ePoints = getShapePoints( *elIt );
2350     // compute UV
2351     computeUVOnEdge( *elIt, ePoints );
2352     // collect on-edge points (excluding the last one)
2353     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2354   }
2355
2356   // If there are several wires, define the order of edges of inner wires:
2357   // compute UV of inner edge-points using 2 methods: the one for in-face points
2358   // and the one for on-edge points and then choose the best edge order
2359   // by the best correspondance of the 2 results
2360   if ( nbWires > 1 )
2361   {
2362     // compute UV of inner edge-points using the method for in-face points
2363     // and devide eList into a list of separate wires
2364     bool aBool;
2365     list< list< TopoDS_Edge > > wireList;
2366     list<TopoDS_Edge>::iterator eIt = elIt;
2367     list<int>::iterator nbEIt = nbVertexInWires.begin();
2368     for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2369     {
2370       int nbEdges = *nbEIt;
2371       wireList.push_back( list< TopoDS_Edge >() );
2372       list< TopoDS_Edge > & wire = wireList.back();
2373       for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2374       {
2375         list< TPoint* > & ePoints = getShapePoints( *eIt );
2376         pIt = ePoints.begin();
2377         for (  pIt++; pIt != ePoints.end(); pIt++ ) {
2378           TPoint* p = (*pIt);
2379           if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2380             MESSAGE("cant Apply(face)");
2381             return false;
2382           }
2383           // keep the computed UV to compare against by setFirstEdge()
2384           p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2385         }
2386         wire.push_back( *eIt );
2387       }
2388     }
2389     // remove inner edges from eList
2390     eList.erase( elIt, eList.end() );
2391
2392     // sort wireList by nb edges in a wire
2393     sortBySize< TopoDS_Edge > ( wireList );
2394
2395     // an ID of the first edge of a boundary
2396     int id1 = nbVertices + nbEdgesInOuterWire + 1;
2397 //     if ( nbSeamShapes > 0 )
2398 //       id1 += 2; // 2 vertices more
2399
2400     // find points - edge correspondence for wires of unique size,
2401     // edge order within a wire should be defined only
2402
2403     list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2404     while ( wlIt != wireList.end() )
2405     {
2406       list< TopoDS_Edge >& wire = (*wlIt);
2407       int nbEdges = wire.size();
2408       wlIt++;
2409       if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2410       {
2411         // choose the best first edge of a wire
2412         setFirstEdge( wire, id1 );
2413
2414         // compute eventual UV and collect on-edge points
2415         edgesPointsList.push_back( list< TPoint* >() );
2416         edgesPoints = & edgesPointsList.back();
2417         int eID = id1;
2418         for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2419         {
2420           list< TPoint* > & ePoints = getShapePoints( eID++ );
2421           computeUVOnEdge( *eIt, ePoints );
2422           edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2423         }
2424       }
2425       id1 += nbEdges;
2426     }
2427
2428     // find boundary - wire correspondence for several wires of same size
2429     
2430     id1 = nbVertices + nbEdgesInOuterWire + 1;
2431     wlIt = wireList.begin();
2432     while ( wlIt != wireList.end() )
2433     {
2434       int nbSameSize = 0, nbEdges = (*wlIt).size();
2435       list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2436       wlIt2++;
2437       while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2438         nbSameSize++;
2439         wlIt2++;
2440       }
2441       if ( nbSameSize > 0 )
2442         if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2443           return false;
2444       wlIt = wlIt2;
2445       id1 += nbEdges * ( nbSameSize + 1 );
2446     }
2447
2448     // add well-ordered edges to eList
2449     
2450     for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2451     {
2452       list< TopoDS_Edge >& wire = (*wlIt);
2453       eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2454     }
2455
2456     // re-fill myShapeIDMap - all shapes get good IDs
2457
2458     myShapeIDMap.Clear();
2459     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2460       myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2461     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2462       myShapeIDMap.Add( *elIt );
2463     myShapeIDMap.Add( face );
2464     
2465   } // there are inner wires
2466
2467   // Compute XYZ of on-edge points
2468
2469   TopLoc_Location loc;
2470   for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2471   {
2472     BRepAdaptor_Curve C3d( *elIt );
2473     list< TPoint* > & ePoints = getShapePoints( iE++ );
2474     pIt = ePoints.begin();
2475     for ( pIt++; pIt != ePoints.end(); pIt++ )
2476     {
2477       TPoint* point = *pIt;
2478       point->myXYZ = C3d.Value( point->myU );
2479     }
2480   }
2481
2482   // Compute UV and XYZ of in-face points
2483
2484   // try to use a simple algo
2485   list< TPoint* > & fPoints = getShapePoints( face );
2486   bool isDeformed = false;
2487   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2488     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2489                                   (*pIt)->myUV, isDeformed )) {
2490       MESSAGE("cant Apply(face)");
2491       return false;
2492     }
2493   // try to use a complex algo if it is a difficult case
2494   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2495   {
2496     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2497       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2498                                     (*pIt)->myUV, isDeformed )) {
2499         MESSAGE("cant Apply(face)");
2500         return false;
2501       }
2502   }
2503
2504   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2505   const gp_Trsf & aTrsf = loc.Transformation();
2506   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2507   {
2508     TPoint * point = *pIt;
2509     point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2510     if ( !loc.IsIdentity() )
2511       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2512   }
2513
2514   myIsComputed = true;
2515
2516   return setErrorCode( ERR_OK );
2517 }
2518
2519 //=======================================================================
2520 //function : Apply
2521 //purpose  : Compute nodes coordinates applying
2522 //           the loaded pattern to <theFace>. The first key-point
2523 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2524 //=======================================================================
2525
2526 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2527                            const int            theNodeIndexOnKeyPoint1,
2528                            const bool           theReverse)
2529 {
2530 //  MESSAGE(" ::Apply(MeshFace) " );
2531
2532   if ( !IsLoaded() ) {
2533     MESSAGE( "Pattern not loaded" );
2534     return setErrorCode( ERR_APPL_NOT_LOADED );
2535   }
2536
2537   // check nb of nodes
2538   if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2539     MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2540     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2541   }
2542
2543   // find points on edges, it fills myNbKeyPntInBoundary
2544   if ( !findBoundaryPoints() )
2545     return false;
2546
2547   // check that there are no holes in a pattern
2548   if (myNbKeyPntInBoundary.size() > 1 ) {
2549     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2550   }
2551
2552   // Define the nodes order
2553
2554   list< const SMDS_MeshNode* > nodes;
2555   list< const SMDS_MeshNode* >::iterator n = nodes.end();
2556   SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2557   int iSub = 0;
2558   while ( noIt->more() ) {
2559     const SMDS_MeshNode* node = smdsNode( noIt->next() );
2560     nodes.push_back( node );
2561     if ( iSub++ == theNodeIndexOnKeyPoint1 )
2562       n = --nodes.end();
2563   }
2564   if ( n != nodes.end() ) {
2565     if ( theReverse ) {
2566       if ( n != --nodes.end() )
2567         nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2568       nodes.reverse();
2569     }
2570     else if ( n != nodes.begin() )
2571       nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2572   }
2573   list< gp_XYZ > xyzList;
2574   myOrderedNodes.resize( theFace->NbNodes() );
2575   for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2576     xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2577     myOrderedNodes[ iSub++] = *n;
2578   }
2579
2580   // Define a face plane
2581
2582   list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2583   gp_Pnt P ( *xyzIt++ );
2584   gp_Vec Vx( P, *xyzIt++ ), N;
2585   do {
2586     N = Vx ^ gp_Vec( P, *xyzIt++ );
2587   } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2588   if ( N.SquareMagnitude() <= DBL_MIN )
2589     return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2590   gp_Ax2 pos( P, N, Vx );
2591
2592   // Compute UV of key-points on a plane
2593   for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2594   {
2595     gp_Vec vec ( pos.Location(), *xyzIt );
2596     TPoint* p = getShapePoints( iSub ).front();
2597     p->myUV.SetX( vec * pos.XDirection() );
2598     p->myUV.SetY( vec * pos.YDirection() );
2599     p->myXYZ = *xyzIt;
2600   }
2601
2602   // points on edges to be used for UV computation of in-face points
2603   list< list< TPoint* > > edgesPointsList;
2604   edgesPointsList.push_back( list< TPoint* >() );
2605   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2606   list< TPoint* >::iterator pIt;
2607
2608   // compute UV and XYZ of points on edges
2609
2610   for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2611   {
2612     gp_XYZ& xyz1 = *xyzIt++;
2613     gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2614     
2615     list< TPoint* > & ePoints = getShapePoints( iSub );
2616     ePoints.back()->myInitU = 1.0;
2617     list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2618     while ( *pIt != ePoints.back() )
2619     {
2620       TPoint* p = *pIt++;
2621       p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2622       gp_Vec vec ( pos.Location(), p->myXYZ );
2623       p->myUV.SetX( vec * pos.XDirection() );
2624       p->myUV.SetY( vec * pos.YDirection() );
2625     }
2626     // collect on-edge points (excluding the last one)
2627     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2628   }
2629
2630   // Compute UV and XYZ of in-face points
2631
2632   // try to use a simple algo to compute UV
2633   list< TPoint* > & fPoints = getShapePoints( iSub );
2634   bool isDeformed = false;
2635   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2636     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2637                                   (*pIt)->myUV, isDeformed )) {
2638       MESSAGE("cant Apply(face)");
2639       return false;
2640     }
2641   // try to use a complex algo if it is a difficult case
2642   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2643   {
2644     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2645       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2646                                     (*pIt)->myUV, isDeformed )) {
2647         MESSAGE("cant Apply(face)");
2648         return false;
2649       }
2650   }
2651
2652   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2653   {
2654     (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2655   }
2656
2657   myIsComputed = true;
2658
2659   return setErrorCode( ERR_OK );
2660 }
2661
2662 //=======================================================================
2663 //function : Apply
2664 //purpose  : Compute nodes coordinates applying
2665 //           the loaded pattern to <theFace>. The first key-point
2666 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2667 //=======================================================================
2668
2669 bool SMESH_Pattern::Apply (SMESH_Mesh*          theMesh,
2670                            const SMDS_MeshFace* theFace,
2671                            const TopoDS_Shape&  theSurface,
2672                            const int            theNodeIndexOnKeyPoint1,
2673                            const bool           theReverse)
2674 {
2675 //  MESSAGE(" ::Apply(MeshFace) " );
2676   if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2677     return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2678   }
2679   const TopoDS_Face& face = TopoDS::Face( theSurface );
2680   TopLoc_Location loc;
2681   Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2682   const gp_Trsf & aTrsf = loc.Transformation();
2683
2684   if ( !IsLoaded() ) {
2685     MESSAGE( "Pattern not loaded" );
2686     return setErrorCode( ERR_APPL_NOT_LOADED );
2687   }
2688
2689   // check nb of nodes
2690   if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2691     MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2692     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2693   }
2694
2695   // find points on edges, it fills myNbKeyPntInBoundary
2696   if ( !findBoundaryPoints() )
2697     return false;
2698
2699   // check that there are no holes in a pattern
2700   if (myNbKeyPntInBoundary.size() > 1 ) {
2701     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2702   }
2703
2704   // Define the nodes order
2705
2706   list< const SMDS_MeshNode* > nodes;
2707   list< const SMDS_MeshNode* >::iterator n = nodes.end();
2708   SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2709   int iSub = 0;
2710   while ( noIt->more() ) {
2711     const SMDS_MeshNode* node = smdsNode( noIt->next() );
2712     nodes.push_back( node );
2713     if ( iSub++ == theNodeIndexOnKeyPoint1 )
2714       n = --nodes.end();
2715   }
2716   if ( n != nodes.end() ) {
2717     if ( theReverse ) {
2718       if ( n != --nodes.end() )
2719         nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2720       nodes.reverse();
2721     }
2722     else if ( n != nodes.begin() )
2723       nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2724   }
2725
2726   // find a node not on a seam edge, if necessary
2727   SMESH_MesherHelper helper( *theMesh );
2728   helper.SetSubShape( theSurface );
2729   const SMDS_MeshNode* inFaceNode = 0;
2730   if ( helper.GetNodeUVneedInFaceNode() )
2731   {
2732     SMESH_MeshEditor editor( theMesh );
2733     for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2734       int shapeID = editor.FindShape( *n );
2735       if ( !shapeID )
2736         return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2737       if ( !helper.IsSeamShape( shapeID ))
2738         inFaceNode = *n;
2739     }
2740   }
2741
2742   // Set UV of key-points (i.e. of nodes of theFace )
2743   vector< gp_XY > keyUV( theFace->NbNodes() );
2744   myOrderedNodes.resize( theFace->NbNodes() );
2745   for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2746   {
2747     TPoint* p = getShapePoints( iSub ).front();
2748     p->myUV  = helper.GetNodeUV( face, *n, inFaceNode );
2749     p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2750
2751     keyUV[ iSub-1 ] = p->myUV;
2752     myOrderedNodes[ iSub-1 ] = *n;
2753   }
2754
2755   // points on edges to be used for UV computation of in-face points
2756   list< list< TPoint* > > edgesPointsList;
2757   edgesPointsList.push_back( list< TPoint* >() );
2758   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2759   list< TPoint* >::iterator pIt;
2760
2761   // compute UV and XYZ of points on edges
2762
2763   for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2764   {
2765     gp_XY& uv1 = keyUV[ i ];
2766     gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2767
2768     list< TPoint* > & ePoints = getShapePoints( iSub );
2769     ePoints.back()->myInitU = 1.0;
2770     list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2771     while ( *pIt != ePoints.back() )
2772     {
2773       TPoint* p = *pIt++;
2774       p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2775       p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2776       if ( !loc.IsIdentity() )
2777         aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2778     }
2779     // collect on-edge points (excluding the last one)
2780     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2781   }
2782
2783   // Compute UV and XYZ of in-face points
2784
2785   // try to use a simple algo to compute UV
2786   list< TPoint* > & fPoints = getShapePoints( iSub );
2787   bool isDeformed = false;
2788   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2789     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2790                                   (*pIt)->myUV, isDeformed )) {
2791       MESSAGE("cant Apply(face)");
2792       return false;
2793     }
2794   // try to use a complex algo if it is a difficult case
2795   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2796   {
2797     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2798       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2799                                     (*pIt)->myUV, isDeformed )) {
2800         MESSAGE("cant Apply(face)");
2801         return false;
2802       }
2803   }
2804
2805   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2806   {
2807     TPoint * point = *pIt;
2808     point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2809     if ( !loc.IsIdentity() )
2810       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2811   }
2812
2813   myIsComputed = true;
2814
2815   return setErrorCode( ERR_OK );
2816 }
2817
2818 //=======================================================================
2819 //function : undefinedXYZ
2820 //purpose  : 
2821 //=======================================================================
2822
2823 static const gp_XYZ& undefinedXYZ()
2824 {
2825   static gp_XYZ xyz( 1.e100, 0., 0. );
2826   return xyz;
2827 }
2828
2829 //=======================================================================
2830 //function : isDefined
2831 //purpose  : 
2832 //=======================================================================
2833
2834 inline static bool isDefined(const gp_XYZ& theXYZ)
2835 {
2836   return theXYZ.X() < 1.e100;
2837 }
2838
2839 //=======================================================================
2840 //function : Apply
2841 //purpose  : Compute nodes coordinates applying
2842 //           the loaded pattern to <theFaces>. The first key-point
2843 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2844 //=======================================================================
2845
2846 bool SMESH_Pattern::Apply (SMESH_Mesh*                     theMesh,
2847                            std::set<const SMDS_MeshFace*>& theFaces,
2848                            const int                       theNodeIndexOnKeyPoint1,
2849                            const bool                      theReverse)
2850 {
2851   MESSAGE(" ::Apply(set<MeshFace>) " );
2852
2853   if ( !IsLoaded() ) {
2854     MESSAGE( "Pattern not loaded" );
2855     return setErrorCode( ERR_APPL_NOT_LOADED );
2856   }
2857
2858   // find points on edges, it fills myNbKeyPntInBoundary
2859   if ( !findBoundaryPoints() )
2860     return false;
2861
2862   // check that there are no holes in a pattern
2863   if (myNbKeyPntInBoundary.size() > 1 ) {
2864     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2865   }
2866
2867   myShape.Nullify();
2868   myXYZ.clear();
2869   myElemXYZIDs.clear();
2870   myXYZIdToNodeMap.clear();
2871   myElements.clear();
2872   myIdsOnBoundary.clear();
2873   myReverseConnectivity.clear();
2874
2875   myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2876   myElements.reserve( theFaces.size() );
2877
2878   // to find point index
2879   map< TPoint*, int > pointIndex;
2880   for ( int i = 0; i < myPoints.size(); i++ )
2881     pointIndex.insert( make_pair( & myPoints[ i ], i ));
2882
2883   int ind1 = 0; // lowest point index for a face
2884
2885   // meshed geometry
2886   TopoDS_Shape shape;
2887 //   int          shapeID = 0;
2888 //   SMESH_MeshEditor editor( theMesh ); 
2889
2890   // apply to each face in theFaces set
2891   set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2892   for ( ; face != theFaces.end(); ++face )
2893   {
2894 //     int curShapeId = editor.FindShape( *face );
2895 //     if ( curShapeId != shapeID ) {
2896 //       if ( curShapeId )
2897 //         shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2898 //       else
2899 //         shape.Nullify();
2900 //       shapeID = curShapeId;
2901 //     }
2902     bool ok;
2903     if ( shape.IsNull() )
2904       ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2905     else
2906       ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2907     if ( !ok ) {
2908       MESSAGE( "Failed on " << *face );
2909       continue;
2910     }
2911     myElements.push_back( *face );
2912
2913     // store computed points belonging to elements
2914     list< TElemDef >::iterator ll = myElemPointIDs.begin();
2915     for ( ; ll != myElemPointIDs.end(); ++ll )
2916     {
2917       myElemXYZIDs.push_back(TElemDef());
2918       TElemDef& xyzIds = myElemXYZIDs.back();
2919       TElemDef& pIds = *ll;
2920       for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
2921         int pIndex = *id + ind1;
2922         xyzIds.push_back( pIndex );
2923         myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
2924         myReverseConnectivity[ pIndex ].push_back( & xyzIds );
2925       }
2926     }
2927     // put points on links to myIdsOnBoundary,
2928     // they will be used to sew new elements on adjacent refined elements
2929     int nbNodes = (*face)->NbNodes(), eID = nbNodes + 1;
2930     for ( int i = 0; i < nbNodes; i++ )
2931     {
2932       list< TPoint* > & linkPoints = getShapePoints( eID++ );
2933       const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
2934       const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
2935       // make a link and a node set
2936       TNodeSet linkSet, node1Set;
2937       linkSet.insert( n1 );
2938       linkSet.insert( n2 );
2939       node1Set.insert( n1 );
2940       list< TPoint* >::iterator p = linkPoints.begin();
2941       {
2942         // map the first link point to n1
2943         int nId = pointIndex[ *p ] + ind1;
2944         myXYZIdToNodeMap[ nId ] = n1;
2945         list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
2946         groups.push_back(list< int > ());
2947         groups.back().push_back( nId );
2948       }
2949       // add the linkSet to the map
2950       list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
2951       groups.push_back(list< int > ());
2952       list< int >& indList = groups.back();
2953       // add points to the map excluding the end points
2954       for ( p++; *p != linkPoints.back(); p++ )
2955         indList.push_back( pointIndex[ *p ] + ind1 );
2956     }
2957     ind1 += myPoints.size();
2958   }
2959
2960   return !myElemXYZIDs.empty();
2961 }
2962
2963 //=======================================================================
2964 //function : Apply
2965 //purpose  : Compute nodes coordinates applying
2966 //           the loaded pattern to <theVolumes>. The (0,0,0) key-point
2967 //           will be mapped into <theNode000Index>-th node. The
2968 //           (0,0,1) key-point will be mapped into <theNode000Index>-th
2969 //           node.
2970 //=======================================================================
2971
2972 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
2973                            const int                          theNode000Index,
2974                            const int                          theNode001Index)
2975 {
2976   MESSAGE(" ::Apply(set<MeshVolumes>) " );
2977
2978   if ( !IsLoaded() ) {
2979     MESSAGE( "Pattern not loaded" );
2980     return setErrorCode( ERR_APPL_NOT_LOADED );
2981   }
2982
2983    // bind ID to points
2984   if ( !findBoundaryPoints() )
2985     return false;
2986
2987   // check that there are no holes in a pattern
2988   if (myNbKeyPntInBoundary.size() > 1 ) {
2989     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2990   }
2991
2992   myShape.Nullify();
2993   myXYZ.clear();
2994   myElemXYZIDs.clear();
2995   myXYZIdToNodeMap.clear();
2996   myElements.clear();
2997   myIdsOnBoundary.clear();
2998   myReverseConnectivity.clear();
2999
3000   myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3001   myElements.reserve( theVolumes.size() );
3002
3003   // to find point index
3004   map< TPoint*, int > pointIndex;
3005   for ( int i = 0; i < myPoints.size(); i++ )
3006     pointIndex.insert( make_pair( & myPoints[ i ], i ));
3007
3008   int ind1 = 0; // lowest point index for an element
3009
3010   // apply to each element in theVolumes set
3011   set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3012   for ( ; vol != theVolumes.end(); ++vol )
3013   {
3014     if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3015       MESSAGE( "Failed on " << *vol );
3016       continue;
3017     }
3018     myElements.push_back( *vol );
3019
3020     // store computed points belonging to elements
3021     list< TElemDef >::iterator ll = myElemPointIDs.begin();
3022     for ( ; ll != myElemPointIDs.end(); ++ll )
3023     {
3024       myElemXYZIDs.push_back(TElemDef());
3025       TElemDef& xyzIds = myElemXYZIDs.back();
3026       TElemDef& pIds = *ll;
3027       for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3028         int pIndex = *id + ind1;
3029         xyzIds.push_back( pIndex );
3030         myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3031         myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3032       }
3033     }
3034     // put points on edges and faces to myIdsOnBoundary,
3035     // they will be used to sew new elements on adjacent refined elements
3036     for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3037     {
3038       // make a set of sub-points
3039       TNodeSet subNodes;
3040       vector< int > subIDs;
3041       if ( SMESH_Block::IsVertexID( Id )) {
3042         subNodes.insert( myOrderedNodes[ Id - 1 ]);
3043       }
3044       else if ( SMESH_Block::IsEdgeID( Id )) {
3045         SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3046         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3047         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3048       }
3049       else {
3050         SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3051         int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3052         SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3053         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3054         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3055         SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3056         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3057         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3058       }
3059       // add points
3060       list< TPoint* > & points = getShapePoints( Id );
3061       list< TPoint* >::iterator p = points.begin();
3062       list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3063       groups.push_back(list< int > ());
3064       list< int >& indList = groups.back();
3065       for ( ; p != points.end(); p++ )
3066         indList.push_back( pointIndex[ *p ] + ind1 );
3067       if ( subNodes.size() == 1 ) // vertex case
3068         myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3069     }
3070     ind1 += myPoints.size();
3071   }
3072
3073   return !myElemXYZIDs.empty();
3074 }
3075
3076 //=======================================================================
3077 //function : Load
3078 //purpose  : Create a pattern from the mesh built on <theBlock>
3079 //=======================================================================
3080
3081 bool SMESH_Pattern::Load (SMESH_Mesh*         theMesh,
3082                           const TopoDS_Shell& theBlock)
3083 {
3084   MESSAGE(" ::Load(volume) " );
3085   Clear();
3086   myIs2D = false;
3087   SMESHDS_SubMesh * aSubMesh;
3088
3089   // load shapes in myShapeIDMap
3090   SMESH_Block block;
3091   TopoDS_Vertex v1, v2;
3092   if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3093     return setErrorCode( ERR_LOADV_BAD_SHAPE );
3094
3095   // count nodes
3096   int nbNodes = 0, shapeID;
3097   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3098   {
3099     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3100     aSubMesh = getSubmeshWithElements( theMesh, S );
3101     if ( aSubMesh )
3102       nbNodes += aSubMesh->NbNodes();
3103   }
3104   myPoints.resize( nbNodes );
3105
3106   // load U of points on edges
3107   TNodePointIDMap nodePointIDMap;
3108   int iPoint = 0;
3109   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3110   {
3111     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3112     list< TPoint* > & shapePoints = getShapePoints( shapeID );
3113     aSubMesh = getSubmeshWithElements( theMesh, S );
3114     if ( ! aSubMesh ) continue;
3115     SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3116     if ( !nIt->more() ) continue;
3117
3118       // store a node and a point
3119     while ( nIt->more() ) {
3120       const SMDS_MeshNode* node = smdsNode( nIt->next() );
3121       nodePointIDMap.insert( make_pair( node, iPoint ));
3122       if ( block.IsVertexID( shapeID ))
3123         myKeyPointIDs.push_back( iPoint );
3124       TPoint* p = & myPoints[ iPoint++ ];
3125       shapePoints.push_back( p );
3126       p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3127       p->myInitXYZ.SetCoord( 0,0,0 );
3128     }
3129     list< TPoint* >::iterator pIt = shapePoints.begin();
3130
3131     // compute init XYZ
3132     switch ( S.ShapeType() )
3133     {
3134     case TopAbs_VERTEX:
3135     case TopAbs_EDGE: {
3136
3137       for ( ; pIt != shapePoints.end(); pIt++ ) {
3138         double * coef = block.GetShapeCoef( shapeID );
3139         for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3140           if ( coef[ iCoord - 1] > 0 )
3141             (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3142       }
3143       if ( S.ShapeType() == TopAbs_VERTEX )
3144         break;
3145
3146       const TopoDS_Edge& edge = TopoDS::Edge( S );
3147       double f,l;
3148       BRep_Tool::Range( edge, f, l );
3149       int iCoord     = SMESH_Block::GetCoordIndOnEdge( shapeID );
3150       bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3151       pIt = shapePoints.begin();
3152       nIt = aSubMesh->GetNodes();
3153       for ( ; nIt->more(); pIt++ )
3154       {
3155         const SMDS_MeshNode* node = smdsNode( nIt->next() );
3156         const SMDS_EdgePosition* epos =
3157           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
3158         double u = ( epos->GetUParameter() - f ) / ( l - f );
3159         (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3160       }
3161       break;
3162     }
3163     default:
3164       for ( ; pIt != shapePoints.end(); pIt++ )
3165       {
3166         if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3167           MESSAGE( "!block.ComputeParameters()" );
3168           return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3169         }
3170       }
3171     }
3172   } // loop on block sub-shapes
3173
3174   // load elements
3175
3176   aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3177   if ( aSubMesh )
3178   {
3179     SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3180     while ( elemIt->more() ) {
3181       SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
3182       myElemPointIDs.push_back( TElemDef() );
3183       TElemDef& elemPoints = myElemPointIDs.back();
3184       while ( nIt->more() )
3185         elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
3186     }
3187   }
3188
3189   myIsBoundaryPointsFound = true;
3190
3191   return setErrorCode( ERR_OK );
3192 }
3193
3194 //=======================================================================
3195 //function : getSubmeshWithElements
3196 //purpose  : return submesh containing elements bound to theBlock in theMesh
3197 //=======================================================================
3198
3199 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh*         theMesh,
3200                                                         const TopoDS_Shape& theShape)
3201 {
3202   SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3203   if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3204     return aSubMesh;
3205
3206   if ( theShape.ShapeType() == TopAbs_SHELL )
3207   {
3208     // look for submesh of VOLUME
3209     TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3210     for (; it.More(); it.Next()) {
3211       aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3212       if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3213         return aSubMesh;
3214     }
3215   }
3216   return 0;
3217 }
3218
3219
3220 //=======================================================================
3221 //function : Apply
3222 //purpose  : Compute nodes coordinates applying
3223 //           the loaded pattern to <theBlock>. The (0,0,0) key-point
3224 //           will be mapped into <theVertex000>. The (0,0,1)
3225 //           fifth key-point will be mapped into <theVertex001>.
3226 //=======================================================================
3227
3228 bool SMESH_Pattern::Apply (const TopoDS_Shell&  theBlock,
3229                            const TopoDS_Vertex& theVertex000,
3230                            const TopoDS_Vertex& theVertex001)
3231 {
3232   MESSAGE(" ::Apply(volume) " );
3233
3234   if (!findBoundaryPoints()     || // bind ID to points
3235       !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3236     return false;
3237
3238   SMESH_Block block;  // bind ID to shape
3239   if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3240     return setErrorCode( ERR_APPLV_BAD_SHAPE );
3241
3242   // compute XYZ of points on shapes
3243
3244   for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3245   {
3246     list< TPoint* > & shapePoints = getShapePoints( shapeID );
3247     list< TPoint* >::iterator pIt = shapePoints.begin();
3248     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3249     switch ( S.ShapeType() )
3250     {
3251     case TopAbs_VERTEX: {
3252
3253       for ( ; pIt != shapePoints.end(); pIt++ )
3254         block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3255       break;
3256     }
3257     case TopAbs_EDGE: {
3258
3259       for ( ; pIt != shapePoints.end(); pIt++ )
3260         block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3261       break;
3262     }
3263     case TopAbs_FACE: {
3264
3265       for ( ; pIt != shapePoints.end(); pIt++ )
3266         block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3267       break;
3268     }
3269     default:
3270       for ( ; pIt != shapePoints.end(); pIt++ )
3271         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3272     }
3273   } // loop on block sub-shapes
3274
3275   myIsComputed = true;
3276
3277   return setErrorCode( ERR_OK );
3278 }
3279
3280 //=======================================================================
3281 //function : Apply
3282 //purpose  : Compute nodes coordinates applying
3283 //           the loaded pattern to <theVolume>. The (0,0,0) key-point
3284 //           will be mapped into <theNode000Index>-th node. The
3285 //           (0,0,1) key-point will be mapped into <theNode000Index>-th
3286 //           node.
3287 //=======================================================================
3288
3289 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3290                            const int              theNode000Index,
3291                            const int              theNode001Index)
3292 {
3293   //MESSAGE(" ::Apply(MeshVolume) " );
3294
3295   if (!findBoundaryPoints()) // bind ID to points
3296     return false;
3297
3298   SMESH_Block block;  // bind ID to shape
3299   if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3300     return setErrorCode( ERR_APPLV_BAD_SHAPE );
3301   // compute XYZ of points on shapes
3302
3303   for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3304   {
3305     list< TPoint* > & shapePoints = getShapePoints( ID );
3306     list< TPoint* >::iterator pIt = shapePoints.begin();
3307
3308     if ( block.IsVertexID( ID ))
3309       for ( ; pIt != shapePoints.end(); pIt++ ) {
3310         block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3311       }
3312     else if ( block.IsEdgeID( ID ))
3313       for ( ; pIt != shapePoints.end(); pIt++ ) {
3314         block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3315       }
3316     else if ( block.IsFaceID( ID ))
3317       for ( ; pIt != shapePoints.end(); pIt++ ) {
3318         block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3319       }
3320     else
3321       for ( ; pIt != shapePoints.end(); pIt++ )
3322         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3323   } // loop on block sub-shapes
3324
3325   myIsComputed = true;
3326
3327   return setErrorCode( ERR_OK );
3328 }
3329
3330 //=======================================================================
3331 //function : mergePoints
3332 //purpose  : Merge XYZ on edges and/or faces.
3333 //=======================================================================
3334
3335 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3336 {
3337   map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3338   for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3339   {
3340     list<list< int > >& groups = idListIt->second;
3341     if ( groups.size() < 2 )
3342       continue;
3343
3344     // find tolerance
3345     const TNodeSet& nodes = idListIt->first;
3346     double tol2 = 1.e-10;
3347     if ( nodes.size() > 1 ) {
3348       Bnd_Box box;
3349       TNodeSet::const_iterator n = nodes.begin();
3350       for ( ; n != nodes.end(); ++n )
3351         box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3352       double x, y, z, X, Y, Z;
3353       box.Get( x, y, z, X, Y, Z );
3354       gp_Pnt p( x, y, z ), P( X, Y, Z );
3355       tol2 = 1.e-4 * p.SquareDistance( P );
3356     }
3357
3358     // to unite groups on link
3359     bool unite = ( uniteGroups && nodes.size() == 2 );
3360     map< double, int > distIndMap;
3361     const SMDS_MeshNode* node = *nodes.begin();
3362     gp_Pnt P( node->X(), node->Y(), node->Z() );
3363
3364     // compare points, replace indices
3365
3366     list< int >::iterator ind1, ind2;
3367     list< list< int > >::iterator grpIt1, grpIt2;
3368     for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3369     {
3370       list< int >& indices1 = *grpIt1;
3371       grpIt2 = grpIt1;
3372       for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3373       {
3374         list< int >& indices2 = *grpIt2;
3375         for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3376         {
3377           gp_XYZ& p1 = myXYZ[ *ind1 ];
3378           ind2 = indices2.begin();
3379           while ( ind2 != indices2.end() )
3380           {
3381             gp_XYZ& p2 = myXYZ[ *ind2 ];
3382             //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3383             if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3384             {
3385               ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3386               list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3387               list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3388               for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3389               {
3390                 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3391                 myXYZ[ *ind2 ] = undefinedXYZ();
3392                 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3393               }
3394               ind2 = indices2.erase( ind2 );
3395             }
3396             else
3397               ind2++;
3398           }
3399         }
3400       }
3401       if ( unite ) { // sort indices using distIndMap
3402         for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3403         {
3404           ASSERT( isDefined( myXYZ[ *ind1 ] ));
3405           double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3406           distIndMap.insert( make_pair( dist, *ind1 ));
3407         }
3408       }
3409     }
3410     if ( unite ) { // put all sorted indices into the first group
3411       list< int >& g = groups.front();
3412       g.clear();
3413       map< double, int >::iterator dist_ind = distIndMap.begin();
3414       for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3415         g.push_back( dist_ind->second );
3416     }
3417   } // loop on myIdsOnBoundary
3418 }
3419
3420 //=======================================================================
3421 //function : makePolyElements
3422 //purpose  : prepare intermediate data to create Polygons and Polyhedrons
3423 //=======================================================================
3424
3425 void SMESH_Pattern::
3426   makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3427                    const bool                            toCreatePolygons,
3428                    const bool                            toCreatePolyedrs)
3429 {
3430   myPolyElemXYZIDs.clear();
3431   myPolyElems.clear();
3432   myPolyElems.reserve( myIdsOnBoundary.size() );
3433
3434   // make a set of refined elements
3435   TIDSortedElemSet avoidSet, elemSet;
3436   std::vector<const SMDS_MeshElement*>::iterator itv =  myElements.begin();
3437   for(; itv!=myElements.end(); itv++) {
3438     const SMDS_MeshElement* el = (*itv);
3439     avoidSet.insert( el );
3440   }
3441   //avoidSet.insert( myElements.begin(), myElements.end() );
3442
3443   map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3444
3445   if ( toCreatePolygons )
3446   {
3447     int lastFreeId = myXYZ.size();
3448
3449     // loop on links of refined elements
3450     indListIt = myIdsOnBoundary.begin();
3451     for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3452     {
3453       const TNodeSet & linkNodes = indListIt->first;
3454       if ( linkNodes.size() != 2 )
3455         continue; // skip face
3456       const SMDS_MeshNode* n1 = * linkNodes.begin();
3457       const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3458
3459       list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3460       if ( idGroups.empty() || idGroups.front().empty() )
3461         continue;
3462
3463       // find not refined face having n1-n2 link
3464
3465       while (true)
3466       {
3467         const SMDS_MeshElement* face =
3468           SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3469         if ( face )
3470         {
3471           avoidSet.insert ( face );
3472           myPolyElems.push_back( face );
3473
3474           // some links of <face> are split;
3475           // make list of xyz for <face>
3476           myPolyElemXYZIDs.push_back(TElemDef());
3477           TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3478           // loop on links of a <face>
3479           SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3480           int i = 0, nbNodes = face->NbNodes();
3481           vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3482           while ( nIt->more() )
3483             nodes[ i++ ] = smdsNode( nIt->next() );
3484           nodes[ i ] = nodes[ 0 ];
3485           for ( i = 0; i < nbNodes; ++i )
3486           {
3487             // look for point mapped on a link
3488             TNodeSet faceLinkNodes;
3489             faceLinkNodes.insert( nodes[ i ] );
3490             faceLinkNodes.insert( nodes[ i + 1 ] );
3491             if ( faceLinkNodes == linkNodes )
3492               nn_IdList = indListIt;
3493             else
3494               nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3495             // add face point ids
3496             faceNodeIds.push_back( ++lastFreeId );
3497             myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3498             if ( nn_IdList != myIdsOnBoundary.end() )
3499             {
3500               // there are points mapped on a link
3501               list< int >& mappedIds = nn_IdList->second.front();
3502               if ( isReversed( nodes[ i ], mappedIds ))
3503                 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3504               else
3505                 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3506             }
3507           } // loop on links of a <face>
3508         } // if ( face )
3509         else
3510           break;
3511       } // while (true)
3512
3513       if ( myIs2D && idGroups.size() > 1 ) {
3514
3515         // sew new elements on 2 refined elements sharing n1-n2 link
3516
3517         list< int >& idsOnLink = idGroups.front();
3518         // temporarily add ids of link nodes to idsOnLink
3519         bool rev = isReversed( n1, idsOnLink );
3520         for ( int i = 0; i < 2; ++i )
3521         {
3522           TNodeSet nodeSet;
3523           nodeSet.insert( i ? n2 : n1 );
3524           ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3525           list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3526           int nodeId = groups.front().front();
3527           bool append = i;
3528           if ( rev ) append = !append;
3529           if ( append )
3530             idsOnLink.push_back( nodeId );
3531           else
3532             idsOnLink.push_front( nodeId );
3533         }
3534         list< int >::iterator id = idsOnLink.begin();
3535         for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3536         {
3537           list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3538           list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3539           for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3540           {
3541             TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3542             // look for <id> in element definition
3543             TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3544             ASSERT ( idDef != pIdList->end() );
3545             // look for 2 neighbour ids of <id> in element definition
3546             for ( int prev = 0; prev < 2; ++prev ) {
3547               TElemDef::iterator idDef2 = idDef;
3548               if ( prev )
3549                 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3550               else
3551                 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3552               // look for idDef2 on a link starting from id
3553               list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3554               if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3555                 // insert ids located on link between <id> and <id2>
3556                 // into the element definition between idDef and idDef2
3557                 if ( prev )
3558                   for ( ; id2 != id; --id2 )
3559                     pIdList->insert( idDef, *id2 );
3560                 else {
3561                   list< int >::iterator id1 = id;
3562                   for ( ++id1, ++id2; id1 != id2; ++id1 )
3563                     pIdList->insert( idDef2, *id1 );
3564                 }
3565               }
3566             }
3567           }
3568         }
3569         // remove ids of link nodes
3570         idsOnLink.pop_front();
3571         idsOnLink.pop_back();
3572       }
3573     } // loop on myIdsOnBoundary
3574   } // if ( toCreatePolygons )
3575
3576   if ( toCreatePolyedrs )
3577   {
3578     // check volumes adjacent to the refined elements
3579     SMDS_VolumeTool volTool;
3580     vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3581     for ( ; refinedElem != myElements.end(); ++refinedElem )
3582     {
3583       // loop on nodes of refinedElem
3584       SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3585       while ( nIt->more() ) {
3586         const SMDS_MeshNode* node = smdsNode( nIt->next() );
3587         // loop on inverse elements of node
3588         SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3589         while ( eIt->more() )
3590         {
3591           const SMDS_MeshElement* elem = eIt->next();
3592           if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3593             continue; // skip faces or refined elements
3594           // add polyhedron definition
3595           myPolyhedronQuantities.push_back(vector<int> ());
3596           myPolyElemXYZIDs.push_back(TElemDef());
3597           vector<int>& quantity = myPolyhedronQuantities.back();
3598           TElemDef &   elemDef  = myPolyElemXYZIDs.back();
3599           // get definitions of new elements on volume faces
3600           bool makePoly = false;
3601           for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3602           {
3603             if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3604                                     volTool.NbFaceNodes( iF ),
3605                                     theNodes, elemDef, quantity))
3606               makePoly = true;
3607           }
3608           if ( makePoly )
3609             myPolyElems.push_back( elem );
3610           else {
3611             myPolyhedronQuantities.pop_back();
3612             myPolyElemXYZIDs.pop_back();
3613           }
3614         }
3615       }
3616     }
3617   }
3618 }
3619
3620 //=======================================================================
3621 //function : getFacesDefinition
3622 //purpose  : return faces definition for a volume face defined by theBndNodes
3623 //=======================================================================
3624
3625 bool SMESH_Pattern::
3626   getFacesDefinition(const SMDS_MeshNode**                 theBndNodes,
3627                      const int                             theNbBndNodes,
3628                      const vector< const SMDS_MeshNode* >& theNodes,
3629                      list< int >&                          theFaceDefs,
3630                      vector<int>&                          theQuantity)
3631 {
3632   bool makePoly = false;
3633 //   cout << "FROM FACE NODES: " <<endl;
3634 //   for ( int i = 0; i < theNbBndNodes; ++i )
3635 //     cout << theBndNodes[ i ];
3636
3637   set< const SMDS_MeshNode* > bndNodeSet;
3638   for ( int i = 0; i < theNbBndNodes; ++i )
3639     bndNodeSet.insert( theBndNodes[ i ]);
3640
3641   map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3642
3643   // make a set of all nodes on a face
3644   set< int > ids;
3645   if ( !myIs2D ) { // for 2D, merge only edges
3646     nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3647     if ( nn_IdList != myIdsOnBoundary.end() ) {
3648       makePoly = true;
3649       list< int > & faceIds = nn_IdList->second.front();
3650       ids.insert( faceIds.begin(), faceIds.end() );
3651     }
3652   }
3653   //bool hasIdsInFace = !ids.empty();
3654
3655   // add ids on links and bnd nodes
3656   int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3657   TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3658   for ( int iN = 0; iN < theNbBndNodes; ++iN )
3659   {
3660     // add id of iN-th bnd node
3661     TNodeSet nSet;
3662     nSet.insert( theBndNodes[ iN ] );
3663     nn_IdList = myIdsOnBoundary.find( nSet );
3664     int bndId = ++lastFreeId;
3665     if ( nn_IdList != myIdsOnBoundary.end() ) {
3666       bndId = nn_IdList->second.front().front();
3667       ids.insert( bndId );
3668     }
3669     else 
3670       myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3671     faceDef.push_back( bndId );
3672     // add ids on a link
3673     TNodeSet linkNodes;
3674     linkNodes.insert( theBndNodes[ iN ]);
3675     linkNodes.insert( theBndNodes[ iN + 1 == theNbBndNodes ? 0 : iN + 1 ]);
3676     nn_IdList = myIdsOnBoundary.find( linkNodes );
3677     if ( nn_IdList != myIdsOnBoundary.end() ) {
3678       makePoly = true;
3679       list< int > & linkIds = nn_IdList->second.front();
3680       ids.insert( linkIds.begin(), linkIds.end() );
3681       if ( isReversed( theBndNodes[ iN ], linkIds ))
3682         faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3683       else
3684         faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3685     }
3686   }
3687
3688   // find faces definition of new volumes
3689
3690   bool defsAdded = false;
3691   if ( !myIs2D ) { // for 2D, merge only edges
3692     SMDS_VolumeTool vol;
3693     set< TElemDef* > checkedVolDefs;
3694     set< int >::iterator id = ids.begin();
3695     for ( ; id != ids.end(); ++id )
3696     {
3697       // definitions of volumes sharing id
3698       list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3699       ASSERT( !defList.empty() );
3700       // loop on volume definitions
3701       list< TElemDef* >::iterator pIdList = defList.begin();
3702       for ( ; pIdList != defList.end(); ++pIdList)
3703       {
3704         if ( !checkedVolDefs.insert( *pIdList ).second )
3705           continue; // skip already checked volume definition
3706         vector< int > idVec;
3707         idVec.reserve( (*pIdList)->size() );
3708         idVec.insert( idVec.begin(), (*pIdList)->begin(), (*pIdList)->end() );
3709         // loop on face defs of a volume
3710         SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3711         if ( volType == SMDS_VolumeTool::UNKNOWN )
3712           continue;
3713         int nbFaces = vol.NbFaces( volType );
3714         for ( int iF = 0; iF < nbFaces; ++iF )
3715         {
3716           const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3717           int iN, nbN = vol.NbFaceNodes( volType, iF );
3718           // check if all nodes of a faces are in <ids>
3719           bool all = true;
3720           for ( iN = 0; iN < nbN && all; ++iN ) {
3721             int nodeId = idVec[ nodeInds[ iN ]];
3722             all = ( ids.find( nodeId ) != ids.end() );
3723           }
3724           if ( all ) {
3725             // store a face definition
3726             for ( iN = 0; iN < nbN; ++iN ) {
3727               theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3728             }
3729             theQuantity.push_back( nbN );
3730             defsAdded = true;
3731           }
3732         }
3733       }
3734     }
3735   }
3736   if ( !defsAdded ) {
3737     theQuantity.push_back( faceDef.size() );
3738     theFaceDefs.splice( theFaceDefs.end(), faceDef, faceDef.begin(), faceDef.end() );
3739   }
3740
3741   return makePoly;
3742 }
3743
3744 //=======================================================================
3745 //function : clearSubMesh
3746 //purpose  : 
3747 //=======================================================================
3748
3749 static bool clearSubMesh( SMESH_Mesh*         theMesh,
3750                           const TopoDS_Shape& theShape)
3751 {
3752   bool removed = false;
3753   if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3754   {
3755     if ( aSubMesh->GetSubMeshDS() ) {
3756       removed =
3757         aSubMesh->GetSubMeshDS()->NbElements() || aSubMesh->GetSubMeshDS()->NbNodes();
3758       aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3759     }
3760   }
3761   else {
3762     SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3763     if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3764     {
3765       SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3766       removed = eIt->more();
3767       while ( eIt->more() )
3768         aMeshDS->RemoveElement( eIt->next() );
3769       SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3770       removed = removed || nIt->more();
3771       while ( nIt->more() )
3772         aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3773     }
3774   }
3775   return removed;
3776 }
3777
3778 //=======================================================================
3779 //function : clearMesh
3780 //purpose  : clear mesh elements existing on myShape in theMesh
3781 //=======================================================================
3782
3783 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3784 {
3785
3786   if ( !myShape.IsNull() )
3787   {
3788     if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3789       TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3790       for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3791       {
3792         clearSubMesh( theMesh, it.Value() );
3793       }
3794     }
3795   }
3796 }
3797
3798 //=======================================================================
3799 //function : MakeMesh
3800 //purpose  : Create nodes and elements in <theMesh> using nodes
3801 //           coordinates computed by either of Apply...() methods
3802 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3803 //           it does not care of nodes and elements already existing on
3804 //           subshapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3805 //=======================================================================
3806
3807 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3808                              const bool  toCreatePolygons,
3809                              const bool  toCreatePolyedrs)
3810 {
3811   MESSAGE(" ::MakeMesh() " );
3812   if ( !myIsComputed )
3813     return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3814
3815   mergePoints( toCreatePolygons );
3816
3817   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3818
3819   // clear elements and nodes existing on myShape
3820   clearMesh(theMesh);
3821
3822   bool onMeshElements = ( !myElements.empty() );
3823
3824   // Create missing nodes
3825
3826   vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3827   if ( onMeshElements )
3828   {
3829     nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3830     map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3831     for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3832       nodesVector[ i_node->first ] = i_node->second;
3833     }
3834     for ( int i = 0; i < myXYZ.size(); ++i ) {
3835       if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3836         nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3837                                              myXYZ[ i ].Y(),
3838                                              myXYZ[ i ].Z());
3839     }
3840   }
3841   else
3842   {
3843     nodesVector.resize( myPoints.size(), 0 );
3844
3845     // to find point index
3846     map< TPoint*, int > pointIndex;
3847     for ( int i = 0; i < myPoints.size(); i++ )
3848       pointIndex.insert( make_pair( & myPoints[ i ], i ));
3849
3850     // loop on sub-shapes of myShape: create nodes
3851     map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3852     for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3853     {
3854       TopoDS_Shape S;
3855       //SMESHDS_SubMesh * subMeshDS = 0;
3856       if ( !myShapeIDMap.IsEmpty() ) {
3857         S = myShapeIDMap( idPointIt->first );
3858         //subMeshDS = aMeshDS->MeshElements( S );
3859       }
3860       list< TPoint* > & points = idPointIt->second;
3861       list< TPoint* >::iterator pIt = points.begin();
3862       for ( ; pIt != points.end(); pIt++ )
3863       {
3864         TPoint* point = *pIt;
3865         int pIndex = pointIndex[ point ];
3866         if ( nodesVector [ pIndex ] )
3867           continue;
3868         SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3869                                                 point->myXYZ.Y(),
3870                                                 point->myXYZ.Z());
3871         nodesVector [ pIndex ] = node;
3872
3873         if ( true /*subMeshDS*/ ) {
3874           // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3875           switch ( S.ShapeType() ) {
3876           case TopAbs_VERTEX: {
3877             aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3878           }
3879           case TopAbs_EDGE: {
3880             aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3881           }
3882           case TopAbs_FACE: {
3883             aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3884                                     point->myUV.X(), point->myUV.Y() ); break;
3885           }
3886           default:
3887             aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3888           }
3889         }
3890       }
3891     }
3892   }
3893
3894   // create elements
3895
3896   if ( onMeshElements )
3897   {
3898     // prepare data to create poly elements
3899     makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3900
3901     // refine elements
3902     createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3903     // sew old and new elements
3904     createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3905   }
3906   else
3907   {
3908     createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3909   }
3910
3911 //   const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3912 //   map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3913 //   for ( ; i_sm != sm.end(); i_sm++ )
3914 //   {
3915 //     cout << " SM " << i_sm->first << " ";
3916 //     TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
3917 //     //SMDS_ElemIteratorPtr GetElements();
3918 //     SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
3919 //     while ( nit->more() )
3920 //       cout << nit->next()->GetID() << " ";
3921 //     cout << endl;
3922 //   }
3923   return setErrorCode( ERR_OK );
3924 }
3925
3926 //=======================================================================
3927 //function : createElements
3928 //purpose  : add elements to the mesh
3929 //=======================================================================
3930
3931 void SMESH_Pattern::createElements(SMESH_Mesh*                            theMesh,
3932                                    const vector<const SMDS_MeshNode* >&   theNodesVector,
3933                                    const list< TElemDef > &               theElemNodeIDs,
3934                                    const vector<const SMDS_MeshElement*>& theElements)
3935 {
3936   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3937   SMESH_MeshEditor editor( theMesh ); 
3938
3939   bool onMeshElements = !theElements.empty();
3940
3941   // shapes and groups theElements are on
3942   vector< int > shapeIDs;
3943   vector< list< SMESHDS_Group* > > groups;
3944   set< const SMDS_MeshNode* > shellNodes;
3945   if ( onMeshElements )
3946   {
3947     shapeIDs.resize( theElements.size() );
3948     groups.resize( theElements.size() );
3949     const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
3950     set<SMESHDS_GroupBase*>::const_iterator grIt;
3951     for ( int i = 0; i < theElements.size(); i++ )
3952     {
3953       shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
3954       for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
3955         SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
3956         if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
3957           groups[ i ].push_back( group );
3958       }
3959     }
3960     // get all nodes bound to shells because their SpacePosition is not set
3961     // by SMESHDS_Mesh::SetNodeInVolume()
3962     TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
3963     if ( !aMainShape.IsNull() ) {
3964       TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
3965       for ( ; shellExp.More(); shellExp.Next() )
3966       {
3967         SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
3968         if ( sm ) {
3969           SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3970           while ( nIt->more() )
3971             shellNodes.insert( nIt->next() );
3972         }
3973       }
3974     }
3975   }
3976    // nb new elements per a refined element
3977   int nbNewElemsPerOld = 1;
3978   if ( onMeshElements )
3979     nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
3980
3981   bool is2d = myIs2D;
3982
3983   list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
3984   list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
3985   for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
3986   {
3987     const TElemDef & elemNodeInd = *enIt;
3988     // retrieve nodes
3989     vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
3990     TElemDef::const_iterator id = elemNodeInd.begin();
3991     int nbNodes;
3992     for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
3993       if ( *id < theNodesVector.size() )
3994         nodes[ nbNodes++ ] = theNodesVector[ *id ];
3995       else
3996         nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
3997     }
3998     // dim of refined elem
3999     int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4000     if ( onMeshElements ) {
4001       is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4002     }
4003     // add an element
4004     const SMDS_MeshElement* elem = 0;
4005     if ( is2d ) {
4006       switch ( nbNodes ) {
4007       case 3:
4008         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4009       case 4:
4010         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4011       case 6:
4012         if ( !onMeshElements ) {// create a quadratic face
4013           elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4014                                    nodes[4], nodes[5] ); break;
4015         } // else do not break but create a polygon
4016       case 8:
4017         if ( !onMeshElements ) {// create a quadratic face
4018           elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4019                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4020         } // else do not break but create a polygon
4021       default:
4022         elem = aMeshDS->AddPolygonalFace( nodes );
4023       }
4024     }
4025     else {
4026       switch ( nbNodes ) {
4027       case 4:
4028         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4029       case 5:
4030         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4031                                    nodes[4] ); break;
4032       case 6:
4033         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4034                                    nodes[4], nodes[5] ); break;
4035       case 8:
4036         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4037                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4038       default:
4039         elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4040       }
4041     }
4042     // set element on a shape
4043     if ( elem && onMeshElements ) // applied to mesh elements
4044     {
4045       int shapeID = shapeIDs[ elemIndex ];
4046       if ( shapeID > 0 ) {
4047         aMeshDS->SetMeshElementOnShape( elem, shapeID );
4048         // set nodes on a shape
4049         TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4050         if ( S.ShapeType() == TopAbs_SOLID ) {
4051           TopoDS_Iterator shellIt( S );
4052           if ( shellIt.More() )
4053             shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4054         }
4055         SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4056         while ( noIt->more() ) {
4057           SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4058           if (!node->GetPosition()->GetShapeId() &&
4059               shellNodes.find( node ) == shellNodes.end() ) {
4060             if ( S.ShapeType() == TopAbs_FACE )
4061               aMeshDS->SetNodeOnFace( node, shapeID );
4062             else {
4063               aMeshDS->SetNodeInVolume( node, shapeID );
4064               shellNodes.insert( node );
4065             }
4066           }
4067         }
4068       }
4069       // add elem in groups
4070       list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4071       for ( ; g != groups[ elemIndex ].end(); ++g )
4072         (*g)->SMDSGroup().Add( elem );
4073     }
4074     if ( elem && !myShape.IsNull() ) // applied to shape
4075       aMeshDS->SetMeshElementOnShape( elem, myShape );
4076   }
4077
4078   // make that SMESH_subMesh::_computeState == COMPUTE_OK
4079   // so that operations with hypotheses will erase the mesh being built
4080
4081   SMESH_subMesh * subMesh;
4082   if ( !myShape.IsNull() ) {
4083     subMesh = theMesh->GetSubMeshContaining( myShape );
4084     if ( subMesh )
4085       subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4086   }
4087   if ( onMeshElements ) {
4088     list< int > elemIDs;
4089     for ( int i = 0; i < theElements.size(); i++ )
4090     {
4091       subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4092       if ( subMesh )
4093         subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4094
4095       elemIDs.push_back( theElements[ i ]->GetID() );
4096     }
4097     // remove refined elements
4098     editor.Remove( elemIDs, false );
4099   }
4100 }
4101
4102 //=======================================================================
4103 //function : isReversed
4104 //purpose  : check xyz ids order in theIdsList taking into account
4105 //           theFirstNode on a link
4106 //=======================================================================
4107
4108 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4109                                const list< int >&   theIdsList) const
4110 {
4111   if ( theIdsList.size() < 2 )
4112     return false;
4113
4114   gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4115   gp_Pnt P[2];
4116   list<int>::const_iterator id = theIdsList.begin();
4117   for ( int i = 0; i < 2; ++i, ++id ) {
4118     if ( *id < myXYZ.size() )
4119       P[ i ] = myXYZ[ *id ];
4120     else {
4121       map< int, const SMDS_MeshNode*>::const_iterator i_n;
4122       i_n = myXYZIdToNodeMap.find( *id );
4123       ASSERT( i_n != myXYZIdToNodeMap.end() );
4124       const SMDS_MeshNode* n = i_n->second;
4125       P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4126     }
4127   }
4128   return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4129 }
4130
4131
4132 //=======================================================================
4133 //function : arrangeBoundaries
4134 //purpose  : if there are several wires, arrange boundaryPoints so that
4135 //           the outer wire goes first and fix inner wires orientation
4136 //           update myKeyPointIDs to correspond to the order of key-points
4137 //           in boundaries; sort internal boundaries by the nb of key-points
4138 //=======================================================================
4139
4140 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4141 {
4142   typedef list< list< TPoint* > >::iterator TListOfListIt;
4143   TListOfListIt bndIt;
4144   list< TPoint* >::iterator pIt;
4145
4146   int nbBoundaries = boundaryList.size();
4147   if ( nbBoundaries > 1 )
4148   {
4149     // sort boundaries by nb of key-points
4150     if ( nbBoundaries > 2 )
4151     {
4152       // move boundaries in tmp list
4153       list< list< TPoint* > > tmpList; 
4154       tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4155       // make a map nb-key-points to boundary-position-in-tmpList,
4156       // boundary-positions get ordered in it
4157       typedef map< int, TListOfListIt > TNbKpBndPosMap;
4158       TNbKpBndPosMap nbKpBndPosMap;
4159       bndIt = tmpList.begin();
4160       list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4161       for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4162         int nb = *nbKpIt * nbBoundaries;
4163         while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4164           nb++;
4165         nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4166       }
4167       // move boundaries back to boundaryList
4168       TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4169       for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4170         TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4171         TListOfListIt bndPos1 = bndPos2++;
4172         boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4173       }
4174     }
4175
4176     // Look for the outer boundary: the one with the point with the least X
4177     double leastX = DBL_MAX;
4178     TListOfListIt outerBndPos;
4179     for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4180     {
4181       list< TPoint* >& boundary = (*bndIt);
4182       for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4183       {
4184         TPoint* point = *pIt;
4185         if ( point->myInitXYZ.X() < leastX ) {
4186           leastX = point->myInitXYZ.X();
4187           outerBndPos = bndIt;
4188         }
4189       }
4190     }
4191
4192     if ( outerBndPos != boundaryList.begin() )
4193       boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4194
4195   } // if nbBoundaries > 1
4196                  
4197   // Check boundaries orientation and re-fill myKeyPointIDs
4198
4199   set< TPoint* > keyPointSet;
4200   list< int >::iterator kpIt = myKeyPointIDs.begin();
4201   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4202     keyPointSet.insert( & myPoints[ *kpIt ]);
4203   myKeyPointIDs.clear();
4204
4205   // update myNbKeyPntInBoundary also
4206   list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4207
4208   for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4209   {
4210     // find the point with the least X
4211     double leastX = DBL_MAX;
4212     list< TPoint* >::iterator xpIt;
4213     list< TPoint* >& boundary = (*bndIt);
4214     for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4215     {
4216       TPoint* point = *pIt;
4217       if ( point->myInitXYZ.X() < leastX ) {
4218         leastX = point->myInitXYZ.X();
4219         xpIt = pIt;
4220       }
4221     }
4222     // find points next to the point with the least X
4223     TPoint* p = *xpIt, *pPrev, *pNext;
4224     if ( p == boundary.front() )
4225       pPrev = *(++boundary.rbegin());
4226     else {
4227       xpIt--;
4228       pPrev = *xpIt;
4229       xpIt++;
4230     }
4231     if ( p == boundary.back() )
4232       pNext = *(++boundary.begin());
4233     else {
4234       xpIt++;
4235       pNext = *xpIt;
4236     }
4237     // vectors of boundary direction near <p>
4238     gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4239     double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4240     if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4241       double yPrev = v1.Y() / sqrt( sqMag1 );
4242       double yNext = v2.Y() / sqrt( sqMag2 );
4243       double sumY = yPrev + yNext;
4244       bool reverse;
4245       if ( bndIt == boundaryList.begin() ) // outer boundary
4246         reverse = sumY > 0;
4247       else
4248         reverse = sumY < 0;
4249       if ( reverse )
4250         boundary.reverse();
4251     }
4252
4253     // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4254     (*nbKpIt) = 0; // count nb of key-points again
4255     pIt = boundary.begin();
4256     for ( ; pIt != boundary.end(); pIt++)
4257     {
4258       TPoint* point = *pIt;
4259       if ( keyPointSet.find( point ) == keyPointSet.end() )
4260         continue;
4261       // find an index of a keypoint
4262       int index = 0;
4263       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4264       for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4265         if ( &(*pVecIt) == point )
4266           break;
4267       myKeyPointIDs.push_back( index );
4268       (*nbKpIt)++;
4269     }
4270     myKeyPointIDs.pop_back(); // remove the first key-point from the back
4271     (*nbKpIt)--;
4272
4273   } // loop on a list of boundaries
4274
4275   ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4276 }
4277
4278 //=======================================================================
4279 //function : findBoundaryPoints
4280 //purpose  : if loaded from file, find points to map on edges and faces and
4281 //           compute their parameters
4282 //=======================================================================
4283
4284 bool SMESH_Pattern::findBoundaryPoints()
4285 {
4286   if ( myIsBoundaryPointsFound ) return true;
4287
4288   MESSAGE(" findBoundaryPoints() ");
4289
4290   myNbKeyPntInBoundary.clear();
4291
4292   if ( myIs2D )
4293   {
4294     set< TPoint* > pointsInElems;
4295
4296     // Find free links of elements:
4297     // put links of all elements in a set and remove links encountered twice
4298
4299     typedef pair< TPoint*, TPoint*> TLink;
4300     set< TLink > linkSet;
4301     list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4302     for ( ; epIt != myElemPointIDs.end(); epIt++ )
4303     {
4304       TElemDef & elemPoints = *epIt;
4305       TElemDef::iterator pIt = elemPoints.begin();
4306       int prevP = elemPoints.back();
4307       for ( ; pIt != elemPoints.end(); pIt++ ) {
4308         TPoint* p1 = & myPoints[ prevP ];
4309         TPoint* p2 = & myPoints[ *pIt ];
4310         TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4311         ASSERT( link.first != link.second );
4312         pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4313         if ( !itUniq.second )
4314           linkSet.erase( itUniq.first );
4315         prevP = *pIt;
4316
4317         pointsInElems.insert( p1 );
4318       }
4319     }
4320     // Now linkSet contains only free links,
4321     // find the points order that they have in boundaries
4322
4323     // 1. make a map of key-points
4324     set< TPoint* > keyPointSet;
4325     list< int >::iterator kpIt = myKeyPointIDs.begin();
4326     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4327       keyPointSet.insert( & myPoints[ *kpIt ]);
4328
4329     // 2. chain up boundary points
4330     list< list< TPoint* > > boundaryList;
4331     boundaryList.push_back( list< TPoint* >() );
4332     list< TPoint* > * boundary = & boundaryList.back();
4333
4334     TPoint *point1, *point2, *keypoint1;
4335     kpIt = myKeyPointIDs.begin();
4336     point1 = keypoint1 = & myPoints[ *kpIt++ ];
4337     // loop on free links: look for the next point
4338     int iKeyPoint = 0;
4339     set< TLink >::iterator lIt = linkSet.begin();
4340     while ( lIt != linkSet.end() )
4341     {
4342       if ( (*lIt).first == point1 )
4343         point2 = (*lIt).second;
4344       else if ( (*lIt).second == point1 )
4345         point2 = (*lIt).first;
4346       else {
4347         lIt++;
4348         continue;
4349       }
4350       linkSet.erase( lIt );
4351       lIt = linkSet.begin();
4352
4353       if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4354       {
4355         boundary->push_back( point2 );
4356       }
4357       else // a key-point found
4358       {
4359         keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4360         iKeyPoint++;
4361         if ( point2 != keypoint1 ) // its not the boundary end
4362         {
4363           boundary->push_back( point2 );
4364         }
4365         else  // the boundary end reached
4366         {
4367           boundary->push_front( keypoint1 );
4368           boundary->push_back( keypoint1 );
4369           myNbKeyPntInBoundary.push_back( iKeyPoint );
4370           if ( keyPointSet.empty() )
4371             break; // all boundaries containing key-points are found
4372
4373           // prepare to search for the next boundary
4374           boundaryList.push_back( list< TPoint* >() );
4375           boundary = & boundaryList.back();
4376           point2 = keypoint1 = (*keyPointSet.begin());
4377         }
4378       }
4379       point1 = point2;
4380     } // loop on the free links set
4381
4382     if ( boundary->empty() ) {
4383       MESSAGE(" a separate key-point");
4384       return setErrorCode( ERR_READ_BAD_KEY_POINT );
4385     }
4386
4387     // if there are several wires, arrange boundaryPoints so that
4388     // the outer wire goes first and fix inner wires orientation;
4389     // sort myKeyPointIDs to correspond to the order of key-points
4390     // in boundaries
4391     arrangeBoundaries( boundaryList );
4392
4393     // Find correspondence shape ID - points,
4394     // compute points parameter on edge
4395
4396     keyPointSet.clear();
4397     for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4398       keyPointSet.insert( & myPoints[ *kpIt ]);
4399
4400     set< TPoint* > edgePointSet; // to find in-face points
4401     int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4402     int edgeID = myKeyPointIDs.size() + 1;
4403
4404     list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4405     for ( ; bndIt != boundaryList.end(); bndIt++ )
4406     {
4407       boundary = & (*bndIt);
4408       double edgeLength = 0;
4409       list< TPoint* >::iterator pIt = boundary->begin();
4410       getShapePoints( edgeID ).push_back( *pIt );
4411       getShapePoints( vertexID++ ).push_back( *pIt );
4412       for ( pIt++; pIt != boundary->end(); pIt++)
4413       {
4414         list< TPoint* > & edgePoints = getShapePoints( edgeID );
4415         TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4416         TPoint* point = *pIt;
4417         edgePointSet.insert( point );
4418         if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4419         {
4420           edgePoints.push_back( point );
4421           edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4422           point->myInitU = edgeLength;
4423         }
4424         else // a key-point
4425         {
4426           // treat points on the edge which ends up: compute U [0,1]
4427           edgePoints.push_back( point );
4428           if ( edgePoints.size() > 2 ) {
4429             edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4430             list< TPoint* >::iterator epIt = edgePoints.begin();
4431             for ( ; epIt != edgePoints.end(); epIt++ )
4432               (*epIt)->myInitU /= edgeLength;
4433           }
4434           // begin the next edge treatment
4435           edgeLength = 0;
4436           edgeID++;
4437           if ( point != boundary->front() ) { // not the first key-point again
4438             getShapePoints( edgeID ).push_back( point );
4439             getShapePoints( vertexID++ ).push_back( point );
4440           }
4441         }
4442       }
4443     }
4444
4445     // find in-face points
4446     list< TPoint* > & facePoints = getShapePoints( edgeID );
4447     vector< TPoint >::iterator pVecIt = myPoints.begin();
4448     for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4449       TPoint* point = &(*pVecIt);
4450       if ( edgePointSet.find( point ) == edgePointSet.end() &&
4451           pointsInElems.find( point ) != pointsInElems.end())
4452         facePoints.push_back( point );
4453     }
4454
4455   } // 2D case
4456
4457   else // 3D case
4458   {
4459     // bind points to shapes according to point parameters
4460     vector< TPoint >::iterator pVecIt = myPoints.begin();
4461     for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4462       TPoint* point = &(*pVecIt);
4463       int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4464       getShapePoints( shapeID ).push_back( point );
4465       // detect key-points
4466       if ( SMESH_Block::IsVertexID( shapeID ))
4467         myKeyPointIDs.push_back( i );        
4468     }
4469   }
4470
4471   myIsBoundaryPointsFound = true;
4472   return myIsBoundaryPointsFound;
4473 }
4474
4475 //=======================================================================
4476 //function : Clear
4477 //purpose  : clear fields
4478 //=======================================================================
4479
4480 void SMESH_Pattern::Clear()
4481 {
4482   myIsComputed = myIsBoundaryPointsFound = false;
4483
4484   myPoints.clear();
4485   myKeyPointIDs.clear();
4486   myElemPointIDs.clear();
4487   myShapeIDToPointsMap.clear();
4488   myShapeIDMap.Clear();
4489   myShape.Nullify();
4490   myNbKeyPntInBoundary.clear();
4491 }
4492
4493 //=======================================================================
4494 //function : setShapeToMesh
4495 //purpose  : set a shape to be meshed. Return True if meshing is possible
4496 //=======================================================================
4497
4498 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4499 {
4500   if ( !IsLoaded() ) {
4501     MESSAGE( "Pattern not loaded" );
4502     return setErrorCode( ERR_APPL_NOT_LOADED );
4503   }
4504
4505   TopAbs_ShapeEnum aType = theShape.ShapeType();
4506   bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4507   if ( !dimOk ) {
4508     MESSAGE( "Pattern dimention mismatch" );
4509     return setErrorCode( ERR_APPL_BAD_DIMENTION );
4510   }
4511
4512   // check if a face is closed
4513   int nbNodeOnSeamEdge = 0;
4514   if ( myIs2D ) {
4515     TopoDS_Face face = TopoDS::Face( theShape );
4516     TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4517     for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() )
4518       if ( BRep_Tool::IsClosed( TopoDS::Edge( eExp.Current() ), face ))
4519         nbNodeOnSeamEdge = 2;
4520   }
4521     
4522   // check nb of vertices
4523   TopTools_IndexedMapOfShape vMap;
4524   TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4525   if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4526     MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4527     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4528   }
4529
4530   myElements.clear(); // not refine elements
4531   myElemXYZIDs.clear();
4532
4533   myShapeIDMap.Clear();
4534   myShape = theShape;
4535   return true;
4536 }
4537
4538 //=======================================================================
4539 //function : GetMappedPoints
4540 //purpose  : Return nodes coordinates computed by Apply() method
4541 //=======================================================================
4542
4543 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4544 {
4545   thePoints.clear();
4546   if ( !myIsComputed )
4547     return false;
4548
4549   if ( myElements.empty() ) { // applied to shape
4550     vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4551     for ( ; pVecIt != myPoints.end(); pVecIt++ )
4552       thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4553   }
4554   else { // applied to mesh elements
4555     const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4556     vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4557     for ( ; xyz != myXYZ.end(); ++xyz )
4558       if ( !isDefined( *xyz ))
4559         thePoints.push_back( definedXYZ );
4560       else
4561         thePoints.push_back( & (*xyz) );
4562   }
4563   return !thePoints.empty();
4564 }
4565
4566
4567 //=======================================================================
4568 //function : GetPoints
4569 //purpose  : Return nodes coordinates of the pattern
4570 //=======================================================================
4571
4572 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4573 {
4574   thePoints.clear();
4575
4576   if ( !IsLoaded() )
4577     return false;
4578
4579   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4580   for ( ; pVecIt != myPoints.end(); pVecIt++ )
4581     thePoints.push_back( & (*pVecIt).myInitXYZ );
4582
4583   return ( thePoints.size() > 0 );
4584 }
4585
4586 //=======================================================================
4587 //function : getShapePoints
4588 //purpose  : return list of points located on theShape
4589 //=======================================================================
4590
4591 list< SMESH_Pattern::TPoint* > &
4592   SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4593 {
4594   int aShapeID;
4595   if ( !myShapeIDMap.Contains( theShape ))
4596     aShapeID = myShapeIDMap.Add( theShape );
4597   else
4598     aShapeID = myShapeIDMap.FindIndex( theShape );
4599
4600   return myShapeIDToPointsMap[ aShapeID ];
4601 }
4602
4603 //=======================================================================
4604 //function : getShapePoints
4605 //purpose  : return list of points located on the shape
4606 //=======================================================================
4607
4608 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4609 {
4610   return myShapeIDToPointsMap[ theShapeID ];
4611 }
4612
4613 //=======================================================================
4614 //function : DumpPoints
4615 //purpose  : Debug
4616 //=======================================================================
4617
4618 void SMESH_Pattern::DumpPoints() const
4619 {
4620 #ifdef _DEBUG_
4621   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4622   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4623     cout << i << ": " << *pVecIt;
4624 #endif
4625 }
4626
4627 //=======================================================================
4628 //function : TPoint()
4629 //purpose  : 
4630 //=======================================================================
4631
4632 SMESH_Pattern::TPoint::TPoint()
4633 {
4634 #ifdef _DEBUG_
4635   myInitXYZ.SetCoord(0,0,0);
4636   myInitUV.SetCoord(0.,0.);
4637   myInitU = 0;
4638   myXYZ.SetCoord(0,0,0);
4639   myUV.SetCoord(0.,0.);
4640   myU = 0;
4641 #endif
4642 }
4643
4644 //=======================================================================
4645 //function : operator <<
4646 //purpose  : 
4647 //=======================================================================
4648
4649 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4650 {
4651   gp_XYZ xyz = p.myInitXYZ;
4652   OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4653   gp_XY xy = p.myInitUV;
4654   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
4655   double u = p.myInitU;
4656   OS << " u( " <<  u << " )) " << &p << endl;
4657   xyz = p.myXYZ.XYZ();
4658   OS << "\t    ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4659   xy = p.myUV;
4660   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
4661   u = p.myU;
4662   OS << " u( " <<  u << " ))" << endl;
4663   
4664   return OS;
4665 }