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