Salome HOME
Merge branch 'V9_9_BR'
[modules/smesh.git] / src / SMESH / SMESH_Pattern.cxx
1 // Copyright (C) 2007-2022  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_MeshEditor.hxx"
42 #include "SMESH_MesherHelper.hxx"
43 #include "SMESH_subMesh.hxx"
44
45 #include <BRepAdaptor_Curve.hxx>
46 #include <BRepTools.hxx>
47 #include <BRepTools_WireExplorer.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_Box.hxx>
50 #include <Bnd_Box2d.hxx>
51 #include <ElSLib.hxx>
52 #include <Extrema_ExtPC.hxx>
53 #include <Extrema_GenExtPS.hxx>
54 #include <Extrema_POnSurf.hxx>
55 #include <Geom2d_Curve.hxx>
56 #include <GeomAdaptor_Surface.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Surface.hxx>
59 #include <Precision.hxx>
60 #include <TopAbs_ShapeEnum.hxx>
61 #include <TopExp.hxx>
62 #include <TopExp_Explorer.hxx>
63 #include <TopLoc_Location.hxx>
64 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopoDS.hxx>
66 #include <TopoDS_Edge.hxx>
67 #include <TopoDS_Face.hxx>
68 #include <TopoDS_Iterator.hxx>
69 #include <TopoDS_Shell.hxx>
70 #include <TopoDS_Vertex.hxx>
71 #include <TopoDS_Wire.hxx>
72 #include <gp_Ax2.hxx>
73 #include <gp_Lin2d.hxx>
74 #include <gp_Pnt2d.hxx>
75 #include <gp_Trsf.hxx>
76 #include <gp_XY.hxx>
77 #include <gp_XYZ.hxx>
78
79 #include <Basics_Utils.hxx>
80 #include "utilities.h"
81
82 using namespace std;
83
84 typedef std::map< const SMDS_MeshElement*, int > TNodePointIDMap;
85 typedef std::list< TopoDS_Edge >                 TWire;
86
87 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
88
89 namespace
90 {
91   
92 //=======================================================================
93 //function : getInt
94 //purpose  : 
95 //=======================================================================
96
97 inline int getInt( const char * theSring )
98 {
99   if ( *theSring < '0' || *theSring > '9' )
100     return -1;
101
102   char *ptr;
103   int val = strtol( theSring, &ptr, 10 );
104   if ( ptr == theSring ||
105       // there must not be neither '.' nor ',' nor 'E' ...
106       (*ptr != ' ' && *ptr != '\n' && *ptr != '\0' && *ptr != '\r'))
107     return -1;
108
109   return val;
110 }
111
112 //=======================================================================
113 //function : getDouble
114 //purpose  : 
115 //=======================================================================
116
117 inline double getDouble( const char * theSring )
118 {
119   char *ptr;
120   return strtod( theSring, &ptr );
121 }
122
123 //=======================================================================
124 //function : readLine
125 //purpose  : Put token starting positions in theFields until '\n' or '\0'
126 //           Return the number of the found tokens
127 //=======================================================================
128
129 int readLine (list <const char*> & theFields,
130               const char*        & theLineBeg,
131               const bool           theClearFields )
132 {
133   if ( theClearFields )
134     theFields.clear();
135
136   //  algo:
137   /*  loop                                                       */
138   /*    switch ( symbol ) {                                      */
139   /*    case white-space:                                        */
140   /*      look for a non-space symbol;                           */
141   /*    case string-end:                                         */
142   /*    case line-end:                                           */
143   /*      exit;                                                  */
144   /*    case comment beginning:                                  */
145   /*      skip all till a line-end;                              */
146   /*    case a number                                            */
147   /*      put its position in theFields, skip till a white-space;*/
148   /*    default:                                                 */
149   /*      abort;                                                 */
150   /*  till line-end                                              */
151
152   int nbRead = 0;
153   bool stopReading = false;
154   do {
155     bool goOn = true;
156     bool isNumber = false;
157     switch ( *theLineBeg )
158     {
159     case ' ':  // white space
160     case '\t': // tab
161     case 13:   // ^M
162       break;
163
164     case '\n': // a line ends
165       stopReading = ( nbRead > 0 );
166       break;
167
168     case '!':  // comment
169       do theLineBeg++;
170       while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
171       goOn = false;
172       break;
173
174     case '\0': // file ends
175       return nbRead;
176
177     case '-': // real number
178     case '+':
179     case '.':
180       isNumber = true; // fall through
181     default: // data
182       isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
183       if ( isNumber ) {
184         theFields.push_back( theLineBeg );
185         nbRead++;
186         do theLineBeg++;
187         while (*theLineBeg != ' ' &&
188                *theLineBeg != '\n' &&
189                *theLineBeg != '\0');
190         goOn = false;
191       }
192       else
193         return 0; // incorrect file format
194     }
195
196     if ( goOn )
197       theLineBeg++;
198
199   } while ( !stopReading );
200
201   return nbRead;
202 }
203
204 //=======================================================================
205 //function : isRealSeam
206 //purpose  : return true if an EDGE encounters twice in a FACE
207 //=======================================================================
208
209 // bool isRealSeam( const TopoDS_Edge& e, const TopoDS_Face& f )
210 // {
211 //   if ( BRep_Tool::IsClosed( e, f ))
212 //   {
213 //     int nb = 0;
214 //     for (TopExp_Explorer exp( f, TopAbs_EDGE ); exp.More(); exp.Next())
215 //       if ( exp.Current().IsSame( e ))
216 //         if ( ++nb == 2 )
217 //           return true;
218 //   }
219 //   return false;
220 // }
221
222 //=======================================================================
223 //function : loadVE
224 //purpose  : load VERTEXes and EDGEs in a map. Return nb loaded VERTEXes
225 //=======================================================================
226
227 int loadVE( const list< TopoDS_Edge > &          eList,
228             TopTools_IndexedMapOfOrientedShape & map )
229 {
230   list< TopoDS_Edge >::const_iterator eIt = eList.begin();
231   // vertices
232   int nbV;
233   for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
234   {
235     nbV = map.Extent();
236     map.Add( TopExp::FirstVertex( *eIt, true ));
237     bool added = ( nbV < map.Extent() );
238     if ( !added ) { // vertex encountered twice
239       // a seam vertex have two corresponding key points
240       map.Add( TopExp::FirstVertex( *eIt, true ).Reversed());
241     }
242   }
243   nbV = map.Extent();
244
245   // edges
246   for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
247     map.Add( *eIt );
248
249   return nbV;
250 }
251
252 } // namespace
253
254 //=======================================================================
255 //function : SMESH_Pattern
256 //purpose  :
257 //=======================================================================
258
259 SMESH_Pattern::SMESH_Pattern (): myToKeepNodes(false)
260 {
261 }
262
263 //=======================================================================
264 //function : Load
265 //purpose  : Load a pattern from <theFile>
266 //=======================================================================
267
268 bool SMESH_Pattern::Load (const char* theFileContents)
269 {
270   Kernel_Utils::Localizer loc;
271   
272   // file structure:
273
274   // ! This is a comment
275   // NB_POINTS               ! 1 integer - the number of points in the pattern.
276   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
277   //   X2 Y2 [Z2]            ! the pattern dimension is defined by the number of coordinates
278   //   ...
279   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
280   // ! elements description goes after all
281   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
282   // ...
283
284   Clear();
285
286   const char* lineBeg = theFileContents;
287   list <const char*> fields;
288   const bool clearFields = true;
289
290   // NB_POINTS               ! 1 integer - the number of points in the pattern.
291
292   if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
293     MESSAGE("Error reading NB_POINTS");
294     return setErrorCode( ERR_READ_NB_POINTS );
295   }
296   int nbPoints = getInt( fields.front() );
297
298   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
299
300   // read the first point coordinates to define pattern dimension
301   int dim = readLine( fields, lineBeg, clearFields );
302   if ( dim == 2 )
303     myIs2D = true;
304   else if ( dim == 3 )
305     myIs2D = false;
306   else {
307     MESSAGE("Error reading points: wrong nb of coordinates");
308     return setErrorCode( ERR_READ_POINT_COORDS );
309   }
310   if ( nbPoints <= dim ) {
311     MESSAGE(" Too few points ");
312     return setErrorCode( ERR_READ_TOO_FEW_POINTS );
313   }
314
315   // read the rest points
316   int iPoint;
317   for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
318     if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
319       MESSAGE("Error reading  points : wrong nb of coordinates ");
320       return setErrorCode( ERR_READ_POINT_COORDS );
321     }
322   // store point coordinates
323   myPoints.resize( nbPoints );
324   list <const char*>::iterator fIt = fields.begin();
325   for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
326   {
327     TPoint & p = myPoints[ iPoint ];
328     for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
329     {
330       double coord = getDouble( *fIt );
331       if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
332         MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
333         Clear();
334         return setErrorCode( ERR_READ_3D_COORD );
335       }
336       p.myInitXYZ.SetCoord( iCoord, coord );
337       if ( myIs2D )
338         p.myInitUV.SetCoord( iCoord, coord );
339     }
340   }
341
342   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
343   if ( myIs2D )
344   {
345     if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
346       MESSAGE("Error: missing key-points");
347       Clear();
348       return setErrorCode( ERR_READ_NO_KEYPOINT );
349     }
350     set<int> idSet;
351     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
352     {
353       int pointIndex = getInt( *fIt );
354       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
355         MESSAGE("Error: invalid point index " << pointIndex );
356         Clear();
357         return setErrorCode( ERR_READ_BAD_INDEX );
358       }
359       if ( idSet.insert( pointIndex ).second ) // unique?
360         myKeyPointIDs.push_back( pointIndex );
361     }
362   }
363
364   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
365
366   while ( readLine( fields, lineBeg, clearFields ))
367   {
368     myElemPointIDs.push_back( TElemDef() );
369     TElemDef& elemPoints = myElemPointIDs.back();
370     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
371     {
372       int pointIndex = getInt( *fIt );
373       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
374         MESSAGE("Error: invalid point index " << pointIndex );
375         Clear();
376         return setErrorCode( ERR_READ_BAD_INDEX );
377       }
378       elemPoints.push_back( pointIndex );
379     }
380     // check the nb of nodes in element
381     bool Ok = true;
382     switch ( elemPoints.size() ) {
383     case 3: if ( !myIs2D ) Ok = false; break;
384     case 4: break;
385     case 5:
386     case 6:
387     case 8: if ( myIs2D ) Ok = false; break;
388     default: Ok = false;
389     }
390     if ( !Ok ) {
391       MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
392       Clear();
393       return setErrorCode( ERR_READ_ELEM_POINTS );
394     }
395   }
396   if ( myElemPointIDs.empty() ) {
397     MESSAGE("Error: no elements");
398     Clear();
399     return setErrorCode( ERR_READ_NO_ELEMS );
400   }
401
402   findBoundaryPoints(); // sort key-points
403
404   return setErrorCode( ERR_OK );
405 }
406
407 //=======================================================================
408 //function : Save
409 //purpose  : Save the loaded pattern into the file <theFileName>
410 //=======================================================================
411
412 bool SMESH_Pattern::Save (ostream& theFile)
413 {
414   Kernel_Utils::Localizer loc;
415     
416   if ( !IsLoaded() ) {
417     MESSAGE(" Pattern not loaded ");
418     return setErrorCode( ERR_SAVE_NOT_LOADED );
419   }
420
421   theFile << "!!! SALOME Mesh Pattern file" << endl;
422   theFile << "!!!" << endl;
423   theFile << "!!! Nb of points:" << endl;
424   theFile << myPoints.size() << endl;
425
426   // point coordinates
427   const int width = 8;
428 //  theFile.width( 8 );
429 //  theFile.setf(ios::fixed);// use 123.45 floating notation
430 //  theFile.setf(ios::right);
431 //  theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
432 //   theFile.setf(ios::showpoint); // do not show trailing zeros
433   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
434   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
435     const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
436     theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
437     if ( !myIs2D ) theFile  << " " << setw( width ) << xyz.Z();
438     theFile  << "  !- " << i << endl; // point id to ease reading by a human being
439   }
440   // key-points
441   if ( myIs2D ) {
442     theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
443     list< int >::const_iterator kpIt = myKeyPointIDs.begin();
444     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
445       theFile << " " << *kpIt;
446     if ( !myKeyPointIDs.empty() )
447       theFile << endl;
448   }
449   // elements
450   theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
451   list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
452   for ( ; epIt != myElemPointIDs.end(); epIt++ )
453   {
454     const TElemDef & elemPoints = *epIt;
455     TElemDef::const_iterator iIt = elemPoints.begin();
456     for ( ; iIt != elemPoints.end(); iIt++ )
457       theFile << " " << *iIt;
458     theFile << endl;
459   }
460
461   theFile << endl;
462
463   return setErrorCode( ERR_OK );
464 }
465
466 //=======================================================================
467 //function : sortBySize
468 //purpose  : sort theListOfList by size
469 //=======================================================================
470
471 template<typename T> struct TSizeCmp {
472   bool operator ()( const list < T > & l1, const list < T > & l2 )
473     const { return l1.size() < l2.size(); }
474 };
475
476 template<typename T> void sortBySize( list< list < T > > & theListOfList )
477 {
478   if ( theListOfList.size() > 2 ) {
479     TSizeCmp< T > SizeCmp;
480     theListOfList.sort( SizeCmp );
481   }
482 }
483
484 //=======================================================================
485 //function : project
486 //purpose  : 
487 //=======================================================================
488
489 static gp_XY project (const SMDS_MeshNode* theNode,
490                       Extrema_GenExtPS &   theProjectorPS)
491 {
492   gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
493   theProjectorPS.Perform( P );
494   if ( !theProjectorPS.IsDone() ) {
495     MESSAGE( "SMESH_Pattern: point projection FAILED");
496     return gp_XY(0.,0.);
497   }
498   double u =0, v =0, minVal = DBL_MAX;
499   for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
500     if ( theProjectorPS.SquareDistance( i ) < minVal ) {
501       minVal = theProjectorPS.SquareDistance( i );
502       theProjectorPS.Point( i ).Parameter( u, v );
503     }
504   return gp_XY( u, v );
505 }
506
507 //=======================================================================
508 //function : areNodesBound
509 //purpose  : true if all nodes of faces are bound to shapes
510 //=======================================================================
511
512 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
513 {
514   while ( faceItr->more() )
515   {
516     SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
517     while ( nIt->more() )
518     {
519       const SMDS_MeshNode* node = smdsNode( nIt->next() );
520       if (node->getshapeId() <1) {
521         return false;
522       }
523     }
524   }
525   return true;
526 }
527
528 //=======================================================================
529 //function : isMeshBoundToShape
530 //purpose  : return true if all 2d elements are bound to shape
531 //           if aFaceSubmesh != NULL, then check faces bound to it
532 //           else check all faces in aMeshDS
533 //=======================================================================
534
535 static bool isMeshBoundToShape(SMESHDS_Mesh *     aMeshDS,
536                                SMESHDS_SubMesh *  aFaceSubmesh,
537                                const bool         isMainShape)
538 {
539   if ( isMainShape && aFaceSubmesh ) {
540     // check that all faces are bound to aFaceSubmesh
541     if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
542       return false;
543   }
544
545   // check face nodes binding
546   if ( aFaceSubmesh ) {
547     SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
548     return areNodesBound( fIt );
549   }
550   SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
551   return areNodesBound( fIt );
552 }
553
554 //=======================================================================
555 //function : Load
556 //purpose  : Create a pattern from the mesh built on <theFace>.
557 //           <theProject>==true makes override nodes positions
558 //           on <theFace> computed by mesher
559 //=======================================================================
560
561 bool SMESH_Pattern::Load (SMESH_Mesh*        theMesh,
562                           const TopoDS_Face& theFace,
563                           bool               theProject,
564                           TopoDS_Vertex      the1stVertex,
565                           bool               theKeepNodes)
566 {
567   Clear();
568   myIs2D = true;
569   myToKeepNodes = theKeepNodes;
570
571   SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
572   SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
573   const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
574   SMESH_MesherHelper helper( *theMesh );
575   helper.SetSubShape( theFace );
576
577   smIdType nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
578   smIdType nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
579   if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
580   {
581     MESSAGE( "No elements bound to the face");
582     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
583   }
584
585   TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
586
587   // check if face is closed
588   bool isClosed = helper.HasSeam();
589   list<TopoDS_Edge> eList;
590   list<TopoDS_Edge>::iterator elIt;
591   SMESH_Block::GetOrderedEdges( face, eList, myNbKeyPntInBoundary, the1stVertex );
592
593   // check that requested or needed projection is possible
594   bool isMainShape = theMesh->IsMainShape( face );
595   bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
596   bool canProject  = ( nbElems ? true : isMainShape );
597   if ( isClosed )
598     canProject = false; // so far
599
600   if ( ( theProject || needProject ) && !canProject )
601     return setErrorCode( ERR_LOADF_CANT_PROJECT );
602
603   Extrema_GenExtPS projector;
604   GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
605   projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
606
607   int iPoint = 0;
608   TNodePointIDMap nodePointIDMap;
609   TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
610
611   if ( needProject )
612   {
613     // ---------------------------------------------------------------
614     // The case where the submesh is projected to theFace
615     // ---------------------------------------------------------------
616
617     // get all faces
618     SMDS_ElemIteratorPtr fIt;
619     if ( nbElems > 0 )
620       fIt = fSubMesh->GetElements();
621     else
622       fIt = aMeshDS->elementsIterator( SMDSAbs_Face );
623
624     // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
625     while ( fIt->more() )
626     {
627       const SMDS_MeshElement* face = fIt->next();
628       myElemPointIDs.push_back( TElemDef() );
629       TElemDef& elemPoints = myElemPointIDs.back();
630       int nbNodes = face->NbCornerNodes();
631       for ( int i = 0;i < nbNodes; ++i )
632       {
633         const SMDS_MeshElement* node = face->GetNode( i );
634         TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
635         if ( nIdIt->second == -1 )
636           nIdIt->second = iPoint++;
637         elemPoints.push_back( (*nIdIt).second );
638       }
639     }
640     myPoints.resize( iPoint );
641
642     // project all nodes of 2d elements to theFace
643     TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
644     for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
645     {
646       const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
647       TPoint * p = & myPoints[ (*nIdIt).second ];
648       p->myInitUV = project( node, projector );
649       p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
650     }
651     // find key-points: the points most close to UV of vertices
652     TopExp_Explorer vExp( face, TopAbs_VERTEX );
653     set<int> foundIndices;
654     for ( ; vExp.More(); vExp.Next() ) {
655       const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
656       gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
657       double minDist = DBL_MAX;
658       int index = 0;
659       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
660       for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
661         double dist = uv.SquareDistance( (*pVecIt).myInitUV );
662         if ( dist < minDist ) {
663           minDist = dist;
664           index = iPoint;
665         }
666       }
667       if ( foundIndices.insert( index ).second ) // unique?
668         myKeyPointIDs.push_back( index );
669     }
670     myIsBoundaryPointsFound = false;
671
672   }
673   else
674   {
675     // ---------------------------------------------------------------------
676     // The case where a pattern is being made from the mesh built by mesher
677     // ---------------------------------------------------------------------
678
679     // Load shapes in the consequent order and count nb of points
680
681     loadVE( eList, myShapeIDMap );
682     myShapeIDMap.Add( face );
683
684     nbNodes += myShapeIDMap.Extent() - 1;
685
686     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
687       if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
688         nbNodes += eSubMesh->NbNodes() + 1;
689
690     myPoints.resize( nbNodes );
691
692     // care of INTERNAL VERTEXes
693     TopExp_Explorer vExp( face, TopAbs_VERTEX, TopAbs_EDGE );
694     for ( ; vExp.More(); vExp.Next() )
695     {
696       const SMDS_MeshNode* node =
697         SMESH_Algo::VertexNode( TopoDS::Vertex( vExp.Current()), aMeshDS );
698       if ( !node || node->NbInverseElements( SMDSAbs_Face ) == 0 )
699         continue;
700       myPoints.resize( ++nbNodes );
701       list< TPoint* > & fPoints = getShapePoints( face );
702       nodePointIDMap.insert( make_pair( node, iPoint ));
703       TPoint* p = &myPoints[ iPoint++ ];
704       fPoints.push_back( p );
705       gp_XY uv = helper.GetNodeUV( face, node );
706       p->myInitUV.SetCoord( uv.X(), uv.Y() );
707       p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
708     }
709
710     // Load U of points on edges
711
712     Bnd_Box2d edgesUVBox;
713
714     list<int>::iterator nbEinW = myNbKeyPntInBoundary.begin();
715     int iE = 0;
716     vector< TopoDS_Edge > eVec;
717     for ( elIt = eList.begin(); elIt != eList.end(); elIt++, iE++ )
718     {
719       if ( isClosed && ( iE == 0 || iE == *nbEinW ))
720       {
721         // new wire begins; put wire EDGEs in eVec
722         list<TopoDS_Edge>::iterator eEnd = elIt;
723         if ( iE == *nbEinW )
724           ++nbEinW;
725         std::advance( eEnd, *nbEinW );
726         eVec.assign( elIt, eEnd );
727         iE = 0;
728       }
729       TopoDS_Edge & edge = *elIt;
730       list< TPoint* > & ePoints = getShapePoints( edge );
731       double f, l;
732       Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
733       bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
734
735       TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
736       TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
737       // to make adjacent edges share key-point, we make v2 FORWARD too
738       // (as we have different points for same shape with different orientation)
739       v2.Reverse();
740
741       // on closed face we must have REVERSED some of seam vertices
742       if ( isClosed ) {
743         if ( helper.IsSeamShape( edge ) ) {
744           if ( helper.IsRealSeam( edge ) && !isForward ) {
745             // reverse on reversed SEAM edge
746             v1.Reverse();
747             v2.Reverse();
748           }
749         }
750         else { // on CLOSED edge (i.e. having one vertex with different orientations)
751           for ( int is2 = 0; is2 < 2; ++is2 ) {
752             TopoDS_Shape & v = is2 ? v2 : v1;
753             if ( helper.IsRealSeam( v ) ) {
754               // reverse or not depending on orientation of adjacent seam
755               int iSeam = helper.WrapIndex( iE + ( is2 ? +1 : -1 ), eVec.size() );
756               if ( eVec[ iSeam ].Orientation() == TopAbs_REVERSED )
757                 v.Reverse();
758             }
759           }
760         }
761       }
762
763       // the forward key-point
764       list< TPoint* > * vPoint = & getShapePoints( v1 );
765       if ( vPoint->empty() )
766       {
767         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
768         if ( vSubMesh && vSubMesh->NbNodes() ) {
769           myKeyPointIDs.push_back( iPoint );
770           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
771           const SMDS_MeshNode* node = nIt->next();
772           if ( v1.Orientation() == TopAbs_REVERSED )
773             closeNodePointIDMap.insert( make_pair( node, iPoint ));
774           else
775             nodePointIDMap.insert( make_pair( node, iPoint ));
776
777           TPoint* keyPoint = &myPoints[ iPoint++ ];
778           vPoint->push_back( keyPoint );
779           if ( theProject )
780             keyPoint->myInitUV = project( node, projector );
781           else
782             keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
783           keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
784           edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
785         }
786       }
787       if ( !vPoint->empty() )
788         ePoints.push_back( vPoint->front() );
789
790       // on-edge points
791       SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
792       if ( eSubMesh && eSubMesh->NbNodes() )
793       {
794         // loop on nodes of an edge: sort them by param on edge
795         typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
796         TParamNodeMap paramNodeMap;
797         int nbMeduimNodes = 0;
798         SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
799         while ( nIt->more() )
800         {
801           const SMDS_MeshNode* node = nIt->next();
802           if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
803             ++nbMeduimNodes;
804             continue;
805           }
806           SMDS_EdgePositionPtr epos = node->GetPosition();
807           double u = epos->GetUParameter();
808           paramNodeMap.insert( make_pair( u, node ));
809         }
810         if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes ) {
811           // wrong U on edge, project
812           Extrema_ExtPC proj;
813           BRepAdaptor_Curve aCurve( edge );
814           proj.Initialize( aCurve, f, l );
815           paramNodeMap.clear();
816           nIt = eSubMesh->GetNodes();
817           for ( int iNode = 0; nIt->more(); ++iNode ) {
818             const SMDS_MeshNode* node = nIt->next();
819             if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
820               continue;
821             proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
822             double u = 0;
823             if ( proj.IsDone() ) {
824               for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
825                 if ( proj.IsMin( i )) {
826                   u = proj.Point( i ).Parameter();
827                   break;
828                 }
829             } else {
830               u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
831             }
832             paramNodeMap.insert( make_pair( u, node ));
833           }
834
835           //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
836           if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
837             return setErrorCode(ERR_UNEXPECTED);
838         }
839
840         // put U in [0,1] so that the first key-point has U==0
841         bool isSeam = helper.IsRealSeam( edge );
842         double du = l - f;
843         TParamNodeMap::iterator         unIt  = paramNodeMap.begin();
844         TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
845         while ( unIt != paramNodeMap.end() )
846         {
847           TPoint* p = & myPoints[ iPoint ];
848           ePoints.push_back( p );
849           const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
850           if ( isSeam && !isForward )
851             closeNodePointIDMap.insert( make_pair( node, iPoint ));
852           else
853             nodePointIDMap.insert ( make_pair( node, iPoint ));
854
855           if ( theProject )
856             p->myInitUV = project( node, projector );
857           else {
858             double u = isForward ? (*unIt).first : (*unRIt).first;
859             p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
860             p->myInitUV = C2d->Value( u ).XY();
861           }
862           p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
863           edgesUVBox.Add( gp_Pnt2d( p->myInitUV ));
864           unIt++; unRIt++;
865           iPoint++;
866         }
867       }
868       // the reverse key-point
869       vPoint = & getShapePoints( v2 );
870       if ( vPoint->empty() )
871       {
872         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
873         if ( vSubMesh && vSubMesh->NbNodes() ) {
874           myKeyPointIDs.push_back( iPoint );
875           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
876           const SMDS_MeshNode* node = nIt->next();
877           if ( v2.Orientation() == TopAbs_REVERSED )
878             closeNodePointIDMap.insert( make_pair( node, iPoint ));
879           else
880             nodePointIDMap.insert( make_pair( node, iPoint ));
881
882           TPoint* keyPoint = &myPoints[ iPoint++ ];
883           vPoint->push_back( keyPoint );
884           if ( theProject )
885             keyPoint->myInitUV = project( node, projector );
886           else
887             keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
888           keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
889           edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
890         }
891       }
892       if ( !vPoint->empty() )
893         ePoints.push_back( vPoint->front() );
894
895       // compute U of edge-points
896       if ( theProject )
897       {
898         double totalDist = 0;
899         list< TPoint* >::iterator pIt = ePoints.begin();
900         TPoint* prevP = *pIt;
901         prevP->myInitU = totalDist;
902         for ( pIt++; pIt != ePoints.end(); pIt++ ) {
903           TPoint* p = *pIt;
904           totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
905           p->myInitU = totalDist;
906           prevP = p;
907         }
908         if ( totalDist > DBL_MIN)
909           for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
910             TPoint* p = *pIt;
911             p->myInitU /= totalDist;
912           }
913       }
914     } // loop on edges of a wire
915
916     // Load in-face points and elements
917
918     if ( fSubMesh && fSubMesh->NbElements() )
919     {
920       list< TPoint* > & fPoints = getShapePoints( face );
921       SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
922       while ( nIt->more() )
923       {
924         const SMDS_MeshNode* node = nIt->next();
925         if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
926           continue;
927         nodePointIDMap.insert( make_pair( node, iPoint ));
928         TPoint* p = &myPoints[ iPoint++ ];
929         fPoints.push_back( p );
930         if ( theProject || edgesUVBox.IsOut( p->myInitUV ) )
931           p->myInitUV = project( node, projector );
932         else {
933           SMDS_FacePositionPtr pos = 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   // The wires are sorted by number of edges to correspond to wires of the pattern
2486   if ( nbWires > 1 )
2487   {
2488     // compute UV of inner edge-points using the method for in-face points
2489     // and divide eList into a list of separate wires
2490     bool aBool;
2491     list< TWire > wireList;
2492     list<TopoDS_Edge>::iterator eIt = elIt;
2493     list<int>::iterator nbEIt = nbVertexInWires.begin();
2494     for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2495     {
2496       int nbEdges = *nbEIt;
2497       wireList.push_back( list< TopoDS_Edge >() );
2498       TWire & wire = wireList.back();
2499       for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2500       {
2501         list< TPoint* > & ePoints = getShapePoints( *eIt );
2502         pIt = ePoints.begin();
2503         for (  pIt++; pIt != ePoints.end(); pIt++ ) {
2504           TPoint* p = (*pIt);
2505           if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2506             MESSAGE("can't Apply(face)");
2507             return false;
2508           }
2509           // keep the computed UV to compare against by setFirstEdge()
2510           p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2511         }
2512         wire.push_back( *eIt );
2513       }
2514     }
2515     // remove inner edges from eList
2516     eList.erase( elIt, eList.end() );
2517
2518     // sort wireList by nb edges in a wire
2519     sortBySize< TopoDS_Edge > ( wireList );
2520
2521     // an ID of the first edge of a boundary
2522     int id1 = nbVertices + nbEdgesInOuterWire + 1;
2523 //     if ( nbSeamShapes > 0 )
2524 //       id1 += 2; // 2 vertices more
2525
2526     // find points - edge correspondence for wires of unique size,
2527     // edge order within a wire should be defined only
2528
2529     list< TWire >::iterator wlIt = wireList.begin();
2530     while ( wlIt != wireList.end() )
2531     {
2532       TWire& wire = (*wlIt);
2533       size_t nbEdges = wire.size();
2534       wlIt++;
2535       if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2536       {
2537         // choose the best first edge of a wire
2538         setFirstEdge( wire, id1 );
2539
2540         // compute eventual UV and collect on-edge points
2541         edgesPointsList.push_back( list< TPoint* >() );
2542         edgesPoints = & edgesPointsList.back();
2543         int eID = id1;
2544         for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2545         {
2546           list< TPoint* > & ePoints = getShapePoints( eID++ );
2547           computeUVOnEdge( *eIt, ePoints );
2548           edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2549         }
2550       }
2551       else
2552       {
2553         // skip same size wires
2554         while ( wlIt != wireList.end() && (*wlIt).size() == nbEdges )
2555           wlIt++;
2556       }
2557       id1 += nbEdges;
2558     }
2559
2560     // find boundary - wire correspondence for several wires of same size
2561
2562     id1 = nbVertices + nbEdgesInOuterWire + 1;
2563     wlIt = wireList.begin();
2564     while ( wlIt != wireList.end() )
2565     {
2566       size_t nbSameSize = 0, nbEdges = (*wlIt).size();
2567       list< TWire >::iterator wlIt2 = wlIt;
2568       wlIt2++;
2569       while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2570         nbSameSize++;
2571         wlIt2++;
2572       }
2573       if ( nbSameSize > 0 )
2574         if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2575           return false;
2576       wlIt = wlIt2;
2577       id1 += nbEdges * ( nbSameSize + 1 );
2578     }
2579
2580     // add well-ordered edges to eList
2581
2582     for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2583     {
2584       TWire& wire = (*wlIt);
2585       eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2586     }
2587
2588     // re-fill myShapeIDMap - all shapes get good IDs
2589
2590     myShapeIDMap.Clear();
2591     nbVertices = loadVE( eList, myShapeIDMap );
2592     myShapeIDMap.Add( face );
2593
2594   } // there are inner wires
2595
2596   // Set XYZ of on-vertex points
2597
2598   // for ( int iV = 1; iV <= nbVertices; ++iV )
2599   // {
2600   //   const TopoDS_Vertex&    V = TopoDS::Vertex( myShapeIDMap( iV ));
2601   //   list< TPoint* > & vPoints = getShapePoints( iV );
2602   //   if ( !vPoints.empty() )
2603   //   {
2604   //     //vPoints.front()->myUV  = BRep_Tool::Parameters( V, theFace ).XY();
2605   //     vPoints.front()->myXYZ = BRep_Tool::Pnt( V );
2606   //   }
2607   // }
2608
2609   // Compute XYZ of on-edge points
2610
2611   TopLoc_Location loc;
2612   for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2613   {
2614     BRepAdaptor_Curve C3d( *elIt );
2615     list< TPoint* > & ePoints = getShapePoints( iE++ );
2616     for ( pIt = ++ePoints.begin(), pEnd = ePoints.end(); pIt != pEnd; pIt++ )
2617     {
2618       TPoint* point = *pIt;
2619       point->myXYZ = C3d.Value( point->myU );
2620     }
2621   }
2622
2623   // Compute UV and XYZ of in-face points
2624
2625   // try to use a simple algo
2626   list< TPoint* > & fPoints = getShapePoints( face );
2627   bool isDeformed = false;
2628   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2629     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2630                                   (*pIt)->myUV, isDeformed )) {
2631       MESSAGE("can't Apply(face)");
2632       return false;
2633     }
2634   // try to use a complex algo if it is a difficult case
2635   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2636   {
2637     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2638       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2639                                     (*pIt)->myUV, isDeformed )) {
2640         MESSAGE("can't Apply(face)");
2641         return false;
2642       }
2643   }
2644
2645   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2646   const gp_Trsf & aTrsf = loc.Transformation();
2647   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2648   {
2649     TPoint * point = *pIt;
2650     point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2651     if ( !loc.IsIdentity() )
2652       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2653   }
2654
2655   myIsComputed = true;
2656
2657   return setErrorCode( ERR_OK );
2658 }
2659
2660 //=======================================================================
2661 //function : Apply
2662 //purpose  : Compute nodes coordinates applying
2663 //           the loaded pattern to <theFace>. The first key-point
2664 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2665 //=======================================================================
2666
2667 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2668                            const int            theNodeIndexOnKeyPoint1,
2669                            const bool           theReverse)
2670 {
2671 //  MESSAGE(" ::Apply(MeshFace) " );
2672
2673   if ( !IsLoaded() ) {
2674     MESSAGE( "Pattern not loaded" );
2675     return setErrorCode( ERR_APPL_NOT_LOADED );
2676   }
2677
2678   // check nb of nodes
2679   const int nbFaceNodes = theFace->NbCornerNodes();
2680   if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2681     MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2682     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2683   }
2684
2685   // find points on edges, it fills myNbKeyPntInBoundary
2686   if ( !findBoundaryPoints() )
2687     return false;
2688
2689   // check that there are no holes in a pattern
2690   if (myNbKeyPntInBoundary.size() > 1 ) {
2691     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2692   }
2693
2694   // Define the nodes order
2695
2696   list< const SMDS_MeshNode* > nodes;
2697   list< const SMDS_MeshNode* >::iterator n = nodes.end();
2698   SMDS_NodeIteratorPtr noIt = theFace->nodeIterator();
2699   int iSub = 0;
2700   while ( noIt->more() && iSub < nbFaceNodes ) {
2701     const SMDS_MeshNode* node = noIt->next();
2702     nodes.push_back( node );
2703     if ( iSub++ == theNodeIndexOnKeyPoint1 )
2704       n = --nodes.end();
2705   }
2706   if ( n != nodes.end() ) {
2707     if ( theReverse ) {
2708       if ( n != --nodes.end() )
2709         nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2710       nodes.reverse();
2711     }
2712     else if ( n != nodes.begin() )
2713       nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2714   }
2715   list< gp_XYZ > xyzList;
2716   myOrderedNodes.resize( nbFaceNodes );
2717   for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2718     xyzList.push_back( SMESH_TNodeXYZ( *n ));
2719     myOrderedNodes[ iSub++] = *n;
2720   }
2721
2722   // Define a face plane
2723
2724   list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2725   gp_Pnt P ( *xyzIt++ );
2726   gp_Vec Vx( P, *xyzIt++ ), N;
2727   do {
2728     N = Vx ^ gp_Vec( P, *xyzIt++ );
2729   } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2730   if ( N.SquareMagnitude() <= DBL_MIN )
2731     return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2732   gp_Ax2 pos( P, N, Vx );
2733
2734   // Compute UV of key-points on a plane
2735   for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2736   {
2737     gp_Vec vec ( pos.Location(), *xyzIt );
2738     TPoint* p = getShapePoints( iSub ).front();
2739     p->myUV.SetX( vec * pos.XDirection() );
2740     p->myUV.SetY( vec * pos.YDirection() );
2741     p->myXYZ = *xyzIt;
2742   }
2743
2744   // points on edges to be used for UV computation of in-face points
2745   list< list< TPoint* > > edgesPointsList;
2746   edgesPointsList.push_back( list< TPoint* >() );
2747   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2748   list< TPoint* >::iterator pIt;
2749
2750   // compute UV and XYZ of points on edges
2751
2752   for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2753   {
2754     gp_XYZ& xyz1 = *xyzIt++;
2755     gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2756
2757     list< TPoint* > & ePoints = getShapePoints( iSub );
2758     ePoints.back()->myInitU = 1.0;
2759     list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2760     while ( *pIt != ePoints.back() )
2761     {
2762       TPoint* p = *pIt++;
2763       p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2764       gp_Vec vec ( pos.Location(), p->myXYZ );
2765       p->myUV.SetX( vec * pos.XDirection() );
2766       p->myUV.SetY( vec * pos.YDirection() );
2767     }
2768     // collect on-edge points (excluding the last one)
2769     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2770   }
2771
2772   // Compute UV and XYZ of in-face points
2773
2774   // try to use a simple algo to compute UV
2775   list< TPoint* > & fPoints = getShapePoints( iSub );
2776   bool isDeformed = false;
2777   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2778     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2779                                   (*pIt)->myUV, isDeformed )) {
2780       MESSAGE("can't Apply(face)");
2781       return false;
2782     }
2783   // try to use a complex algo if it is a difficult case
2784   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2785   {
2786     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2787       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2788                                     (*pIt)->myUV, isDeformed )) {
2789         MESSAGE("can't Apply(face)");
2790         return false;
2791       }
2792   }
2793
2794   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2795   {
2796     (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2797   }
2798
2799   myIsComputed = true;
2800
2801   return setErrorCode( ERR_OK );
2802 }
2803
2804 //=======================================================================
2805 //function : Apply
2806 //purpose  : Compute nodes coordinates applying
2807 //           the loaded pattern to <theFace>. The first key-point
2808 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2809 //=======================================================================
2810
2811 bool SMESH_Pattern::Apply (SMESH_Mesh*          theMesh,
2812                            const SMDS_MeshFace* theFace,
2813                            const TopoDS_Shape&  theSurface,
2814                            const int            theNodeIndexOnKeyPoint1,
2815                            const bool           theReverse)
2816 {
2817 //  MESSAGE(" ::Apply(MeshFace) " );
2818   if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2819     return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2820   }
2821   const TopoDS_Face& face = TopoDS::Face( theSurface );
2822   TopLoc_Location loc;
2823   Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2824   const gp_Trsf & aTrsf = loc.Transformation();
2825
2826   if ( !IsLoaded() ) {
2827     MESSAGE( "Pattern not loaded" );
2828     return setErrorCode( ERR_APPL_NOT_LOADED );
2829   }
2830
2831   // check nb of nodes
2832   if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2833     MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2834     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2835   }
2836
2837   // find points on edges, it fills myNbKeyPntInBoundary
2838   if ( !findBoundaryPoints() )
2839     return false;
2840
2841   // check that there are no holes in a pattern
2842   if (myNbKeyPntInBoundary.size() > 1 ) {
2843     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2844   }
2845
2846   // Define the nodes order
2847
2848   list< const SMDS_MeshNode* > nodes;
2849   list< const SMDS_MeshNode* >::iterator n = nodes.end();
2850   SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2851   int iSub = 0;
2852   while ( noIt->more() ) {
2853     const SMDS_MeshNode* node = smdsNode( noIt->next() );
2854     nodes.push_back( node );
2855     if ( iSub++ == theNodeIndexOnKeyPoint1 )
2856       n = --nodes.end();
2857   }
2858   if ( n != nodes.end() ) {
2859     if ( theReverse ) {
2860       if ( n != --nodes.end() )
2861         nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2862       nodes.reverse();
2863     }
2864     else if ( n != nodes.begin() )
2865       nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2866   }
2867
2868   // find a node not on a seam edge, if necessary
2869   SMESH_MesherHelper helper( *theMesh );
2870   helper.SetSubShape( theSurface );
2871   const SMDS_MeshNode* inFaceNode = 0;
2872   if ( helper.GetNodeUVneedInFaceNode() )
2873   {
2874     SMESH_MeshEditor editor( theMesh );
2875     for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2876       int shapeID = editor.FindShape( *n );
2877       if ( !shapeID )
2878         return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2879       if ( !helper.IsSeamShape( shapeID ))
2880         inFaceNode = *n;
2881     }
2882   }
2883
2884   // Set UV of key-points (i.e. of nodes of theFace )
2885   vector< gp_XY > keyUV( theFace->NbNodes() );
2886   myOrderedNodes.resize( theFace->NbNodes() );
2887   for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2888   {
2889     TPoint* p = getShapePoints( iSub ).front();
2890     p->myUV  = helper.GetNodeUV( face, *n, inFaceNode );
2891     p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2892
2893     keyUV[ iSub-1 ] = p->myUV;
2894     myOrderedNodes[ iSub-1 ] = *n;
2895   }
2896
2897   // points on edges to be used for UV computation of in-face points
2898   list< list< TPoint* > > edgesPointsList;
2899   edgesPointsList.push_back( list< TPoint* >() );
2900   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2901   list< TPoint* >::iterator pIt;
2902
2903   // compute UV and XYZ of points on edges
2904
2905   for ( size_t i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2906   {
2907     gp_XY& uv1 = keyUV[ i ];
2908     gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2909
2910     list< TPoint* > & ePoints = getShapePoints( iSub );
2911     ePoints.back()->myInitU = 1.0;
2912     list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2913     while ( *pIt != ePoints.back() )
2914     {
2915       TPoint* p = *pIt++;
2916       p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2917       p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2918       if ( !loc.IsIdentity() )
2919         aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2920     }
2921     // collect on-edge points (excluding the last one)
2922     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2923   }
2924
2925   // Compute UV and XYZ of in-face points
2926
2927   // try to use a simple algo to compute UV
2928   list< TPoint* > & fPoints = getShapePoints( iSub );
2929   bool isDeformed = false;
2930   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2931     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2932                                   (*pIt)->myUV, isDeformed )) {
2933       MESSAGE("can't Apply(face)");
2934       return false;
2935     }
2936   // try to use a complex algo if it is a difficult case
2937   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2938   {
2939     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2940       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2941                                     (*pIt)->myUV, isDeformed )) {
2942         MESSAGE("can't Apply(face)");
2943         return false;
2944       }
2945   }
2946
2947   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2948   {
2949     TPoint * point = *pIt;
2950     point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2951     if ( !loc.IsIdentity() )
2952       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2953   }
2954
2955   myIsComputed = true;
2956
2957   return setErrorCode( ERR_OK );
2958 }
2959
2960 //=======================================================================
2961 //function : undefinedXYZ
2962 //purpose  : 
2963 //=======================================================================
2964
2965 static const gp_XYZ& undefinedXYZ()
2966 {
2967   static gp_XYZ xyz( 1.e100, 0., 0. );
2968   return xyz;
2969 }
2970
2971 //=======================================================================
2972 //function : isDefined
2973 //purpose  : 
2974 //=======================================================================
2975
2976 inline static bool isDefined(const gp_XYZ& theXYZ)
2977 {
2978   return theXYZ.X() < 1.e100;
2979 }
2980
2981 //=======================================================================
2982 //function : Apply
2983 //purpose  : Compute nodes coordinates applying
2984 //           the loaded pattern to <theFaces>. The first key-point
2985 //           will be mapped into <theNodeIndexOnKeyPoint1>-th node
2986 //=======================================================================
2987
2988 bool SMESH_Pattern::Apply (SMESH_Mesh*                     theMesh,
2989                            std::set<const SMDS_MeshFace*>& theFaces,
2990                            const int                       theNodeIndexOnKeyPoint1,
2991                            const bool                      theReverse)
2992 {
2993   MESSAGE(" ::Apply(set<MeshFace>) " );
2994
2995   if ( !IsLoaded() ) {
2996     MESSAGE( "Pattern not loaded" );
2997     return setErrorCode( ERR_APPL_NOT_LOADED );
2998   }
2999
3000   // find points on edges, it fills myNbKeyPntInBoundary
3001   if ( !findBoundaryPoints() )
3002     return false;
3003
3004   // check that there are no holes in a pattern
3005   if (myNbKeyPntInBoundary.size() > 1 ) {
3006     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3007   }
3008
3009   myShape.Nullify();
3010   myXYZ.clear();
3011   myElemXYZIDs.clear();
3012   myXYZIdToNodeMap.clear();
3013   myElements.clear();
3014   myIdsOnBoundary.clear();
3015   myReverseConnectivity.clear();
3016
3017   myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
3018   myElements.reserve( theFaces.size() );
3019
3020   int ind1 = 0; // lowest point index for a face
3021
3022   // meshed geometry
3023   TopoDS_Shape shape;
3024 //   int          shapeID = 0;
3025 //   SMESH_MeshEditor editor( theMesh );
3026
3027   // apply to each face in theFaces set
3028   set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
3029   for ( ; face != theFaces.end(); ++face )
3030   {
3031 //     int curShapeId = editor.FindShape( *face );
3032 //     if ( curShapeId != shapeID ) {
3033 //       if ( curShapeId )
3034 //         shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
3035 //       else
3036 //         shape.Nullify();
3037 //       shapeID = curShapeId;
3038 //     }
3039     bool ok;
3040     if ( shape.IsNull() )
3041       ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
3042     else
3043       ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
3044     if ( !ok ) {
3045       MESSAGE( "Failed on " << *face );
3046       continue;
3047     }
3048     myElements.push_back( *face );
3049
3050     // store computed points belonging to elements
3051     list< TElemDef >::iterator ll = myElemPointIDs.begin();
3052     for ( ; ll != myElemPointIDs.end(); ++ll )
3053     {
3054       myElemXYZIDs.push_back(TElemDef());
3055       TElemDef& xyzIds = myElemXYZIDs.back();
3056       TElemDef& pIds = *ll;
3057       for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3058         int pIndex = *id + ind1;
3059         xyzIds.push_back( pIndex );
3060         myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3061         myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3062       }
3063     }
3064     // put points on links to myIdsOnBoundary,
3065     // they will be used to sew new elements on adjacent refined elements
3066     int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3067     for ( int i = 0; i < nbNodes; i++ )
3068     {
3069       list< TPoint* > & linkPoints = getShapePoints( eID++ );
3070       const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3071       const SMDS_MeshNode* n2 = myOrderedNodes[( i+1 ) % nbNodes ];
3072       // make a link and a node set
3073       TNodeSet linkSet, node1Set;
3074       linkSet.insert( n1 );
3075       linkSet.insert( n2 );
3076       node1Set.insert( n1 );
3077       list< TPoint* >::iterator p = linkPoints.begin();
3078       {
3079         // map the first link point to n1
3080         int nId = ( *p - &myPoints[0] ) + ind1;
3081         myXYZIdToNodeMap[ nId ] = n1;
3082         list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3083         groups.push_back(list< int > ());
3084         groups.back().push_back( nId );
3085       }
3086       // add the linkSet to the map
3087       list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3088       groups.push_back(list< int > ());
3089       list< int >& indList = groups.back();
3090       // add points to the map excluding the end points
3091       for ( p++; *p != linkPoints.back(); p++ )
3092         indList.push_back( ( *p - &myPoints[0] ) + ind1 );
3093     }
3094     ind1 += myPoints.size();
3095   }
3096
3097   return !myElemXYZIDs.empty();
3098 }
3099
3100 //=======================================================================
3101 //function : Apply
3102 //purpose  : Compute nodes coordinates applying
3103 //           the loaded pattern to <theVolumes>. The (0,0,0) key-point
3104 //           will be mapped into <theNode000Index>-th node. The
3105 //           (0,0,1) key-point will be mapped into <theNode000Index>-th
3106 //           node.
3107 //=======================================================================
3108
3109 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3110                            const int                          theNode000Index,
3111                            const int                          theNode001Index)
3112 {
3113   if ( !IsLoaded() ) {
3114     MESSAGE( "Pattern not loaded" );
3115     return setErrorCode( ERR_APPL_NOT_LOADED );
3116   }
3117
3118    // bind ID to points
3119   if ( !findBoundaryPoints() )
3120     return false;
3121
3122   // check that there are no holes in a pattern
3123   if (myNbKeyPntInBoundary.size() > 1 ) {
3124     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3125   }
3126
3127   myShape.Nullify();
3128   myXYZ.clear();
3129   myElemXYZIDs.clear();
3130   myXYZIdToNodeMap.clear();
3131   myElements.clear();
3132   myIdsOnBoundary.clear();
3133   myReverseConnectivity.clear();
3134
3135   myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3136   myElements.reserve( theVolumes.size() );
3137
3138   // to find point index
3139   map< TPoint*, int > pointIndex;
3140   for ( size_t i = 0; i < myPoints.size(); i++ )
3141     pointIndex.insert( make_pair( & myPoints[ i ], i ));
3142
3143   int ind1 = 0; // lowest point index for an element
3144
3145   // apply to each element in theVolumes set
3146   set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3147   for ( ; vol != theVolumes.end(); ++vol )
3148   {
3149     if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3150       MESSAGE( "Failed on " << *vol );
3151       continue;
3152     }
3153     myElements.push_back( *vol );
3154
3155     // store computed points belonging to elements
3156     list< TElemDef >::iterator ll = myElemPointIDs.begin();
3157     for ( ; ll != myElemPointIDs.end(); ++ll )
3158     {
3159       myElemXYZIDs.push_back(TElemDef());
3160       TElemDef& xyzIds = myElemXYZIDs.back();
3161       TElemDef& pIds = *ll;
3162       for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3163         int pIndex = *id + ind1;
3164         xyzIds.push_back( pIndex );
3165         myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3166         myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3167       }
3168     }
3169     // put points on edges and faces to myIdsOnBoundary,
3170     // they will be used to sew new elements on adjacent refined elements
3171     for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3172     {
3173       // make a set of sub-points
3174       TNodeSet subNodes;
3175       vector< int > subIDs;
3176       if ( SMESH_Block::IsVertexID( Id )) {
3177         subNodes.insert( myOrderedNodes[ Id - 1 ]);
3178       }
3179       else if ( SMESH_Block::IsEdgeID( Id )) {
3180         SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3181         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3182         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3183       }
3184       else {
3185         SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3186         int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3187         SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3188         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3189         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3190         SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3191         subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3192         subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3193       }
3194       // add points
3195       list< TPoint* > & points = getShapePoints( Id );
3196       list< TPoint* >::iterator p = points.begin();
3197       list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3198       groups.push_back(list< int > ());
3199       list< int >& indList = groups.back();
3200       for ( ; p != points.end(); p++ )
3201         indList.push_back( pointIndex[ *p ] + ind1 );
3202       if ( subNodes.size() == 1 ) // vertex case
3203         myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3204     }
3205     ind1 += myPoints.size();
3206   }
3207
3208   return !myElemXYZIDs.empty();
3209 }
3210
3211 //=======================================================================
3212 //function : Load
3213 //purpose  : Create a pattern from the mesh built on <theBlock>
3214 //=======================================================================
3215
3216 bool SMESH_Pattern::Load (SMESH_Mesh*         theMesh,
3217                           const TopoDS_Shell& theBlock,
3218                           bool                theKeepNodes)
3219 {
3220   Clear();
3221   myIs2D = false;
3222   myToKeepNodes = theKeepNodes;
3223   SMESHDS_SubMesh * aSubMesh;
3224
3225   const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3226
3227   // load shapes in myShapeIDMap
3228   SMESH_Block block;
3229   TopoDS_Vertex v1, v2;
3230   if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3231     return setErrorCode( ERR_LOADV_BAD_SHAPE );
3232
3233   // count nodes
3234   smIdType nbNodes = 0; int shapeID;
3235   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3236   {
3237     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3238     aSubMesh = getSubmeshWithElements( theMesh, S );
3239     if ( aSubMesh )
3240       nbNodes += aSubMesh->NbNodes();
3241   }
3242   myPoints.resize( nbNodes );
3243
3244   // load U of points on edges
3245   TNodePointIDMap nodePointIDMap;
3246   int iPoint = 0;
3247   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3248   {
3249     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3250     list< TPoint* > & shapePoints = getShapePoints( shapeID );
3251     aSubMesh = getSubmeshWithElements( theMesh, S );
3252     if ( ! aSubMesh ) continue;
3253     SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3254     if ( !nIt->more() ) continue;
3255
3256     // store a node and a point
3257     while ( nIt->more() ) {
3258       const SMDS_MeshNode* node = smdsNode( nIt->next() );
3259       if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3260         continue;
3261       nodePointIDMap.insert( make_pair( node, iPoint ));
3262       if ( block.IsVertexID( shapeID ))
3263         myKeyPointIDs.push_back( iPoint );
3264       TPoint* p = & myPoints[ iPoint++ ];
3265       shapePoints.push_back( p );
3266       p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3267       p->myInitXYZ.SetCoord( 0,0,0 );
3268     }
3269     list< TPoint* >::iterator pIt = shapePoints.begin();
3270
3271     // compute init XYZ
3272     switch ( S.ShapeType() )
3273     {
3274     case TopAbs_VERTEX:
3275     case TopAbs_EDGE: {
3276
3277       for ( ; pIt != shapePoints.end(); pIt++ ) {
3278         double * coef = block.GetShapeCoef( shapeID );
3279         for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3280           if ( coef[ iCoord - 1] > 0 )
3281             (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3282       }
3283       if ( S.ShapeType() == TopAbs_VERTEX )
3284         break;
3285
3286       const TopoDS_Edge& edge = TopoDS::Edge( S );
3287       double f,l;
3288       BRep_Tool::Range( edge, f, l );
3289       int iCoord     = SMESH_Block::GetCoordIndOnEdge( shapeID );
3290       bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3291       pIt = shapePoints.begin();
3292       nIt = aSubMesh->GetNodes();
3293       for ( ; nIt->more(); pIt++ )
3294       {
3295         const SMDS_MeshNode* node = nIt->next();
3296         if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3297           continue;
3298         SMDS_EdgePositionPtr epos = node->GetPosition();
3299         double u = ( epos->GetUParameter() - f ) / ( l - f );
3300         (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3301       }
3302       break;
3303     }
3304     default:
3305       for ( ; pIt != shapePoints.end(); pIt++ )
3306       {
3307         if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3308           MESSAGE( "!block.ComputeParameters()" );
3309           return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3310         }
3311       }
3312     }
3313   } // loop on block sub-shapes
3314
3315   // load elements
3316
3317   aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3318   if ( aSubMesh )
3319   {
3320     SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3321     while ( elemIt->more() ) {
3322       const SMDS_MeshElement* elem = elemIt->next();
3323       myElemPointIDs.push_back( TElemDef() );
3324       TElemDef& elemPoints = myElemPointIDs.back();
3325       int nbNodes = elem->NbCornerNodes();
3326       for ( int i = 0;i < nbNodes; ++i )
3327         elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3328     }
3329   }
3330
3331   myIsBoundaryPointsFound = true;
3332
3333   if ( myToKeepNodes )
3334   {
3335     myInNodes.resize( nodePointIDMap.size() );
3336     TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
3337     for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
3338       myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
3339   }
3340
3341   return setErrorCode( ERR_OK );
3342 }
3343
3344 //=======================================================================
3345 //function : getSubmeshWithElements
3346 //purpose  : return submesh containing elements bound to theBlock in theMesh
3347 //=======================================================================
3348
3349 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh*         theMesh,
3350                                                         const TopoDS_Shape& theShape)
3351 {
3352   SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3353   if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3354     return aSubMesh;
3355
3356   if ( theShape.ShapeType() == TopAbs_SHELL )
3357   {
3358     // look for submesh of VOLUME
3359     TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3360     for (; it.More(); it.Next()) {
3361       aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3362       if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3363         return aSubMesh;
3364     }
3365   }
3366   return 0;
3367 }
3368
3369
3370 //=======================================================================
3371 //function : Apply
3372 //purpose  : Compute nodes coordinates applying
3373 //           the loaded pattern to <theBlock>. The (0,0,0) key-point
3374 //           will be mapped into <theVertex000>. The (0,0,1)
3375 //           fifth key-point will be mapped into <theVertex001>.
3376 //=======================================================================
3377
3378 bool SMESH_Pattern::Apply (const TopoDS_Shell&  theBlock,
3379                            const TopoDS_Vertex& theVertex000,
3380                            const TopoDS_Vertex& theVertex001)
3381 {
3382   if (!findBoundaryPoints()     || // bind ID to points
3383       !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3384     return false;
3385
3386   SMESH_Block block;  // bind ID to shape
3387   if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3388     return setErrorCode( ERR_APPLV_BAD_SHAPE );
3389
3390   // compute XYZ of points on shapes
3391
3392   for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3393   {
3394     list< TPoint* > & shapePoints = getShapePoints( shapeID );
3395     list< TPoint* >::iterator pIt = shapePoints.begin();
3396     const TopoDS_Shape& S = myShapeIDMap( shapeID );
3397     switch ( S.ShapeType() )
3398     {
3399     case TopAbs_VERTEX: {
3400
3401       for ( ; pIt != shapePoints.end(); pIt++ )
3402         block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3403       break;
3404     }
3405     case TopAbs_EDGE: {
3406
3407       for ( ; pIt != shapePoints.end(); pIt++ )
3408         block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3409       break;
3410     }
3411     case TopAbs_FACE: {
3412
3413       for ( ; pIt != shapePoints.end(); pIt++ )
3414         block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3415       break;
3416     }
3417     default:
3418       for ( ; pIt != shapePoints.end(); pIt++ )
3419         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3420     }
3421   } // loop on block sub-shapes
3422
3423   myIsComputed = true;
3424
3425   return setErrorCode( ERR_OK );
3426 }
3427
3428 //=======================================================================
3429 //function : Apply
3430 //purpose  : Compute nodes coordinates applying
3431 //           the loaded pattern to <theVolume>. The (0,0,0) key-point
3432 //           will be mapped into <theNode000Index>-th node. The
3433 //           (0,0,1) key-point will be mapped into <theNode000Index>-th
3434 //           node.
3435 //=======================================================================
3436
3437 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3438                            const int              theNode000Index,
3439                            const int              theNode001Index)
3440 {
3441   if (!findBoundaryPoints()) // bind ID to points
3442     return false;
3443
3444   SMESH_Block block;  // bind ID to shape
3445   if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3446     return setErrorCode( ERR_APPLV_BAD_SHAPE );
3447   // compute XYZ of points on shapes
3448
3449   for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3450   {
3451     list< TPoint* > & shapePoints = getShapePoints( ID );
3452     list< TPoint* >::iterator pIt = shapePoints.begin();
3453
3454     if ( block.IsVertexID( ID ))
3455       for ( ; pIt != shapePoints.end(); pIt++ ) {
3456         block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3457       }
3458     else if ( block.IsEdgeID( ID ))
3459       for ( ; pIt != shapePoints.end(); pIt++ ) {
3460         block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3461       }
3462     else if ( block.IsFaceID( ID ))
3463       for ( ; pIt != shapePoints.end(); pIt++ ) {
3464         block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3465       }
3466     else
3467       for ( ; pIt != shapePoints.end(); pIt++ )
3468         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3469   } // loop on block sub-shapes
3470
3471   myIsComputed = true;
3472
3473   return setErrorCode( ERR_OK );
3474 }
3475
3476 //=======================================================================
3477 //function : mergePoints
3478 //purpose  : Merge XYZ on edges and/or faces.
3479 //=======================================================================
3480
3481 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3482 {
3483   map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3484   for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3485   {
3486     list<list< int > >& groups = idListIt->second;
3487     if ( groups.size() < 2 )
3488       continue;
3489
3490     // find tolerance
3491     const TNodeSet& nodes = idListIt->first;
3492     double tol2 = 1.e-10;
3493     if ( nodes.size() > 1 ) {
3494       Bnd_Box box;
3495       TNodeSet::const_iterator n = nodes.begin();
3496       for ( ; n != nodes.end(); ++n )
3497         box.Add( gp_Pnt( SMESH_TNodeXYZ( *n )));
3498       double x, y, z, X, Y, Z;
3499       box.Get( x, y, z, X, Y, Z );
3500       gp_Pnt p( x, y, z ), P( X, Y, Z );
3501       tol2 = 1.e-4 * p.SquareDistance( P );
3502     }
3503
3504     // to unite groups on link
3505     bool unite = ( uniteGroups && nodes.size() == 2 );
3506     map< double, int > distIndMap;
3507     const SMDS_MeshNode* node = *nodes.begin();
3508     gp_Pnt P = SMESH_TNodeXYZ( node );
3509
3510     // compare points, replace indices
3511
3512     list< int >::iterator ind1, ind2;
3513     list< list< int > >::iterator grpIt1, grpIt2;
3514     for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3515     {
3516       list< int >& indices1 = *grpIt1;
3517       grpIt2 = grpIt1;
3518       for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3519       {
3520         list< int >& indices2 = *grpIt2;
3521         for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3522         {
3523           gp_XYZ& p1 = myXYZ[ *ind1 ];
3524           ind2 = indices2.begin();
3525           while ( ind2 != indices2.end() )
3526           {
3527             gp_XYZ& p2 = myXYZ[ *ind2 ];
3528             //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3529             if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3530             {
3531               ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3532               list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3533               list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3534               for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3535               {
3536                 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3537                 myXYZ[ *ind2 ] = undefinedXYZ();
3538                 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3539               }
3540               ind2 = indices2.erase( ind2 );
3541             }
3542             else
3543               ind2++;
3544           }
3545         }
3546       }
3547       if ( unite ) { // sort indices using distIndMap
3548         for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3549         {
3550           ASSERT( isDefined( myXYZ[ *ind1 ] ));
3551           double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3552           distIndMap.insert( make_pair( dist, *ind1 ));
3553         }
3554       }
3555     }
3556     if ( unite ) { // put all sorted indices into the first group
3557       list< int >& g = groups.front();
3558       g.clear();
3559       map< double, int >::iterator dist_ind = distIndMap.begin();
3560       for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3561         g.push_back( dist_ind->second );
3562     }
3563   } // loop on myIdsOnBoundary
3564 }
3565
3566 //=======================================================================
3567 //function : makePolyElements
3568 //purpose  : prepare intermediate data to create Polygons and Polyhedrons
3569 //=======================================================================
3570
3571 void SMESH_Pattern::
3572   makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3573                    const bool                            toCreatePolygons,
3574                    const bool                            toCreatePolyedrs)
3575 {
3576   myPolyElemXYZIDs.clear();
3577   myPolyElems.clear();
3578   myPolyElems.reserve( myIdsOnBoundary.size() );
3579
3580   // make a set of refined elements
3581   TIDSortedElemSet elemSet, avoidSet( myElements.begin(), myElements.end() );
3582
3583   map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3584
3585   if ( toCreatePolygons )
3586   {
3587     int lastFreeId = myXYZ.size();
3588
3589     // loop on links of refined elements
3590     indListIt = myIdsOnBoundary.begin();
3591     for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3592     {
3593       const TNodeSet & linkNodes = indListIt->first;
3594       if ( linkNodes.size() != 2 )
3595         continue; // skip face
3596       const SMDS_MeshNode* n1 = * linkNodes.begin();
3597       const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3598
3599       list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3600       if ( idGroups.empty() || idGroups.front().empty() )
3601         continue;
3602
3603       // find not refined face having n1-n2 link
3604
3605       while (true)
3606       {
3607         const SMDS_MeshElement* face =
3608           SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3609         if ( face )
3610         {
3611           avoidSet.insert ( face );
3612           myPolyElems.push_back( face );
3613
3614           // some links of <face> are split;
3615           // make list of xyz for <face>
3616           myPolyElemXYZIDs.push_back(TElemDef());
3617           TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3618           // loop on links of a <face>
3619           SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3620           int i = 0, nbNodes = face->NbNodes();
3621           vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3622           while ( nIt->more() )
3623             nodes[ i++ ] = smdsNode( nIt->next() );
3624           nodes[ i ] = nodes[ 0 ];
3625           for ( i = 0; i < nbNodes; ++i )
3626           {
3627             // look for point mapped on a link
3628             TNodeSet faceLinkNodes;
3629             faceLinkNodes.insert( nodes[ i ] );
3630             faceLinkNodes.insert( nodes[ i + 1 ] );
3631             if ( faceLinkNodes == linkNodes )
3632               nn_IdList = indListIt;
3633             else
3634               nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3635             // add face point ids
3636             faceNodeIds.push_back( ++lastFreeId );
3637             myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3638             if ( nn_IdList != myIdsOnBoundary.end() )
3639             {
3640               // there are points mapped on a link
3641               list< int >& mappedIds = nn_IdList->second.front();
3642               if ( isReversed( nodes[ i ], mappedIds ))
3643                 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3644               else
3645                 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3646             }
3647           } // loop on links of a <face>
3648         } // if ( face )
3649         else
3650           break;
3651       } // while (true)
3652
3653       if ( myIs2D && idGroups.size() > 1 ) {
3654
3655         // sew new elements on 2 refined elements sharing n1-n2 link
3656
3657         list< int >& idsOnLink = idGroups.front();
3658         // temporarily add ids of link nodes to idsOnLink
3659         bool rev = isReversed( n1, idsOnLink );
3660         for ( int i = 0; i < 2; ++i )
3661         {
3662           TNodeSet nodeSet;
3663           nodeSet.insert( i ? n2 : n1 );
3664           ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3665           list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3666           int nodeId = groups.front().front();
3667           bool append = i;
3668           if ( rev ) append = !append;
3669           if ( append )
3670             idsOnLink.push_back( nodeId );
3671           else
3672             idsOnLink.push_front( nodeId );
3673         }
3674         list< int >::iterator id = idsOnLink.begin();
3675         for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3676         {
3677           list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3678           list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3679           for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3680           {
3681             TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3682             // look for <id> in element definition
3683             TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3684             ASSERT ( idDef != pIdList->end() );
3685             // look for 2 neighbour ids of <id> in element definition
3686             for ( int prev = 0; prev < 2; ++prev ) {
3687               TElemDef::iterator idDef2 = idDef;
3688               if ( prev )
3689                 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3690               else
3691                 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3692               // look for idDef2 on a link starting from id
3693               list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3694               if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3695                 // insert ids located on link between <id> and <id2>
3696                 // into the element definition between idDef and idDef2
3697                 if ( prev )
3698                   for ( ; id2 != id; --id2 )
3699                     pIdList->insert( idDef, *id2 );
3700                 else {
3701                   list< int >::iterator id1 = id;
3702                   for ( ++id1, ++id2; id1 != id2; ++id1 )
3703                     pIdList->insert( idDef2, *id1 );
3704                 }
3705               }
3706             }
3707           }
3708         }
3709         // remove ids of link nodes
3710         idsOnLink.pop_front();
3711         idsOnLink.pop_back();
3712       }
3713     } // loop on myIdsOnBoundary
3714   } // if ( toCreatePolygons )
3715
3716   if ( toCreatePolyedrs )
3717   {
3718     // check volumes adjacent to the refined elements
3719     SMDS_VolumeTool volTool;
3720     vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3721     for ( ; refinedElem != myElements.end(); ++refinedElem )
3722     {
3723       // loop on nodes of refinedElem
3724       SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3725       while ( nIt->more() ) {
3726         const SMDS_MeshNode* node = smdsNode( nIt->next() );
3727         // loop on inverse elements of node
3728         SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3729         while ( eIt->more() )
3730         {
3731           const SMDS_MeshElement* elem = eIt->next();
3732           if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3733             continue; // skip faces or refined elements
3734           // add polyhedron definition
3735           myPolyhedronQuantities.push_back(vector<int> ());
3736           myPolyElemXYZIDs.push_back(TElemDef());
3737           vector<int>& quantity = myPolyhedronQuantities.back();
3738           TElemDef &   elemDef  = myPolyElemXYZIDs.back();
3739           // get definitions of new elements on volume faces
3740           bool makePoly = false;
3741           for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3742           {
3743             if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3744                                     volTool.NbFaceNodes( iF ),
3745                                     theNodes, elemDef, quantity))
3746               makePoly = true;
3747           }
3748           if ( makePoly )
3749             myPolyElems.push_back( elem );
3750           else {
3751             myPolyhedronQuantities.pop_back();
3752             myPolyElemXYZIDs.pop_back();
3753           }
3754         }
3755       }
3756     }
3757   }
3758 }
3759
3760 //=======================================================================
3761 //function : getFacesDefinition
3762 //purpose  : return faces definition for a volume face defined by theBndNodes
3763 //=======================================================================
3764
3765 bool SMESH_Pattern::
3766   getFacesDefinition(const SMDS_MeshNode**                 theBndNodes,
3767                      const int                             theNbBndNodes,
3768                      const vector< const SMDS_MeshNode* >& theNodes,
3769                      list< int >&                          theFaceDefs,
3770                      vector<int>&                          theQuantity)
3771 {
3772   bool makePoly = false;
3773
3774   set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3775
3776   map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3777
3778   // make a set of all nodes on a face
3779   set< int > ids;
3780   if ( !myIs2D ) { // for 2D, merge only edges
3781     nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3782     if ( nn_IdList != myIdsOnBoundary.end() ) {
3783       list< int > & faceIds = nn_IdList->second.front();
3784       if ( !faceIds.empty() ) {
3785         makePoly = true;
3786         ids.insert( faceIds.begin(), faceIds.end() );
3787       }
3788     }
3789   }
3790
3791   // add ids on links and bnd nodes
3792   int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3793   TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3794   for ( int iN = 0; iN < theNbBndNodes; ++iN )
3795   {
3796     // add id of iN-th bnd node
3797     TNodeSet nSet;
3798     nSet.insert( theBndNodes[ iN ] );
3799     nn_IdList = myIdsOnBoundary.find( nSet );
3800     int bndId = ++lastFreeId;
3801     if ( nn_IdList != myIdsOnBoundary.end() ) {
3802       bndId = nn_IdList->second.front().front();
3803       ids.insert( bndId );
3804     }
3805     else {
3806       myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3807     }
3808     faceDef.push_back( bndId );
3809     // add ids on a link
3810     TNodeSet linkNodes;
3811     linkNodes.insert( theBndNodes[ iN ]);
3812     linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3813     nn_IdList = myIdsOnBoundary.find( linkNodes );
3814     if ( nn_IdList != myIdsOnBoundary.end() ) {
3815       list< int > & linkIds = nn_IdList->second.front();
3816       if ( !linkIds.empty() )
3817       {
3818         makePoly = true;
3819         ids.insert( linkIds.begin(), linkIds.end() );
3820         if ( isReversed( theBndNodes[ iN ], linkIds ))
3821           faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3822         else
3823           faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3824       }
3825     }
3826   }
3827
3828   // find faces definition of new volumes
3829
3830   bool defsAdded = false;
3831   if ( !myIs2D ) { // for 2D, merge only edges
3832     SMDS_VolumeTool vol;
3833     set< TElemDef* > checkedVolDefs;
3834     set< int >::iterator id = ids.begin();
3835     for ( ; id != ids.end(); ++id )
3836     {
3837       // definitions of volumes sharing id
3838       list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3839       ASSERT( !defList.empty() );
3840       // loop on volume definitions
3841       list< TElemDef* >::iterator pIdList = defList.begin();
3842       for ( ; pIdList != defList.end(); ++pIdList)
3843       {
3844         if ( !checkedVolDefs.insert( *pIdList ).second )
3845           continue; // skip already checked volume definition
3846         vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3847         // loop on face defs of a volume
3848         SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3849         if ( volType == SMDS_VolumeTool::UNKNOWN )
3850           continue;
3851         int nbFaces = vol.NbFaces( volType );
3852         for ( int iF = 0; iF < nbFaces; ++iF )
3853         {
3854           const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3855           int iN, nbN = vol.NbFaceNodes( volType, iF );
3856           // check if all nodes of a faces are in <ids>
3857           bool all = true;
3858           for ( iN = 0; iN < nbN && all; ++iN ) {
3859             int nodeId = idVec[ nodeInds[ iN ]];
3860             all = ( ids.find( nodeId ) != ids.end() );
3861           }
3862           if ( all ) {
3863             // store a face definition
3864             for ( iN = 0; iN < nbN; ++iN ) {
3865               theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3866             }
3867             theQuantity.push_back( nbN );
3868             defsAdded = true;
3869           }
3870         }
3871       }
3872     }
3873   }
3874   if ( !defsAdded ) {
3875     theQuantity.push_back( faceDef.size() );
3876     theFaceDefs.splice( theFaceDefs.end(), faceDef );
3877   }
3878
3879   return makePoly;
3880 }
3881
3882 //=======================================================================
3883 //function : clearSubMesh
3884 //purpose  : 
3885 //=======================================================================
3886
3887 static bool clearSubMesh( SMESH_Mesh*         theMesh,
3888                           const TopoDS_Shape& theShape)
3889 {
3890   bool removed = false;
3891   if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3892   {
3893     removed = !aSubMesh->IsEmpty();
3894     if ( removed )
3895       aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3896   }
3897   else {
3898     SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3899     if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3900     {
3901       SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3902       removed = eIt->more();
3903       while ( eIt->more() )
3904         aMeshDS->RemoveElement( eIt->next() );
3905       SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3906       removed = removed || nIt->more();
3907       while ( nIt->more() )
3908         aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3909     }
3910   }
3911   return removed;
3912 }
3913
3914 //=======================================================================
3915 //function : clearMesh
3916 //purpose  : clear mesh elements existing on myShape in theMesh
3917 //=======================================================================
3918
3919 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3920 {
3921
3922   if ( !myShape.IsNull() )
3923   {
3924     if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3925       TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3926       for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3927       {
3928         clearSubMesh( theMesh, it.Value() );
3929       }
3930     }
3931   }
3932 }
3933
3934 //=======================================================================
3935 //function : findExistingNodes
3936 //purpose  : fills nodes vector with nodes existing on a given shape (IMP 22368)
3937 //           Returns true if all nodes for all points on S are found
3938 //=======================================================================
3939
3940 bool SMESH_Pattern::findExistingNodes( SMESH_Mesh*                      mesh,
3941                                        const TopoDS_Shape&              S,
3942                                        const std::list< TPoint* > &     points,
3943                                        vector< const SMDS_MeshNode* > & nodesVector)
3944 {
3945   if ( S.IsNull() || points.empty() )
3946     return false;
3947
3948   SMESHDS_Mesh* aMeshDS = mesh->GetMeshDS();
3949
3950   switch ( S.ShapeType() )
3951   {
3952   case TopAbs_VERTEX:
3953   {
3954     int pIndex = points.back() - &myPoints[0];
3955     if ( !nodesVector[ pIndex ] )
3956       nodesVector[ pIndex ] = SMESH_Algo::VertexNode( TopoDS::Vertex( S ), aMeshDS );
3957     return nodesVector[ pIndex ];
3958   }
3959   case TopAbs_EDGE:
3960   {
3961     const TopoDS_Edge& edge = TopoDS::Edge( S );
3962     map< double, const SMDS_MeshNode* > paramsOfNodes;
3963     if ( !SMESH_Algo::GetSortedNodesOnEdge( aMeshDS, edge,
3964                                             /*ignoreMediumNodes=*/false,
3965                                             paramsOfNodes )
3966          || paramsOfNodes.size() < 3 )
3967       break;
3968     // points on VERTEXes are included with wrong myU
3969     list< TPoint* >::const_reverse_iterator pItR = ++points.rbegin();
3970     list< TPoint* >::const_iterator         pItF = ++points.begin();
3971     const bool isForward = ( (*pItF)->myU < (*pItR)->myU );
3972     map< double, const SMDS_MeshNode* >::iterator u2n    = ++paramsOfNodes.begin();
3973     map< double, const SMDS_MeshNode* >::iterator u2nEnd = --paramsOfNodes.end();
3974     TPoint* p;
3975     if ( paramsOfNodes.size() == points.size() )
3976     {
3977       for ( ; u2n != u2nEnd; ++u2n )
3978       {
3979         p = ( isForward ? *pItF : *pItR );
3980         int pIndex = p - &myPoints[0];
3981         if ( !nodesVector [ pIndex ] )
3982           nodesVector [ pIndex ] = u2n->second;
3983         ++pItF;
3984         ++pItR;
3985       }
3986       return true;
3987     }
3988     else
3989     {
3990       const double tolFact = 0.05;
3991       while ( u2n != u2nEnd && pItF != points.end() )
3992       {
3993         const double         u = u2n->first;
3994         const SMDS_MeshNode* n = u2n->second;
3995         const double       tol = ( (++u2n)->first - u ) * tolFact;
3996         do
3997         {
3998           p = ( isForward ? *pItF : *pItR );
3999           if ( Abs( u - p->myU ) < tol )
4000           {
4001             int pIndex = p - &myPoints[0];
4002             if ( !nodesVector [ pIndex ] )
4003               nodesVector [ pIndex ] = n;
4004             ++pItF;
4005             ++pItR;
4006             break;
4007           }
4008         }
4009         while ( p->myU < u && ( ++pItF, ++pItR != points.rend() ));
4010       }
4011     }
4012     break;
4013   } // case TopAbs_EDGE:
4014
4015   default:;
4016   } // switch ( S.ShapeType() )
4017
4018   return false;
4019 }
4020
4021 //=======================================================================
4022 //function : MakeMesh
4023 //purpose  : Create nodes and elements in <theMesh> using nodes
4024 //           coordinates computed by either of Apply...() methods
4025 //=======================================================================
4026
4027 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
4028                              const bool  toCreatePolygons,
4029                              const bool  toCreatePolyedrs)
4030 {
4031   if ( !myIsComputed )
4032     return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
4033
4034   mergePoints( toCreatePolygons );
4035
4036   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4037
4038   // clear elements and nodes existing on myShape
4039   clearMesh(theMesh);
4040
4041   bool onMeshElements = ( !myElements.empty() );
4042
4043   // Create missing nodes
4044
4045   vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
4046   if ( onMeshElements )
4047   {
4048     nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
4049     map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
4050     for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
4051       nodesVector[ i_node->first ] = i_node->second;
4052     }
4053     for ( size_t i = 0; i < myXYZ.size(); ++i ) {
4054       if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
4055         nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
4056                                              myXYZ[ i ].Y(),
4057                                              myXYZ[ i ].Z());
4058     }
4059     if ( theMesh->HasShapeToMesh() )
4060     {
4061       // set nodes on EDGEs (IMP 22368)
4062       SMESH_MesherHelper helper( *theMesh );
4063       helper.ToFixNodeParameters( true );
4064       map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
4065       for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
4066       {
4067         list<list< int > >& groups = idListIt->second;
4068         const TNodeSet&      nodes = idListIt->first;
4069         if ( nodes.size() != 2 )
4070           continue; // not a link
4071         const SMDS_MeshNode* n1 = *nodes.begin();
4072         const SMDS_MeshNode* n2 = *nodes.rbegin();
4073         TopoDS_Shape S1 = helper.GetSubShapeByNode( n1, aMeshDS );
4074         TopoDS_Shape S2 = helper.GetSubShapeByNode( n2, aMeshDS );
4075         if ( S1.IsNull() || S1.ShapeType() < TopAbs_EDGE ||
4076              S2.IsNull() || S2.ShapeType() < TopAbs_EDGE )
4077           continue;
4078         TopoDS_Shape S;
4079         if ( S1.ShapeType() == TopAbs_EDGE )
4080         {
4081           if ( S1 == S2 || helper.IsSubShape( S2, S1 ))
4082             S = S1;
4083         }
4084         else if ( S2.ShapeType() == TopAbs_EDGE )
4085         {
4086           if ( helper.IsSubShape( S1, S2 ))
4087             S = S2;
4088         }
4089         else
4090         {
4091           S = helper.GetCommonAncestor( S1, S2, *theMesh, TopAbs_EDGE );
4092         } 
4093         if ( S.IsNull() )
4094           continue;
4095         const TopoDS_Edge & E = TopoDS::Edge( S );
4096         helper.SetSubShape( E );
4097         list<list< int > >::iterator g = groups.begin();
4098         for ( ; g != groups.end(); ++g )
4099         {
4100           list< int >& ids = *g;
4101           list< int >::iterator id = ids.begin();
4102           for ( ; id != ids.end(); ++id )
4103             if ( nodesVector[ *id ] && nodesVector[ *id ]->getshapeId() < 1 )
4104             {
4105               double u = 1e100;
4106               aMeshDS->SetNodeOnEdge( nodesVector[ *id ], E, u );
4107               helper.CheckNodeU( E, nodesVector[ *id ], u, 1e-7, true );
4108             }
4109         }
4110       }
4111     }
4112   }  // if ( onMeshElements )
4113
4114   else
4115   {
4116     nodesVector.resize( myPoints.size(), 0 );
4117
4118     // loop on sub-shapes of myShape: create nodes
4119     map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
4120     for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
4121     {
4122       list< TPoint* > & points = idPointIt->second;
4123       TopoDS_Shape S;
4124       if ( !myShapeIDMap.IsEmpty() )
4125         S = myShapeIDMap( idPointIt->first );
4126
4127       // find existing nodes on EDGEs and VERTEXes
4128       if ( findExistingNodes( theMesh, S, points, nodesVector ))
4129         continue;
4130
4131       list< TPoint* >::iterator pIt = points.begin();
4132       for ( ; pIt != points.end(); pIt++ )
4133       {
4134         TPoint* point = *pIt;
4135         int pIndex = point - &myPoints[0];
4136         if ( nodesVector [ pIndex ] )
4137           continue;
4138         SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
4139                                                 point->myXYZ.Y(),
4140                                                 point->myXYZ.Z());
4141         nodesVector [ pIndex ] = node;
4142
4143         if ( !S.IsNull() ) {
4144
4145           switch ( S.ShapeType() ) {
4146           case TopAbs_VERTEX: {
4147             aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
4148           }
4149           case TopAbs_EDGE: {
4150             aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
4151           }
4152           case TopAbs_FACE: {
4153             aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
4154                                     point->myUV.X(), point->myUV.Y() ); break;
4155           }
4156           default:
4157             aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
4158           }
4159         }
4160       }
4161     }
4162   }
4163
4164   // create elements
4165
4166   if ( onMeshElements )
4167   {
4168     // prepare data to create poly elements
4169     makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
4170
4171     // refine elements
4172     createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
4173     // sew old and new elements
4174     createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
4175   }
4176   else
4177   {
4178     createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4179   }
4180
4181   aMeshDS->Modified();
4182   aMeshDS->CompactMesh();
4183
4184   if ( myToKeepNodes )
4185     myOutNodes.swap( nodesVector );
4186
4187 //   const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4188 //   map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4189 //   for ( ; i_sm != sm.end(); i_sm++ )
4190 //   {
4191 //     cout << " SM " << i_sm->first << " ";
4192 //     TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4193 //     //SMDS_ElemIteratorPtr GetElements();
4194 //     SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4195 //     while ( nit->more() )
4196 //       cout << nit->next()->GetID() << " ";
4197 //     cout << endl;
4198 //   }
4199   return setErrorCode( ERR_OK );
4200 }
4201
4202 //=======================================================================
4203 //function : createElements
4204 //purpose  : add elements to the mesh
4205 //=======================================================================
4206
4207 void SMESH_Pattern::createElements(SMESH_Mesh*                            theMesh,
4208                                    const vector<const SMDS_MeshNode* >&   theNodesVector,
4209                                    const list< TElemDef > &               theElemNodeIDs,
4210                                    const vector<const SMDS_MeshElement*>& theElements)
4211 {
4212   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4213   SMESH_MeshEditor editor( theMesh );
4214
4215   bool onMeshElements = !theElements.empty();
4216
4217   // shapes and groups theElements are on
4218   vector< int > shapeIDs;
4219   vector< list< SMESHDS_Group* > > groups;
4220   set< const SMDS_MeshNode* > shellNodes;
4221   if ( onMeshElements )
4222   {
4223     shapeIDs.resize( theElements.size() );
4224     groups.resize( theElements.size() );
4225     const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4226     set<SMESHDS_GroupBase*>::const_iterator grIt;
4227     for ( size_t i = 0; i < theElements.size(); i++ )
4228     {
4229       shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4230       for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4231         SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4232         if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4233           groups[ i ].push_back( group );
4234       }
4235     }
4236     // get all nodes bound to shells because their SpacePosition is not set
4237     // by SMESHDS_Mesh::SetNodeInVolume()
4238     TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4239     if ( !aMainShape.IsNull() ) {
4240       TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4241       for ( ; shellExp.More(); shellExp.Next() )
4242       {
4243         SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4244         if ( sm ) {
4245           SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4246           while ( nIt->more() )
4247             shellNodes.insert( nIt->next() );
4248         }
4249       }
4250     }
4251   }
4252    // nb new elements per a refined element
4253   int nbNewElemsPerOld = 1;
4254   if ( onMeshElements )
4255     nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4256
4257   bool is2d = myIs2D;
4258
4259   list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4260   list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4261   for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4262   {
4263     const TElemDef & elemNodeInd = *enIt;
4264     // retrieve nodes
4265     vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4266     TElemDef::const_iterator id = elemNodeInd.begin();
4267     int nbNodes;
4268     for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4269       if ( *id < (int) theNodesVector.size() )
4270         nodes[ nbNodes++ ] = theNodesVector[ *id ];
4271       else
4272         nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4273     }
4274     // dim of refined elem
4275     int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4276     if ( onMeshElements ) {
4277       is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4278     }
4279     // add an element
4280     const SMDS_MeshElement* elem = 0;
4281     if ( is2d ) {
4282       switch ( nbNodes ) {
4283       case 3:
4284         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4285       case 4:
4286         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4287       case 6:
4288         if ( !onMeshElements ) {// create a quadratic face
4289           elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4290                                    nodes[4], nodes[5] ); break;
4291         } // else do not break but create a polygon
4292         // fall through
4293       case 8:
4294         if ( !onMeshElements ) {// create a quadratic face
4295           elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4296                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4297         } // else do not break but create a polygon
4298         // fall through
4299       default:
4300         elem = aMeshDS->AddPolygonalFace( nodes );
4301       }
4302     }
4303     else {
4304       switch ( nbNodes ) {
4305       case 4:
4306         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4307       case 5:
4308         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4309                                    nodes[4] ); break;
4310       case 6:
4311         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4312                                    nodes[4], nodes[5] ); break;
4313       case 8:
4314         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4315                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4316       default:
4317         elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4318       }
4319     }
4320     // set element on a shape
4321     if ( elem && onMeshElements ) // applied to mesh elements
4322     {
4323       int shapeID = shapeIDs[ elemIndex ];
4324       if ( shapeID > 0 ) {
4325         aMeshDS->SetMeshElementOnShape( elem, shapeID );
4326         // set nodes on a shape
4327         TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4328         if ( S.ShapeType() == TopAbs_SOLID ) {
4329           TopoDS_Iterator shellIt( S );
4330           if ( shellIt.More() )
4331             shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4332         }
4333         SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4334         while ( noIt->more() ) {
4335           SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4336           if ( node->getshapeId() < 1 &&
4337                shellNodes.find( node ) == shellNodes.end() )
4338           {
4339             if ( S.ShapeType() == TopAbs_FACE )
4340               aMeshDS->SetNodeOnFace( node, shapeID,
4341                                       Precision::Infinite(),// <- it's a sign that UV is not set
4342                                       Precision::Infinite());
4343             else {
4344               aMeshDS->SetNodeInVolume( node, shapeID );
4345               shellNodes.insert( node );
4346             }
4347           }
4348         }
4349       }
4350       // add elem in groups
4351       list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4352       for ( ; g != groups[ elemIndex ].end(); ++g )
4353         (*g)->SMDSGroup().Add( elem );
4354     }
4355     if ( elem && !myShape.IsNull() ) // applied to shape
4356       aMeshDS->SetMeshElementOnShape( elem, myShape );
4357   }
4358
4359   // make that SMESH_subMesh::_computeState == COMPUTE_OK
4360   // so that operations with hypotheses will erase the mesh being built
4361
4362   SMESH_subMesh * subMesh;
4363   if ( !myShape.IsNull() ) {
4364     subMesh = theMesh->GetSubMesh( myShape );
4365     if ( subMesh )
4366       subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4367   }
4368   if ( onMeshElements ) {
4369     list< smIdType > elemIDs;
4370     for ( size_t i = 0; i < theElements.size(); i++ )
4371     {
4372       subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4373       if ( subMesh )
4374         subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4375
4376       elemIDs.push_back( theElements[ i ]->GetID() );
4377     }
4378     // remove refined elements
4379     editor.Remove( elemIDs, false );
4380   }
4381 }
4382
4383 //=======================================================================
4384 //function : isReversed
4385 //purpose  : check xyz ids order in theIdsList taking into account
4386 //           theFirstNode on a link
4387 //=======================================================================
4388
4389 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4390                                const list< int >&   theIdsList) const
4391 {
4392   if ( theIdsList.size() < 2 )
4393     return false;
4394
4395   gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4396   gp_Pnt P[2];
4397   list<int>::const_iterator id = theIdsList.begin();
4398   for ( int i = 0; i < 2; ++i, ++id ) {
4399     if ( *id < (int) myXYZ.size() )
4400       P[ i ] = myXYZ[ *id ];
4401     else {
4402       map< int, const SMDS_MeshNode*>::const_iterator i_n;
4403       i_n = myXYZIdToNodeMap.find( *id );
4404       ASSERT( i_n != myXYZIdToNodeMap.end() );
4405       const SMDS_MeshNode* n = i_n->second;
4406       P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4407     }
4408   }
4409   return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4410 }
4411
4412
4413 //=======================================================================
4414 //function : arrangeBoundaries
4415 //purpose  : if there are several wires, arrange boundaryPoints so that
4416 //           the outer wire goes first and fix inner wires orientation
4417 //           update myKeyPointIDs to correspond to the order of key-points
4418 //           in boundaries; sort internal boundaries by the nb of key-points
4419 //=======================================================================
4420
4421 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4422 {
4423   typedef list< list< TPoint* > >::iterator TListOfListIt;
4424   TListOfListIt bndIt;
4425   list< TPoint* >::iterator pIt;
4426
4427   int nbBoundaries = boundaryList.size();
4428   if ( nbBoundaries > 1 )
4429   {
4430     // sort boundaries by nb of key-points
4431     if ( nbBoundaries > 2 )
4432     {
4433       // move boundaries in tmp list
4434       list< list< TPoint* > > tmpList;
4435       tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4436       // make a map nb-key-points to boundary-position-in-tmpList,
4437       // boundary-positions get ordered in it
4438       typedef map< int, TListOfListIt > TNbKpBndPosMap;
4439       TNbKpBndPosMap nbKpBndPosMap;
4440       bndIt = tmpList.begin();
4441       list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4442       for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4443         int nb = *nbKpIt * nbBoundaries;
4444         while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4445           nb++;
4446         nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4447       }
4448       // move boundaries back to boundaryList
4449       TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4450       for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4451         TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4452         TListOfListIt bndPos1 = bndPos2++;
4453         boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4454       }
4455     }
4456
4457     // Look for the outer boundary: the one with the point with the least X
4458     double leastX = DBL_MAX;
4459     TListOfListIt outerBndPos;
4460     for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4461     {
4462       list< TPoint* >& boundary = (*bndIt);
4463       for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4464       {
4465         TPoint* point = *pIt;
4466         if ( point->myInitXYZ.X() < leastX ) {
4467           leastX = point->myInitXYZ.X();
4468           outerBndPos = bndIt;
4469         }
4470       }
4471     }
4472
4473     if ( outerBndPos != boundaryList.begin() )
4474       boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos );
4475
4476   } // if nbBoundaries > 1
4477
4478   // Check boundaries orientation and re-fill myKeyPointIDs
4479
4480   set< TPoint* > keyPointSet;
4481   list< int >::iterator kpIt = myKeyPointIDs.begin();
4482   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4483     keyPointSet.insert( & myPoints[ *kpIt ]);
4484   myKeyPointIDs.clear();
4485
4486   // update myNbKeyPntInBoundary also
4487   list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4488
4489   for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4490   {
4491     // find the point with the least X
4492     double leastX = DBL_MAX;
4493     list< TPoint* >::iterator xpIt;
4494     list< TPoint* >& boundary = (*bndIt);
4495     for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4496     {
4497       TPoint* point = *pIt;
4498       if ( point->myInitXYZ.X() < leastX ) {
4499         leastX = point->myInitXYZ.X();
4500         xpIt = pIt;
4501       }
4502     }
4503     // find points next to the point with the least X
4504     TPoint* p = *xpIt, *pPrev, *pNext;
4505     if ( p == boundary.front() )
4506       pPrev = *(++boundary.rbegin());
4507     else {
4508       xpIt--;
4509       pPrev = *xpIt;
4510       xpIt++;
4511     }
4512     if ( p == boundary.back() )
4513       pNext = *(++boundary.begin());
4514     else {
4515       xpIt++;
4516       pNext = *xpIt;
4517     }
4518     // vectors of boundary direction near <p>
4519     gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4520     double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4521     if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4522       double yPrev = v1.Y() / sqrt( sqMag1 );
4523       double yNext = v2.Y() / sqrt( sqMag2 );
4524       double sumY = yPrev + yNext;
4525       bool reverse;
4526       if ( bndIt == boundaryList.begin() ) // outer boundary
4527         reverse = sumY > 0;
4528       else
4529         reverse = sumY < 0;
4530       if ( reverse )
4531         boundary.reverse();
4532     }
4533
4534     // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4535     (*nbKpIt) = 0; // count nb of key-points again
4536     pIt = boundary.begin();
4537     for ( ; pIt != boundary.end(); pIt++)
4538     {
4539       TPoint* point = *pIt;
4540       if ( keyPointSet.find( point ) == keyPointSet.end() )
4541         continue;
4542       // find an index of a keypoint
4543       int index = 0;
4544       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4545       for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4546         if ( &(*pVecIt) == point )
4547           break;
4548       myKeyPointIDs.push_back( index );
4549       (*nbKpIt)++;
4550     }
4551     myKeyPointIDs.pop_back(); // remove the first key-point from the back
4552     (*nbKpIt)--;
4553
4554   } // loop on a list of boundaries
4555
4556   ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4557 }
4558
4559 //=======================================================================
4560 //function : findBoundaryPoints
4561 //purpose  : if loaded from file, find points to map on edges and faces and
4562 //           compute their parameters
4563 //=======================================================================
4564
4565 bool SMESH_Pattern::findBoundaryPoints()
4566 {
4567   if ( myIsBoundaryPointsFound ) return true;
4568
4569   myNbKeyPntInBoundary.clear();
4570
4571   if ( myIs2D )
4572   {
4573     set< TPoint* > pointsInElems;
4574
4575     // Find free links of elements:
4576     // put links of all elements in a set and remove links encountered twice
4577
4578     typedef pair< TPoint*, TPoint*> TLink;
4579     set< TLink > linkSet;
4580     list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4581     for ( ; epIt != myElemPointIDs.end(); epIt++ )
4582     {
4583       TElemDef & elemPoints = *epIt;
4584       TElemDef::iterator pIt = elemPoints.begin();
4585       int prevP = elemPoints.back();
4586       for ( ; pIt != elemPoints.end(); pIt++ ) {
4587         TPoint* p1 = & myPoints[ prevP ];
4588         TPoint* p2 = & myPoints[ *pIt ];
4589         TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4590         ASSERT( link.first != link.second );
4591         pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4592         if ( !itUniq.second )
4593           linkSet.erase( itUniq.first );
4594         prevP = *pIt;
4595
4596         pointsInElems.insert( p1 );
4597       }
4598     }
4599     // Now linkSet contains only free links,
4600     // find the points order that they have in boundaries
4601
4602     // 1. make a map of key-points
4603     set< TPoint* > keyPointSet;
4604     list< int >::iterator kpIt = myKeyPointIDs.begin();
4605     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4606       keyPointSet.insert( & myPoints[ *kpIt ]);
4607
4608     // 2. chain up boundary points
4609     list< list< TPoint* > > boundaryList;
4610     boundaryList.push_back( list< TPoint* >() );
4611     list< TPoint* > * boundary = & boundaryList.back();
4612
4613     TPoint *point1, *point2, *keypoint1;
4614     kpIt = myKeyPointIDs.begin();
4615     point1 = keypoint1 = & myPoints[ *kpIt++ ];
4616     // loop on free links: look for the next point
4617     int iKeyPoint = 0;
4618     set< TLink >::iterator lIt = linkSet.begin();
4619     while ( lIt != linkSet.end() )
4620     {
4621       if ( (*lIt).first == point1 )
4622         point2 = (*lIt).second;
4623       else if ( (*lIt).second == point1 )
4624         point2 = (*lIt).first;
4625       else {
4626         lIt++;
4627         continue;
4628       }
4629       linkSet.erase( lIt );
4630       lIt = linkSet.begin();
4631
4632       if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4633       {
4634         boundary->push_back( point2 );
4635       }
4636       else // a key-point found
4637       {
4638         keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4639         iKeyPoint++;
4640         if ( point2 != keypoint1 ) // its not the boundary end
4641         {
4642           boundary->push_back( point2 );
4643         }
4644         else  // the boundary end reached
4645         {
4646           boundary->push_front( keypoint1 );
4647           boundary->push_back( keypoint1 );
4648           myNbKeyPntInBoundary.push_back( iKeyPoint );
4649           if ( keyPointSet.empty() )
4650             break; // all boundaries containing key-points are found
4651
4652           // prepare to search for the next boundary
4653           boundaryList.push_back( list< TPoint* >() );
4654           boundary = & boundaryList.back();
4655           point2 = keypoint1 = (*keyPointSet.begin());
4656         }
4657       }
4658       point1 = point2;
4659     } // loop on the free links set
4660
4661     if ( boundary->empty() ) {
4662       MESSAGE(" a separate key-point");
4663       return setErrorCode( ERR_READ_BAD_KEY_POINT );
4664     }
4665
4666     // if there are several wires, arrange boundaryPoints so that
4667     // the outer wire goes first and fix inner wires orientation;
4668     // sort myKeyPointIDs to correspond to the order of key-points
4669     // in boundaries
4670     arrangeBoundaries( boundaryList );
4671
4672     // Find correspondence shape ID - points,
4673     // compute points parameter on edge
4674
4675     keyPointSet.clear();
4676     for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4677       keyPointSet.insert( & myPoints[ *kpIt ]);
4678
4679     set< TPoint* > edgePointSet; // to find in-face points
4680     int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4681     int edgeID = myKeyPointIDs.size() + 1;
4682
4683     list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4684     for ( ; bndIt != boundaryList.end(); bndIt++ )
4685     {
4686       boundary = & (*bndIt);
4687       double edgeLength = 0;
4688       list< TPoint* >::iterator pIt = boundary->begin();
4689       getShapePoints( edgeID ).push_back( *pIt );
4690       getShapePoints( vertexID++ ).push_back( *pIt );
4691       for ( pIt++; pIt != boundary->end(); pIt++)
4692       {
4693         list< TPoint* > & edgePoints = getShapePoints( edgeID );
4694         TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4695         TPoint* point = *pIt;
4696         edgePointSet.insert( point );
4697         if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4698         {
4699           edgePoints.push_back( point );
4700           edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4701           point->myInitU = edgeLength;
4702         }
4703         else // a key-point
4704         {
4705           // treat points on the edge which ends up: compute U [0,1]
4706           edgePoints.push_back( point );
4707           if ( edgePoints.size() > 2 ) {
4708             edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4709             list< TPoint* >::iterator epIt = edgePoints.begin();
4710             for ( ; epIt != edgePoints.end(); epIt++ )
4711               (*epIt)->myInitU /= edgeLength;
4712           }
4713           // begin the next edge treatment
4714           edgeLength = 0;
4715           edgeID++;
4716           if ( point != boundary->front() ) { // not the first key-point again
4717             getShapePoints( edgeID ).push_back( point );
4718             getShapePoints( vertexID++ ).push_back( point );
4719           }
4720         }
4721       }
4722     }
4723
4724     // find in-face points
4725     list< TPoint* > & facePoints = getShapePoints( edgeID );
4726     vector< TPoint >::iterator pVecIt = myPoints.begin();
4727     for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4728       TPoint* point = &(*pVecIt);
4729       if ( edgePointSet.find( point ) == edgePointSet.end() &&
4730           pointsInElems.find( point ) != pointsInElems.end())
4731         facePoints.push_back( point );
4732     }
4733
4734   } // 2D case
4735
4736   else // 3D case
4737   {
4738     // bind points to shapes according to point parameters
4739     vector< TPoint >::iterator pVecIt = myPoints.begin();
4740     for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4741       TPoint* point = &(*pVecIt);
4742       int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4743       getShapePoints( shapeID ).push_back( point );
4744       // detect key-points
4745       if ( SMESH_Block::IsVertexID( shapeID ))
4746         myKeyPointIDs.push_back( i );
4747     }
4748   }
4749
4750   myIsBoundaryPointsFound = true;
4751   return myIsBoundaryPointsFound;
4752 }
4753
4754 //=======================================================================
4755 //function : Clear
4756 //purpose  : clear fields
4757 //=======================================================================
4758
4759 void SMESH_Pattern::Clear()
4760 {
4761   myIsComputed = myIsBoundaryPointsFound = false;
4762
4763   myPoints.clear();
4764   myKeyPointIDs.clear();
4765   myElemPointIDs.clear();
4766   myShapeIDToPointsMap.clear();
4767   myShapeIDMap.Clear();
4768   myShape.Nullify();
4769   myNbKeyPntInBoundary.clear();
4770
4771   myXYZ.clear();
4772   myElemXYZIDs.clear();
4773   myXYZIdToNodeMap.clear();
4774   myElements.clear();
4775   myOrderedNodes.clear();
4776   myPolyElems.clear();
4777   myPolyElemXYZIDs.clear();
4778   myPolyhedronQuantities.clear();
4779   myIdsOnBoundary.clear();
4780   myReverseConnectivity.clear();
4781 }
4782
4783 //================================================================================
4784 /*!
4785  * \brief set ErrorCode and return true if it is Ok
4786  */
4787 //================================================================================
4788
4789 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4790 {
4791   myErrorCode = theErrorCode;
4792   return myErrorCode == ERR_OK;
4793 }
4794
4795 //=======================================================================
4796 //function : setShapeToMesh
4797 //purpose  : set a shape to be meshed. Return True if meshing is possible
4798 //=======================================================================
4799
4800 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4801 {
4802   if ( !IsLoaded() ) {
4803     MESSAGE( "Pattern not loaded" );
4804     return setErrorCode( ERR_APPL_NOT_LOADED );
4805   }
4806
4807   TopAbs_ShapeEnum aType = theShape.ShapeType();
4808   bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4809   if ( !dimOk ) {
4810     MESSAGE( "Pattern dimension mismatch" );
4811     return setErrorCode( ERR_APPL_BAD_DIMENTION );
4812   }
4813
4814   // check if a face is closed
4815   int nbNodeOnSeamEdge = 0;
4816   if ( myIs2D ) {
4817     TopTools_MapOfShape seamVertices;
4818     TopoDS_Face face = TopoDS::Face( theShape );
4819     TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4820     for ( ; eExp.More() /*&& nbNodeOnSeamEdge == 0*/; eExp.Next() ) {
4821       const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4822       if ( BRep_Tool::IsClosed(ee, face) ) {
4823         // seam edge and vertices encounter twice in theFace
4824         if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4825         if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4826       }
4827     }
4828   }
4829
4830   // check nb of vertices
4831   TopTools_IndexedMapOfShape vMap;
4832   TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4833   if ( vMap.Extent() + nbNodeOnSeamEdge != (int)myKeyPointIDs.size() ) {
4834     MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4835     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4836   }
4837
4838   myElements.clear(); // not refine elements
4839   myElemXYZIDs.clear();
4840
4841   myShapeIDMap.Clear();
4842   myShape = theShape;
4843   return true;
4844 }
4845
4846 //=======================================================================
4847 //function : GetMappedPoints
4848 //purpose  : Return nodes coordinates computed by Apply() method
4849 //=======================================================================
4850
4851 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4852 {
4853   thePoints.clear();
4854   if ( !myIsComputed )
4855     return false;
4856
4857   if ( myElements.empty() ) { // applied to shape
4858     vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4859     for ( ; pVecIt != myPoints.end(); pVecIt++ )
4860       thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4861   }
4862   else { // applied to mesh elements
4863     const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4864     vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4865     for ( ; xyz != myXYZ.end(); ++xyz )
4866       if ( !isDefined( *xyz ))
4867         thePoints.push_back( definedXYZ );
4868       else
4869         thePoints.push_back( & (*xyz) );
4870   }
4871   return !thePoints.empty();
4872 }
4873
4874
4875 //=======================================================================
4876 //function : GetPoints
4877 //purpose  : Return nodes coordinates of the pattern
4878 //=======================================================================
4879
4880 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4881 {
4882   thePoints.clear();
4883
4884   if ( !IsLoaded() )
4885     return false;
4886
4887   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4888   for ( ; pVecIt != myPoints.end(); pVecIt++ )
4889     thePoints.push_back( & (*pVecIt).myInitXYZ );
4890
4891   return ( thePoints.size() > 0 );
4892 }
4893
4894 //=======================================================================
4895 //function : getShapePoints
4896 //purpose  : return list of points located on theShape
4897 //=======================================================================
4898
4899 list< SMESH_Pattern::TPoint* > &
4900   SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4901 {
4902   int aShapeID;
4903   if ( !myShapeIDMap.Contains( theShape ))
4904     aShapeID = myShapeIDMap.Add( theShape );
4905   else
4906     aShapeID = myShapeIDMap.FindIndex( theShape );
4907
4908   return myShapeIDToPointsMap[ aShapeID ];
4909 }
4910
4911 //=======================================================================
4912 //function : getShapePoints
4913 //purpose  : return list of points located on the shape
4914 //=======================================================================
4915
4916 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4917 {
4918   return myShapeIDToPointsMap[ theShapeID ];
4919 }
4920
4921 //=======================================================================
4922 //function : DumpPoints
4923 //purpose  : Debug
4924 //=======================================================================
4925
4926 void SMESH_Pattern::DumpPoints() const
4927 {
4928 #ifdef _DEBUG_
4929   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4930   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4931     MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4932 #endif
4933 }
4934
4935 //=======================================================================
4936 //function : TPoint()
4937 //purpose  : 
4938 //=======================================================================
4939
4940 SMESH_Pattern::TPoint::TPoint()
4941 {
4942 #ifdef _DEBUG_
4943   myInitXYZ.SetCoord(7,7,7);
4944   myInitUV.SetCoord(7.,7.);
4945   myInitU = 7;
4946   myXYZ.SetCoord(7,7,7);
4947   myUV.SetCoord(7.,7.);
4948   myU = 7;
4949 #endif
4950 }
4951
4952 //=======================================================================
4953 //function : operator <<
4954 //purpose  : 
4955 //=======================================================================
4956
4957 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4958 {
4959   gp_XYZ xyz = p.myInitXYZ;
4960   OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4961   gp_XY xy = p.myInitUV;
4962   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
4963   double u = p.myInitU;
4964   OS << " u( " <<  u << " )) " << &p << endl;
4965   xyz = p.myXYZ.XYZ();
4966   OS << "\t    ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4967   xy = p.myUV;
4968   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
4969   u = p.myU;
4970   OS << " u( " <<  u << " ))" << endl;
4971
4972   return OS;
4973 }