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