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