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