Salome HOME
Merge with OCC-V2_1_0_deb
[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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
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 <Bnd_Box2d.hxx>
27 #include <BRepTools.hxx>
28 #include <BRepTools_WireExplorer.hxx>
29 #include <BRep_Tool.hxx>
30 #include <Geom2d_Curve.hxx>
31 #include <Geom_Curve.hxx>
32 #include <Geom_Surface.hxx>
33 #include <IntAna2d_AnaIntersection.hxx>
34 #include <TopAbs_ShapeEnum.hxx>
35 #include <TopExp.hxx>
36 #include <TopLoc_Location.hxx>
37 #include <TopoDS.hxx>
38 #include <TopoDS_Edge.hxx>
39 #include <TopoDS_Face.hxx>
40 #include <TopoDS_Iterator.hxx>
41 #include <TopoDS_Shell.hxx>
42 #include <TopoDS_Vertex.hxx>
43 #include <TopoDS_Wire.hxx>
44 #include <gp_Lin2d.hxx>
45 #include <gp_Pnt2d.hxx>
46 #include <gp_Trsf.hxx>
47 #include <gp_XY.hxx>
48 #include <gp_XYZ.hxx>
49 #include <Extrema_GenExtPS.hxx>
50 #include <Extrema_POnSurf.hxx>
51 #include <GeomAdaptor_Surface.hxx>
52
53 #include "SMDS_EdgePosition.hxx"
54 #include "SMDS_FacePosition.hxx"
55 #include "SMDS_MeshElement.hxx"
56 #include "SMDS_MeshNode.hxx"
57 #include "SMESHDS_Mesh.hxx"
58 #include "SMESHDS_SubMesh.hxx"
59 #include "SMESH_Mesh.hxx"
60 #include "SMESH_Block.hxx"
61 #include "SMESH_subMesh.hxx"
62
63 #include "utilities.h"
64
65 using namespace std;
66
67 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
68
69 //=======================================================================
70 //function : SMESH_Pattern
71 //purpose  : 
72 //=======================================================================
73
74 SMESH_Pattern::SMESH_Pattern ()
75 {
76 }
77 //=======================================================================
78 //function : getInt
79 //purpose  : 
80 //=======================================================================
81
82 static inline int getInt( const char * theSring )
83 {
84   if ( *theSring < '0' || *theSring > '9' )
85     return -1;
86
87   char *ptr;
88   int val = strtol( theSring, &ptr, 10 );
89   if ( ptr == theSring ||
90       // there must not be neither '.' nor ',' nor 'E' ...
91       (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
92     return -1;
93
94   return val;
95 }
96
97 //=======================================================================
98 //function : getDouble
99 //purpose  : 
100 //=======================================================================
101
102 static inline double getDouble( const char * theSring )
103 {
104   char *ptr;
105   return strtod( theSring, &ptr );
106 }
107
108 //=======================================================================
109 //function : readLine
110 //purpose  : Put token starting positions in theFields until '\n' or '\0'
111 //           Return the number of the found tokens
112 //=======================================================================
113
114 static int readLine (list <const char*> & theFields,
115                      const char*        & theLineBeg,
116                      const bool           theClearFields )
117 {
118   if ( theClearFields )
119     theFields.clear();
120
121   //  algo:
122   /*  loop                                                       */
123   /*    switch ( symbol ) {                                      */
124   /*    case white-space:                                        */
125   /*      look for a non-space symbol;                           */
126   /*    case string-end:                                         */
127   /*    case line-end:                                           */
128   /*      exit;                                                  */
129   /*    case comment beginning:                                  */
130   /*      skip all till a line-end;                              */
131   /*    case a number                                            */
132   /*      put its position in theFields, skip till a white-space;*/
133   /*    default:                                                 */
134   /*      abort;                                                 */
135   /*  till line-end                                              */
136
137   int nbRead = 0;
138   bool stopReading = false;
139   do {
140     bool goOn = true;
141     bool isNumber = false;
142     switch ( *theLineBeg )
143     {
144     case ' ':  // white space
145     case '\t': // tab
146     case 13:   // ^M
147       break;
148
149     case '\n': // a line ends
150       stopReading = ( nbRead > 0 );
151       break;
152
153     case '!':  // comment
154       do theLineBeg++;
155       while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
156       goOn = false;
157       break;
158
159     case '\0': // file ends
160       return nbRead;
161
162     case '-': // real number
163     case '+':
164     case '.':
165       isNumber = true;
166     default: // data
167       isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
168       if ( isNumber ) {
169         theFields.push_back( theLineBeg );
170         nbRead++;
171         do theLineBeg++;
172         while (*theLineBeg != ' ' &&
173                *theLineBeg != '\n' &&
174                *theLineBeg != '\0');
175         goOn = false;
176       }
177       else
178         return 0; // incorrect file format
179     }
180
181     if ( goOn )
182       theLineBeg++;
183
184   } while ( !stopReading );
185
186   return nbRead;
187 }
188
189 //=======================================================================
190 //function : Load
191 //purpose  : Load a pattern from <theFile>
192 //=======================================================================
193
194 bool SMESH_Pattern::Load (const char* theFileContents)
195 {
196   MESSAGE("Load( file ) ");
197
198   // file structure:
199
200   // ! This is a comment
201   // NB_POINTS               ! 1 integer - the number of points in the pattern.
202   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
203   //   X2 Y2 [Z2]            ! the pattern dimention is defined by the number of coordinates
204   //   ...
205   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
206   // ! elements description goes after all
207   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
208   // ...
209
210   Clear();
211
212   const char* lineBeg = theFileContents;
213   list <const char*> fields;
214   const bool clearFields = true;
215
216   // NB_POINTS               ! 1 integer - the number of points in the pattern.
217
218   if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
219     MESSAGE("Error reading NB_POINTS");
220     return setErrorCode( ERR_READ_NB_POINTS );
221   }
222   int nbPoints = getInt( fields.front() );
223
224   //   X1 Y1 [Z1]            ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
225
226   // read the first point coordinates to define pattern dimention
227   int dim = readLine( fields, lineBeg, clearFields );
228   if ( dim == 2 )
229     myIs2D = true;
230   else if ( dim == 3 )
231     myIs2D = false;
232   else {
233     MESSAGE("Error reading points: wrong nb of coordinates");
234     return setErrorCode( ERR_READ_POINT_COORDS );
235   }
236   if ( nbPoints <= dim ) {
237     MESSAGE(" Too few points ");
238     return setErrorCode( ERR_READ_TOO_FEW_POINTS );
239   }
240     
241   // read the rest points
242   int iPoint;
243   for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
244     if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
245       MESSAGE("Error reading  points : wrong nb of coordinates ");
246       return setErrorCode( ERR_READ_POINT_COORDS );
247     }
248   // store point coordinates
249   myPoints.resize( nbPoints );
250   list <const char*>::iterator fIt = fields.begin();
251   for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
252   {
253     TPoint & p = myPoints[ iPoint ];
254     for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
255     {
256       double coord = getDouble( *fIt );
257       if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
258         MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
259         Clear();
260         return setErrorCode( ERR_READ_3D_COORD );
261       }
262       p.myInitXYZ.SetCoord( iCoord, coord );
263       if ( myIs2D )
264         p.myInitUV.SetCoord( iCoord, coord );
265     }
266   }
267
268   // [ ID1 ID2 ... IDn ]     ! Indices of key-points for a 2D pattern (only).
269   if ( myIs2D )
270   {
271     if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
272       MESSAGE("Error: missing key-points");
273       Clear();
274       return setErrorCode( ERR_READ_NO_KEYPOINT );
275     }
276     set<int> idSet;
277     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
278     {
279       int pointIndex = getInt( *fIt );
280       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
281         MESSAGE("Error: invalid point index " << pointIndex );
282         Clear();
283         return setErrorCode( ERR_READ_BAD_INDEX );
284       }
285       if ( idSet.insert( pointIndex ).second ) // unique?
286         myKeyPointIDs.push_back( pointIndex );
287     }
288   }
289
290   // ID1 ID2 ... IDn         ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
291
292   while ( readLine( fields, lineBeg, clearFields ))
293   {
294     myElemPointIDs.push_back( list< int >() );
295     list< int >& elemPoints = myElemPointIDs.back();
296     for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
297     {
298       int pointIndex = getInt( *fIt );
299       if ( pointIndex >= nbPoints || pointIndex < 0 ) {
300         MESSAGE("Error: invalid point index " << pointIndex );
301         Clear();
302         return setErrorCode( ERR_READ_BAD_INDEX );
303       }
304       elemPoints.push_back( pointIndex );
305     }
306     // check the nb of nodes in element
307     bool Ok = true;
308     switch ( elemPoints.size() ) {
309     case 3: if ( !myIs2D ) Ok = false; break;
310     case 4: break;
311     case 5:
312     case 6:
313     case 8: if ( myIs2D ) Ok = false; break;
314     default: Ok = false;
315     }
316     if ( !Ok ) {
317       MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
318       Clear();
319       return setErrorCode( ERR_READ_ELEM_POINTS );
320     }
321   }
322   if ( myElemPointIDs.empty() ) {
323     MESSAGE("Error: no elements");
324     Clear();
325     return setErrorCode( ERR_READ_NO_ELEMS );
326   }
327
328   findBoundaryPoints(); // sort key-points
329
330   return setErrorCode( ERR_OK );
331 }
332
333 //=======================================================================
334 //function : Save
335 //purpose  : Save the loaded pattern into the file <theFileName>
336 //=======================================================================
337
338 bool SMESH_Pattern::Save (ostream& theFile)
339 {
340   MESSAGE(" ::Save(file) " );
341   if ( !IsLoaded() ) {
342     MESSAGE(" Pattern not loaded ");
343     return setErrorCode( ERR_SAVE_NOT_LOADED );
344   }
345
346   theFile << "!!! SALOME Mesh Pattern file" << endl;
347   theFile << "!!!" << endl;
348   theFile << "!!! Nb of points:" << endl;
349   theFile << myPoints.size() << endl;
350
351   // point coordinates
352   const int width = 8;
353 //  theFile.width( 8 );
354 //  theFile.setf(ios::fixed);// use 123.45 floating notation
355 //  theFile.setf(ios::right);
356 //  theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
357 //   theFile.setf(ios::showpoint); // do not show trailing zeros
358   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
359   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
360     const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
361     theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
362     if ( !myIs2D ) theFile  << " " << setw( width ) << xyz.Z();
363     theFile  << "  !- " << i << endl; // point id to ease reading by a human being
364   }
365   // key-points
366   if ( myIs2D ) {
367     theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
368     list< int >::const_iterator kpIt = myKeyPointIDs.begin();
369     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
370       theFile << " " << *kpIt;
371     if ( !myKeyPointIDs.empty() )
372       theFile << endl;
373   }
374   // elements
375   theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
376   list<list< int > >::const_iterator epIt = myElemPointIDs.begin();
377   for ( ; epIt != myElemPointIDs.end(); epIt++ )
378   {
379     const list< int > & elemPoints = *epIt;
380     list< int >::const_iterator iIt = elemPoints.begin();
381     for ( ; iIt != elemPoints.end(); iIt++ )
382       theFile << " " << *iIt;
383     theFile << endl;
384   }
385
386   theFile << endl;
387   
388   return setErrorCode( ERR_OK );
389 }
390
391 //=======================================================================
392 //function : sortBySize
393 //purpose  : sort theListOfList by size
394 //=======================================================================
395
396 template<typename T> struct TSizeCmp {
397   bool operator ()( const list < T > & l1, const list < T > & l2 )
398     const { return l1.size() < l2.size(); }
399 };
400
401 template<typename T> void sortBySize( list< list < T > > & theListOfList )
402 {
403   if ( theListOfList.size() > 2 ) {
404     // keep the car
405     //list < T > & aFront = theListOfList.front();
406     // sort the whole list
407     TSizeCmp< T > SizeCmp;
408     theListOfList.sort( SizeCmp );
409   }
410 }
411
412 //=======================================================================
413 //function : getOrderedEdges
414 //purpose  : return nb wires and a list of oredered edges
415 //=======================================================================
416
417 static int getOrderedEdges (const TopoDS_Face&   theFace,
418                             const TopoDS_Vertex& theFirstVertex,
419                             list< TopoDS_Edge >& theEdges,
420                             list< int >  &       theNbVertexInWires)
421 {
422   // put wires in a list, so that an outer wire comes first
423   list<TopoDS_Wire> aWireList;
424   TopoDS_Wire anOuterWire = BRepTools::OuterWire( theFace );
425   aWireList.push_back( anOuterWire );
426   for ( TopoDS_Iterator wIt (theFace); wIt.More(); wIt.Next() )
427     if ( !anOuterWire.IsSame( wIt.Value() ))
428       aWireList.push_back( TopoDS::Wire( wIt.Value() ));
429
430   // loop on edges of wires
431   theNbVertexInWires.clear();
432   list<TopoDS_Wire>::iterator wlIt = aWireList.begin();
433   for ( ; wlIt != aWireList.end(); wlIt++ )
434   {
435     int iE;
436     BRepTools_WireExplorer wExp( *wlIt, theFace );
437     for ( iE = 0; wExp.More(); wExp.Next(), iE++ )
438     {
439       TopoDS_Edge edge = wExp.Current();
440       edge = TopoDS::Edge( edge.Oriented( wExp.Orientation() ));
441       theEdges.push_back( edge );
442     }
443     theNbVertexInWires.push_back( iE );
444     iE = 0;
445     if ( wlIt == aWireList.begin() && theEdges.size() > 1 ) { // the outer wire
446       // orient closed edges
447       list< TopoDS_Edge >::iterator eIt, eIt2;
448       for ( eIt = theEdges.begin(); eIt != theEdges.end(); eIt++ )
449       {
450         TopoDS_Edge& edge = *eIt;
451         if ( TopExp::FirstVertex( edge ).IsSame( TopExp::LastVertex( edge ) ))
452         {
453           eIt2 = eIt;
454           bool isNext = ( eIt2 == theEdges.begin() );
455           TopoDS_Edge edge2 = isNext ? *(++eIt2) : *(--eIt2);
456           double f1,l1,f2,l2;
457           Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( edge, theFace, f1,l1 );
458           Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( edge2, theFace, f2,l2 );
459           gp_Pnt2d pf = c1->Value( edge.Orientation() == TopAbs_FORWARD ? f1 : l1 );
460           gp_Pnt2d pl = c1->Value( edge.Orientation() == TopAbs_FORWARD ? l1 : f1 );
461           bool isFirst = ( edge2.Orientation() == TopAbs_FORWARD ? isNext : !isNext );
462           gp_Pnt2d p2 = c2->Value( isFirst ? f2 : l2 );
463           isFirst = ( p2.SquareDistance( pf ) < p2.SquareDistance( pl ));
464           if ( isNext ? isFirst : !isFirst )
465             edge.Reverse();
466         }
467       }
468       // rotate theEdges until it begins from theFirstVertex
469       if ( ! theFirstVertex.IsNull() )
470         while ( !theFirstVertex.IsSame( TopExp::FirstVertex( theEdges.front(), true )))
471         {
472           theEdges.splice(theEdges.end(), theEdges,
473                           theEdges.begin(), ++ theEdges.begin());
474           if ( iE++ > theNbVertexInWires.back() ) 
475             break; // break infinite loop
476         }
477     }
478   }
479
480   return aWireList.size();
481 }
482
483 //=======================================================================
484 //function : project
485 //purpose  : 
486 //=======================================================================
487
488 static gp_XY project (const SMDS_MeshNode* theNode,
489                       Extrema_GenExtPS &   theProjectorPS)
490 {
491   gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
492   theProjectorPS.Perform( P );
493   if ( !theProjectorPS.IsDone() ) {
494     MESSAGE( "SMESH_Pattern: point projection FAILED");
495     return gp_XY(0.,0.);
496   }
497   double u, v, minVal = DBL_MAX;
498   for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
499     if ( theProjectorPS.Value( i ) < minVal ) {
500       minVal = theProjectorPS.Value( i );
501       theProjectorPS.Point( i ).Parameter( u, v );
502     }
503   return gp_XY( u, v );
504 }
505
506 //=======================================================================
507 //function : isMeshBoundToShape
508 //purpose  : return true if all 2d elements are bound to shape
509 //=======================================================================
510
511 static bool isMeshBoundToShape(SMESH_Mesh* theMesh)
512 {
513   // check faces binding
514   SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
515   SMESHDS_SubMesh * aMainSubMesh = aMeshDS->MeshElements( aMeshDS->ShapeToMesh() );
516   if ( aMeshDS->NbFaces() != aMainSubMesh->NbElements() )
517     return false;
518
519   // check face nodes binding
520   SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
521   while ( fIt->more() )
522   {
523     SMDS_ElemIteratorPtr nIt = fIt->next()->nodesIterator();
524     while ( nIt->more() )
525     {
526       const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nIt->next() );
527       SMDS_PositionPtr pos = node->GetPosition();
528       if ( !pos || !pos->GetShapeId() )
529         return false;
530     }
531   }
532   return true;
533 }
534
535 //=======================================================================
536 //function : Load
537 //purpose  : Create a pattern from the mesh built on <theFace>.
538 //           <theProject>==true makes override nodes positions
539 //           on <theFace> computed by mesher
540 //=======================================================================
541
542 bool SMESH_Pattern::Load (SMESH_Mesh*        theMesh,
543                           const TopoDS_Face& theFace,
544                           bool               theProject)
545 {
546   MESSAGE(" ::Load(face) " );
547   Clear();
548   myIs2D = true;
549
550   SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
551   SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
552
553   int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
554   int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
555   if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
556   {
557     MESSAGE( "No elements bound to the face");
558     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
559   }
560
561   // check that face is not closed
562   TopoDS_Vertex bidon;
563   list<TopoDS_Edge> eList;
564   getOrderedEdges( theFace, bidon, eList, myNbKeyPntInBoundary );
565   list<TopoDS_Edge>::iterator elIt = eList.begin();
566   for ( ; elIt != eList.end() ; elIt++ )
567     if ( BRep_Tool::IsClosed( *elIt , theFace ))
568       return setErrorCode( ERR_LOADF_CLOSED_FACE );
569   
570
571   Extrema_GenExtPS projector;
572   GeomAdaptor_Surface aSurface( BRep_Tool::Surface( theFace ));
573   if ( theProject || nbElems == 0 )
574     projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
575
576   int iPoint = 0;
577   TNodePointIDMap nodePointIDMap;
578
579   if ( nbElems == 0 || (theProject &&
580                         theMesh->IsMainShape( theFace ) &&
581                         !isMeshBoundToShape( theMesh )))
582   {
583     MESSAGE("Project the whole mesh");
584     // ---------------------------------------------------------------
585     // The case where the whole mesh is projected to theFace
586     // ---------------------------------------------------------------
587
588     // put nodes of all faces in the nodePointIDMap and fill myElemPointIDs
589     SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
590     while ( fIt->more() )
591     {
592       myElemPointIDs.push_back( list< int >() );
593       list< int >& elemPoints = myElemPointIDs.back();
594       SMDS_ElemIteratorPtr nIt = fIt->next()->nodesIterator();
595       while ( nIt->more() )
596       {
597         const SMDS_MeshElement* node = nIt->next();
598         TNodePointIDMap::iterator nIdIt = nodePointIDMap.find( node );
599         if ( nIdIt == nodePointIDMap.end() )
600         {
601           elemPoints.push_back( iPoint );
602           nodePointIDMap.insert( TNodePointIDMap::value_type( node, iPoint++ ));
603         }
604         else
605           elemPoints.push_back( (*nIdIt).second );
606       }
607     }
608     myPoints.resize( iPoint );
609
610     // project all nodes of 2d elements to theFace
611     TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
612     for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
613     {
614       const SMDS_MeshNode* node = 
615         static_cast<const SMDS_MeshNode*>( (*nIdIt).first );
616       TPoint * p = & myPoints[ (*nIdIt).second ];
617       p->myInitUV = project( node, projector );
618       p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
619     }
620     // find key-points: the points most close to UV of vertices
621     TopExp_Explorer vExp( theFace, TopAbs_VERTEX );
622     set<int> foundIndices;
623     for ( ; vExp.More(); vExp.Next() ) {
624       const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
625       gp_Pnt2d uv = BRep_Tool::Parameters( v, theFace );
626       double minDist = DBL_MAX;
627       int index;
628       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
629       for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
630         double dist = uv.SquareDistance( (*pVecIt).myInitUV );
631         if ( dist < minDist ) {
632           minDist = dist;
633           index = iPoint;
634         }
635       }
636       if ( foundIndices.insert( index ).second ) // unique?
637         myKeyPointIDs.push_back( index );
638     }
639     myIsBoundaryPointsFound = false;
640
641   }
642   else
643   {
644     // ---------------------------------------------------------------------
645     // The case where a pattern is being made from the mesh built by mesher
646     // ---------------------------------------------------------------------
647
648     // Load shapes in the consequent order and count nb of points
649
650     // vertices
651     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
652       myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
653       SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt );
654       if ( eSubMesh )
655         nbNodes += eSubMesh->NbNodes() + 1;
656     }
657     // edges
658     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
659       myShapeIDMap.Add( *elIt );
660     // the face
661     myShapeIDMap.Add( theFace );
662
663     myPoints.resize( nbNodes );
664
665     // Load U of points on edges
666
667     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
668     {
669       TopoDS_Edge & edge = *elIt;
670       list< TPoint* > & ePoints = getShapePoints( edge );
671       double f, l;
672       Handle(Geom2d_Curve) C2d;
673       if ( !theProject )
674         C2d = BRep_Tool::CurveOnSurface( edge, theFace, f, l );
675       bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
676
677       // the forward key-point
678       TopoDS_Shape v = TopExp::FirstVertex( edge, true );
679       list< TPoint* > & vPoint = getShapePoints( v );
680       if ( vPoint.empty() )
681       {
682         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v );
683         if ( vSubMesh && vSubMesh->NbNodes() ) {
684           myKeyPointIDs.push_back( iPoint );
685           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
686           const SMDS_MeshNode* node = nIt->next();
687           nodePointIDMap.insert( TNodePointIDMap::value_type( node, iPoint ));
688
689           TPoint* keyPoint = &myPoints[ iPoint++ ];
690           vPoint.push_back( keyPoint );
691           if ( theProject )
692             keyPoint->myInitUV = project( node, projector );
693           else
694             keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
695           keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
696         }
697       }
698       if ( !vPoint.empty() )
699         ePoints.push_back( vPoint.front() );
700
701       // on-edge points
702       SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
703       if ( eSubMesh && eSubMesh->NbNodes() )
704       {
705         // loop on nodes of an edge: sort them by param on edge
706         typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
707         TParamNodeMap paramNodeMap;
708         SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
709         while ( nIt->more() )
710         {
711           const SMDS_MeshNode* node = 
712             static_cast<const SMDS_MeshNode*>( nIt->next() );
713           const SMDS_EdgePosition* epos =
714             static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
715           double u = epos->GetUParameter();
716           paramNodeMap.insert( TParamNodeMap::value_type( u, node ));
717         }
718         // put U in [0,1] so that the first key-point has U==0
719         double du = l - f;
720         TParamNodeMap::iterator         unIt  = paramNodeMap.begin();
721         TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
722         while ( unIt != paramNodeMap.end() )
723         {
724           TPoint* p = & myPoints[ iPoint ];
725           ePoints.push_back( p );
726           const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
727           nodePointIDMap.insert ( TNodePointIDMap::value_type( node, iPoint ));
728
729           if ( theProject )
730             p->myInitUV = project( node, projector );
731           else {
732             double u = isForward ? (*unIt).first : (*unRIt).first;
733             p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
734             p->myInitUV = C2d->Value( u ).XY();
735           }
736           p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
737           unIt++; unRIt++;
738           iPoint++;
739         }
740       }
741       // the reverse key-point
742       v = TopExp::LastVertex( edge, true ).Reversed();
743       list< TPoint* > & vPoint2 = getShapePoints( v );
744       if ( vPoint2.empty() )
745       {
746         SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v );
747         if ( vSubMesh && vSubMesh->NbNodes() ) {
748           myKeyPointIDs.push_back( iPoint );
749           SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
750           const SMDS_MeshNode* node = nIt->next();
751           nodePointIDMap.insert( TNodePointIDMap::value_type( node, iPoint ));
752
753           TPoint* keyPoint = &myPoints[ iPoint++ ];
754           vPoint2.push_back( keyPoint );
755           if ( theProject )
756             keyPoint->myInitUV = project( node, projector );
757           else
758             keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
759           keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
760         }
761       }
762       if ( !vPoint2.empty() )
763         ePoints.push_back( vPoint2.front() );
764
765       // compute U of edge-points
766       if ( theProject )
767       {
768         double totalDist = 0;
769         list< TPoint* >::iterator pIt = ePoints.begin();
770         TPoint* prevP = *pIt;
771         prevP->myInitU = totalDist;
772         for ( pIt++; pIt != ePoints.end(); pIt++ ) {
773           TPoint* p = *pIt;
774           totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
775           p->myInitU = totalDist;
776           prevP = p;
777         }
778         if ( totalDist > DBL_MIN)
779           for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
780             TPoint* p = *pIt;
781             p->myInitU /= totalDist;
782           }
783       }
784     } // loop on edges of a wire
785
786     // Load in-face points and elements
787
788     if ( fSubMesh && fSubMesh->NbElements() )
789     {
790       list< TPoint* > & fPoints = getShapePoints( theFace );
791       SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
792       while ( nIt->more() )
793       {
794         const SMDS_MeshNode* node = 
795           static_cast<const SMDS_MeshNode*>( nIt->next() );
796         nodePointIDMap.insert( TNodePointIDMap::value_type( node, iPoint ));
797         TPoint* p = &myPoints[ iPoint++ ];
798         fPoints.push_back( p );
799         if ( theProject )
800           p->myInitUV = project( node, projector );
801         else {
802           const SMDS_FacePosition* pos =
803             static_cast<const SMDS_FacePosition*>(node->GetPosition().get());
804           p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
805         }
806         p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
807       }
808       // load elements
809       SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
810       while ( elemIt->more() ) {
811         SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
812         myElemPointIDs.push_back( list< int >() );
813         list< int >& elemPoints = myElemPointIDs.back();
814         while ( nIt->more() )
815           elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
816       }
817     }
818
819     myIsBoundaryPointsFound = true;
820   }
821
822   // Assure that U range is proportional to V range
823
824   Bnd_Box2d bndBox;
825   vector< TPoint >::iterator pVecIt = myPoints.begin();
826   for ( ; pVecIt != myPoints.end(); pVecIt++ )
827     bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
828   double minU, minV, maxU, maxV;
829   bndBox.Get( minU, minV, maxU, maxV );
830   double dU = maxU - minU, dV = maxV - minV;
831   if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
832     Clear();
833     return setErrorCode( ERR_LOADF_NARROW_FACE );
834   }
835   double ratio = dU / dV, maxratio = 3, scale;
836   int iCoord = 0;
837   if ( ratio > maxratio ) {
838     scale = ratio / maxratio;
839     iCoord = 2;
840   }
841   else if ( ratio < 1./maxratio ) {
842     scale = maxratio / ratio;
843     iCoord = 1;
844   }
845   if ( iCoord ) {
846     SCRUTE( scale );
847     for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
848       TPoint & p = *pVecIt;
849       p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
850       p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
851     }
852   }
853   if ( myElemPointIDs.empty() ) {
854     MESSAGE( "No elements bound to the face");
855     return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
856   }
857
858   return setErrorCode( ERR_OK );
859 }
860
861 //=======================================================================
862 //function : computeUVOnEdge
863 //purpose  : compute coordinates of points on theEdge
864 //=======================================================================
865
866 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge&      theEdge,
867                                      const list< TPoint* > & ePoints )
868 {
869   bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
870   double f, l;
871   Handle(Geom2d_Curve) C2d =
872     BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
873
874   ePoints.back()->myInitU = 1.0;
875   list< TPoint* >::const_iterator pIt = ePoints.begin();
876   for ( pIt++; pIt != ePoints.end(); pIt++ )
877   {
878     TPoint* point = *pIt;
879     // U
880     double du = ( isForward ? point->myInitU : 1 - point->myInitU );
881     point->myU = ( f * ( 1 - du ) + l * du );
882     // UV
883     point->myUV = C2d->Value( point->myU ).XY();
884   }
885 }
886
887 //=======================================================================
888 //function : intersectIsolines
889 //purpose  : 
890 //=======================================================================
891
892 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
893                               const gp_XY& uv21, const gp_XY& uv22, const double r2,
894                               gp_XY& resUV,
895                               bool& isDeformed)
896 {
897   gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
898   gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
899   resUV = 0.5 * ( loc1 + loc2 );
900   isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
901 //   double len1 = ( uv11 - uv12 ).Modulus();
902 //   double len2 = ( uv21 - uv22 ).Modulus();
903 //   resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
904 //  return true;
905
906   
907 //   gp_Lin2d line1( uv11, uv12 - uv11 );
908 //   gp_Lin2d line2( uv21, uv22 - uv21 );
909 //   double angle = Abs( line1.Angle( line2 ) );
910
911 //     IntAna2d_AnaIntersection inter;
912 //     inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
913 //     if ( inter.IsDone() && inter.NbPoints() == 1 )
914 //     {
915 //       gp_Pnt2d interUV = inter.Point(1).Value();
916 //       resUV += interUV.XY();
917 //   inter.Perform( line1, line2 );
918 //   interUV = inter.Point(1).Value();
919 //   resUV += interUV.XY();
920   
921 //   resUV /= 2.;
922 //     }
923   return true;
924 }
925
926 //=======================================================================
927 //function : compUVByIsoIntersection
928 //purpose  : 
929 //=======================================================================
930
931 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
932                                              const gp_XY&                   theInitUV,
933                                              gp_XY&                         theUV,
934                                              bool &                         theIsDeformed )
935 {
936   // compute UV by intersection of 2 iso lines
937   //gp_Lin2d isoLine[2];
938   gp_XY uv1[2], uv2[2];
939   double ratio[2];
940   const double zero = DBL_MIN;
941   for ( int iIso = 0; iIso < 2; iIso++ )
942   {
943     // to build an iso line:
944     // find 2 pairs of consequent edge-points such that the range of their
945     // initial parameters encloses the in-face point initial parameter
946     gp_XY UV[2], initUV[2];
947     int nbUV = 0, iCoord = iIso + 1;
948     double initParam = theInitUV.Coord( iCoord );
949
950     list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
951     for ( ; bndIt != theBndPoints.end(); bndIt++ )
952     {
953       const list< TPoint* > & bndPoints = * bndIt;
954       TPoint* prevP = bndPoints.back(); // this is the first point
955       list< TPoint* >::const_iterator pIt = bndPoints.begin();
956       bool coincPrev = false; 
957       // loop on the edge-points
958       for ( ; pIt != bndPoints.end(); pIt++ )
959       {
960         double paramDiff     = initParam - (*pIt)->myInitUV.Coord( iCoord );
961         double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
962         double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
963         if (!coincPrev && // ignore if initParam coincides with prev point param
964             sumOfDiff > zero && // ignore if both points coincide with initParam
965             prevParamDiff * paramDiff <= zero )
966         {
967           // find UV in parametric space of theFace
968           double r = Abs(prevParamDiff) / sumOfDiff;
969           gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
970           int i = nbUV++;
971           if ( i >= 2 ) {
972             // throw away uv most distant from <theInitUV>
973             gp_XY vec0 = initUV[0] - theInitUV;
974             gp_XY vec1 = initUV[1] - theInitUV;
975             gp_XY vec  = uvInit    - theInitUV;
976             bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
977             double dist0 = vec0.SquareModulus();
978             double dist1 = vec1.SquareModulus();
979             double dist  = vec .SquareModulus();
980             if ( !isBetween || dist < dist0 || dist < dist1 ) {
981               i = ( dist0 < dist1 ? 1 : 0 );
982               if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
983                 i = 3; // theInitUV must remain between
984             }
985           }
986           if ( i < 2 ) {
987             initUV[ i ] = uvInit;
988             UV[ i ]     = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
989           }
990           coincPrev = ( Abs(paramDiff) <= zero );
991         }
992         else
993           coincPrev = false;
994         prevP = *pIt;
995       }
996     }
997     if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
998       MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
999               ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1000       return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1001     }
1002     // an iso line should be normal to UV[0] - UV[1] direction
1003     // and be located at the same relative distance as from initial ends
1004     //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1005     double r =
1006       (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1007     //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1008     //isoLine[ iIso ] = iso.Normal( isoLoc );
1009     uv1[ iIso ] = UV[0];
1010     uv2[ iIso ] = UV[1];
1011     ratio[ iIso ] = r;
1012   }
1013   if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1014                           uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1015     MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1016     return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1017   }
1018
1019   return true;
1020 }
1021
1022
1023 // ==========================================================
1024 // structure representing a node of a grid of iso-poly-lines
1025 // ==========================================================
1026
1027 struct TIsoNode {
1028   bool   myIsMovable;
1029   gp_XY  myInitUV;
1030   gp_XY  myUV;
1031   double myRatio[2];
1032   gp_Dir2d  myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1033   TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1034   TIsoNode* myBndNodes[4];     // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1035   TIsoNode(double initU, double initV):
1036     myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1037   { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1038   bool IsUVComputed() const
1039   { return myUV.X() != 1e100; }
1040   bool IsMovable() const
1041   { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1042   void SetNotMovable()
1043   { myIsMovable = false; }
1044   void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1045   { myBndNodes[ iDir + i * 2 ] = node; }
1046   TIsoNode* GetBoundaryNode(int iDir, int i)
1047   { return myBndNodes[ iDir + i * 2 ]; }
1048   void SetNext(TIsoNode* node, int iDir, int isForward)
1049   { myNext[ iDir + isForward  * 2 ] = node; }
1050   TIsoNode* GetNext(int iDir, int isForward)
1051   { return myNext[ iDir + isForward * 2 ]; }
1052 };
1053
1054 //=======================================================================
1055 //function : getNextNode
1056 //purpose  : 
1057 //=======================================================================
1058
1059 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1060 {
1061   TIsoNode* n = node->myNext[ dir ];
1062   if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1063     n = 0;//node->myBndNodes[ dir ];
1064 //     MESSAGE("getNextNode: use bnd for node "<<
1065 //             node->myInitUV.X()<<" "<<node->myInitUV.Y());
1066   }
1067   return n;
1068 }
1069 //=======================================================================
1070 //function : checkQuads
1071 //purpose  : check if newUV destortes quadrangles around node,
1072 //           and if ( crit == FIX_OLD ) fix newUV in this case
1073 //=======================================================================
1074
1075 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1076
1077 static bool checkQuads (const TIsoNode* node,
1078                         gp_XY&          newUV,
1079                         const bool      reversed,
1080                         const int       crit = FIX_OLD,
1081                         double          fixSize = 0.)
1082 {
1083   gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1084   int nbOldFix = 0, nbOldImpr = 0;
1085   double newBadRate = 0, oldBadRate = 0;
1086   bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1087   int i, dir1 = 0, dir2 = 3;
1088   for ( ; dir1 < 4; dir1++, dir2++ )  // loop on 4 quadrangles around <node>
1089   {
1090     if ( dir2 > 3 ) dir2 = 0;
1091     TIsoNode* n[3];
1092     // walking counterclockwise around a quad,
1093     // nodes are in the order: node, n[0], n[1], n[2]
1094     n[0] = getNextNode( node, dir1 );
1095     n[2] = getNextNode( node, dir2 );
1096     if ( !n[0] || !n[2] ) continue;
1097     n[1] = getNextNode( n[0], dir2 );
1098     if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1099     bool isTriangle = ( !n[1] );
1100     if ( reversed ) {
1101       TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1102     }
1103 //     if ( fixSize != 0 ) {
1104 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1105 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1106 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1107 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1108 // }
1109     // check if a quadrangle is degenerated
1110     if ( !isTriangle &&
1111         ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1112          (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1113       isTriangle = true;
1114     if ( isTriangle &&
1115         ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1116       continue;
1117
1118     // find min size of the diagonal node-n[1]
1119     double minDiag = fixSize;
1120     if ( minDiag == 0. ) {
1121       double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1122       if ( !isTriangle ) {
1123         maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1124         maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1125       }
1126       maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1127       minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1128     }
1129
1130     // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1131     // ( behind means "to the right of")
1132     // it is OK if
1133     // 1. newUV is not behind 01 and 12 dirs
1134     // 2. or newUV is not behind 02 dir and n[2] is convex
1135     bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1136     bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1137     gp_Vec2d moveVec[3], outVec[3];
1138     for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1139     {
1140       bool isDiag = ( i == 2 );
1141       if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1142         break;
1143       gp_Vec2d sideDir;
1144       if ( isDiag )
1145         sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1146       else
1147         sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1148
1149       gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1150       outDir.Normalize();
1151       gp_Vec2d newDir( n[i]->myUV, newUV );
1152       gp_Vec2d oldDir( n[i]->myUV, oldUV );
1153       outVec[i] = outDir;
1154       if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1155       if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1156       if ( crit == FIX_OLD ) {
1157         wasIn[i] = ( outDir * oldDir < 0 );
1158         wasOk[i] = ( outDir * oldDir < -minDiag );
1159         if ( !newOk[i] )
1160           newBadRate += outDir * newDir;
1161         if ( !wasOk[i] )
1162           oldBadRate += outDir * oldDir;
1163         // push node inside
1164         if ( !wasOk[i] ) {
1165           double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1166           //               double r = ( l1 - minDiag ) / ( l1 + l2 );
1167           //               moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1168           moveVec[i] = ( oldDist - minDiag ) * outDir;
1169         }
1170       }
1171     }
1172
1173     // check if n[2] is convex
1174     bool convex = true;
1175     if ( !isTriangle )
1176       convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1177
1178     bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1179     bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1180     newIsOk = ( newIsOk && isNewOk );
1181     newIsIn = ( newIsIn && isNewIn );
1182
1183     if ( crit != FIX_OLD ) {
1184       if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1185       if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1186       continue;
1187     }
1188
1189     bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1190     bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1191     oldIsIn = ( oldIsIn && isOldIn );
1192     oldIsOk = ( oldIsOk && isOldIn );
1193
1194
1195     if ( !isOldIn ) { // node is outside a quadrangle
1196       // move newUV inside a quadrangle
1197 //MESSAGE("Quad "<< dir1 << "  WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1198       // node and newUV are outside: push newUV inside
1199       gp_XY uv;
1200       if ( convex || isTriangle ) {
1201         uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1202       }
1203       else {
1204         gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1205         double outSize = out.Magnitude();
1206         if ( outSize > DBL_MIN )
1207           out /= outSize;
1208         else
1209           out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1210         uv = n[1]->myUV - minDiag * out.XY();
1211       }
1212       oldUVFixed[ nbOldFix++ ] = uv;
1213       //node->myUV = newUV;
1214     }
1215     else if ( !isOldOk )  {
1216       // try to fix old UV: move node inside as less as possible
1217 //MESSAGE("Quad "<< dir1 << "  old is BAD, try to fix old, minDiag: "<< minDiag);
1218       gp_XY uv1, uv2 = node->myUV;
1219       for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1220         if ( wasOk[i] )
1221           moveVec[ i ].SetCoord( 1, 2e100); // not use this vector 
1222       while ( !isOldOk ) {
1223         // find the least moveVec
1224         int i, iMin = 4;
1225         double minMove2 = 1e100;
1226         for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1227         {
1228           if ( moveVec[i].Coord(1) < 1e100 ) {
1229             double move2 = moveVec[i].SquareMagnitude();
1230             if ( move2 < minMove2 ) {
1231               minMove2 = move2;
1232               iMin = i;
1233             }
1234           }
1235         }
1236         if ( iMin == 4 ) {
1237           break;
1238         }
1239         // move node to newUV
1240         uv1 = node->myUV + moveVec[ iMin ].XY();
1241         uv2 += moveVec[ iMin ].XY();
1242         moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1243         // check if uv1 is ok
1244         for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1245           wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1246         isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1247         if ( isOldOk )
1248           oldUVImpr[ nbOldImpr++ ] = uv1;
1249         else {
1250           // check if uv2 is ok
1251           for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1252             wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1253           isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1254           if ( isOldOk )
1255             oldUVImpr[ nbOldImpr++ ] = uv2;
1256         }
1257       }
1258     }
1259
1260   } // loop on 4 quadrangles around <node>
1261
1262   if ( crit == CHECK_NEW_OK  )
1263     return newIsOk;
1264   if ( crit == CHECK_NEW_IN  )
1265     return newIsIn;
1266
1267   if ( newIsOk )
1268     return true;
1269
1270   if ( oldIsOk )
1271     newUV = oldUV;
1272   else {
1273     if ( oldIsIn && nbOldImpr ) {
1274 //       MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1275 //               " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1276       gp_XY uv = oldUVImpr[ 0 ];
1277       for ( int i = 1; i < nbOldImpr; i++ )
1278         uv += oldUVImpr[ i ];
1279       uv /= nbOldImpr;
1280       if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1281         newUV = uv;
1282         return false;
1283       }
1284       else {
1285         //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1286       }
1287     }
1288     if ( !oldIsIn && nbOldFix ) {
1289 //       MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1290 //               " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1291       gp_XY uv = oldUVFixed[ 0 ];
1292       for ( int i = 1; i < nbOldFix; i++ )
1293         uv += oldUVFixed[ i ];
1294       uv /= nbOldFix;
1295       if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1296         newUV = uv;
1297         return false;
1298       }
1299       else {
1300         //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1301       }
1302     }
1303     if ( newIsIn && oldIsIn )
1304       newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1305     else if ( !newIsIn )
1306       newUV = oldUV;
1307   }
1308
1309   return false;
1310 }
1311
1312 //=======================================================================
1313 //function : compUVByElasticIsolines
1314 //purpose  : compute UV as nodes of iso-poly-lines consisting of
1315 //           segments keeping relative size as in the pattern
1316 //=======================================================================
1317 //#define DEB_COMPUVBYELASTICISOLINES
1318 bool SMESH_Pattern::
1319   compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1320                           const list< TPoint* >&         thePntToCompute)
1321 {
1322 //cout << "============================== KEY POINTS =============================="<<endl;
1323 //   list< int >::iterator kpIt = myKeyPointIDs.begin();
1324 //   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1325 //     TPoint& p = myPoints[ *kpIt ];
1326 //     cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1327 //       " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1328 //  }
1329 //cout << "=============================="<<endl;
1330
1331   // Define parameters of iso-grid nodes in U and V dir
1332
1333   set< double > paramSet[ 2 ];
1334   list< list< TPoint* > >::const_iterator pListIt;
1335   list< TPoint* >::const_iterator pIt;
1336   for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1337     const list< TPoint* > & pList = * pListIt;
1338     for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1339       paramSet[0].insert( (*pIt)->myInitUV.X() );
1340       paramSet[1].insert( (*pIt)->myInitUV.Y() );
1341     }
1342   }
1343   for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1344     paramSet[0].insert( (*pIt)->myInitUV.X() );
1345     paramSet[1].insert( (*pIt)->myInitUV.Y() );
1346   }
1347   // unite close parameters and split too long segments
1348   int iDir;
1349   double tol[ 2 ];
1350   for ( iDir = 0; iDir < 2; iDir++ )
1351   {
1352     set< double > & params = paramSet[ iDir ];
1353     double range = ( *params.rbegin() - *params.begin() );
1354     double toler = range / 1e6;
1355     tol[ iDir ] = toler;
1356 //    double maxSegment = range / params.size() / 2.;
1357 //
1358 //     set< double >::iterator parIt = params.begin();
1359 //     double prevPar = *parIt;
1360 //     for ( parIt++; parIt != params.end(); parIt++ )
1361 //     {
1362 //       double segLen = (*parIt) - prevPar;
1363 //       if ( segLen < toler )
1364 //         ;//params.erase( prevPar ); // unite
1365 //       else if ( segLen > maxSegment )
1366 //         params.insert( prevPar + 0.5 * segLen ); // split
1367 //       prevPar = (*parIt);
1368 //     }
1369   }
1370
1371   // Make nodes of a grid of iso-poly-lines
1372
1373   list < TIsoNode > nodes;
1374   typedef list < TIsoNode *> TIsoLine;
1375   map < double, TIsoLine > isoMap[ 2 ];
1376
1377   set< double > & params0 = paramSet[ 0 ];
1378   set< double >::iterator par0It = params0.begin();
1379   for ( ; par0It != params0.end(); par0It++ )
1380   {
1381     TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1382     set< double > & params1 = paramSet[ 1 ];
1383     set< double >::iterator par1It = params1.begin();
1384     for ( ; par1It != params1.end(); par1It++ )
1385     {
1386       nodes.push_back( TIsoNode( *par0It, *par1It ) );
1387       isoLine0.push_back( & nodes.back() );
1388       isoMap[1][ *par1It ].push_back( & nodes.back() );
1389     }
1390   }
1391
1392   // Compute intersections of boundaries with iso-lines:
1393   // only boundary nodes will have computed UV so far
1394
1395   Bnd_Box2d uvBnd;
1396   list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1397   list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1398   for ( ; bndIt != theBndPoints.end(); bndIt++ )
1399   {
1400     const list< TPoint* > & bndPoints = * bndIt;
1401     TPoint* prevP = bndPoints.back(); // this is the first point
1402     list< TPoint* >::const_iterator pIt = bndPoints.begin();
1403     // loop on the edge-points
1404     for ( ; pIt != bndPoints.end(); pIt++ )
1405     {
1406       TPoint* point = *pIt;
1407       for ( iDir = 0; iDir < 2; iDir++ )
1408       {
1409         const int iCoord = iDir + 1;
1410         const int iOtherCoord = 2 - iDir;
1411         double par1 = prevP->myInitUV.Coord( iCoord );
1412         double par2 = point->myInitUV.Coord( iCoord );
1413         double parDif = par2 - par1;
1414         if ( Abs( parDif ) <= DBL_MIN )
1415           continue;
1416         // find iso-lines intersecting a bounadry
1417         double toler = tol[ 1 - iDir ];
1418         double minPar = Min ( par1, par2 );
1419         double maxPar = Max ( par1, par2 );
1420         map < double, TIsoLine >& isos = isoMap[ iDir ];
1421         map < double, TIsoLine >::iterator isoIt = isos.begin();
1422         for ( ; isoIt != isos.end(); isoIt++ )
1423         {
1424           double isoParam = (*isoIt).first;
1425           if ( isoParam < minPar || isoParam > maxPar )
1426             continue;
1427           double r = ( isoParam - par1 ) / parDif;
1428           gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1429           gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1430           double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1431           // find existing node with otherPar or insert a new one
1432           TIsoLine & isoLine = (*isoIt).second;
1433           double nodePar;
1434           TIsoLine::iterator nIt = isoLine.begin();
1435           for ( ; nIt != isoLine.end(); nIt++ ) {
1436             nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1437             if ( nodePar >= otherPar )
1438               break;
1439           }
1440           TIsoNode * node;
1441           if ( Abs( nodePar - otherPar ) <= toler )
1442             node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1443           else {
1444             nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1445             node = & nodes.back();
1446             isoLine.insert( nIt, node );
1447           }
1448           node->SetNotMovable();
1449           node->myUV = uv;
1450           uvBnd.Add( gp_Pnt2d( uv ));
1451 //  cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1452           // tangent dir
1453           gp_XY tgt( point->myUV - prevP->myUV );
1454           if ( ::IsEqual( r, 1. ))
1455             node->myDir[ 0 ] = tgt;
1456           else if ( ::IsEqual( r, 0. ))
1457             node->myDir[ 1 ] = tgt;
1458           else
1459             node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1460           // keep boundary nodes corresponding to boundary points
1461           if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1462             if ( bndNodes.empty() || bndNodes.back() != node )
1463               bndNodes.push_back( node );
1464         } // loop on isolines
1465       } // loop on 2 directions
1466       prevP = point;
1467     } // loop on boundary points
1468   } // loop on boundaries
1469
1470   // Define orientation
1471
1472   // find the point with the least X
1473   double leastX = DBL_MAX;
1474   TIsoNode * leftNode;
1475   list < TIsoNode >::iterator nodeIt = nodes.begin();
1476   for ( ; nodeIt != nodes.end(); nodeIt++  ) {
1477     TIsoNode & node = *nodeIt;
1478     if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1479       leastX = node.myUV.X();
1480       leftNode = &node;
1481     }
1482 // if ( node.IsUVComputed() ) {
1483 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1484 //   node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1485 //    " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1486 //      " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1487 // }
1488   }
1489   bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1490   //SCRUTE( reversed );
1491
1492   // Prepare internal nodes:
1493   // 1. connect nodes
1494   // 2. compute ratios
1495   // 3. find boundary nodes for each node
1496   // 4. remove nodes out of the boundary
1497   for ( iDir = 0; iDir < 2; iDir++ )
1498   {
1499     const int iCoord = 2 - iDir; // coord changing along an isoline
1500     map < double, TIsoLine >& isos = isoMap[ iDir ];
1501     map < double, TIsoLine >::iterator isoIt = isos.begin();
1502     for ( ; isoIt != isos.end(); isoIt++ )
1503     {
1504       TIsoLine & isoLine = (*isoIt).second;
1505       bool firstCompNodeFound = false;
1506       TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1507       nPrevIt = nIt = nNextIt = isoLine.begin();
1508       nIt++;
1509       nNextIt++; nNextIt++;
1510       while ( nIt != isoLine.end() )
1511       {
1512         // 1. connect prev - cur
1513         TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1514         if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1515           firstCompNodeFound = true;
1516           lastCompNodePos = nPrevIt;
1517         }
1518         if ( firstCompNodeFound ) {
1519           node->SetNext( prevNode, iDir, 0 );
1520           prevNode->SetNext( node, iDir, 1 );
1521         }
1522         // 2. compute ratio
1523         if ( nNextIt != isoLine.end() ) {
1524           double par1 = prevNode->myInitUV.Coord( iCoord );
1525           double par2 = node->myInitUV.Coord( iCoord );
1526           double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1527           node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1528         }
1529         // 3. find boundary nodes
1530         if ( node->IsUVComputed() )
1531           lastCompNodePos = nIt;
1532         else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1533           TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1534           for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1535             if ( (*nIt2)->IsUVComputed() )
1536               break;
1537           if ( nIt2 != isoLine.end() ) {
1538             bndNode2 = *nIt2;
1539             node->SetBoundaryNode( bndNode1, iDir, 0 );
1540             node->SetBoundaryNode( bndNode2, iDir, 1 );
1541 // cout << "--------------------------------------------------"<<endl;
1542 //  cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1543 //   " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1544 //     " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1545 //  cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1546 //   " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1547 //     " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1548           }
1549         }
1550         nIt++; nPrevIt++;
1551         if ( nNextIt != isoLine.end() ) nNextIt++;
1552         // 4. remove nodes out of the boundary
1553         if ( !firstCompNodeFound )
1554           isoLine.pop_front();
1555       } // loop on isoLine nodes
1556
1557       // remove nodes after the boundary
1558 //       for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1559 //         (*nIt)->SetNotMovable();
1560       isoLine.erase( ++lastCompNodePos, isoLine.end() );
1561     } // loop on isolines
1562   } // loop on 2 directions
1563
1564   // Compute local isoline direction for internal nodes
1565
1566   /*
1567   map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1568   map < double, TIsoLine >::iterator isoIt = isos.begin();
1569   for ( ; isoIt != isos.end(); isoIt++ )
1570   {
1571     TIsoLine & isoLine = (*isoIt).second;
1572     TIsoLine::iterator nIt = isoLine.begin();
1573     for ( ; nIt != isoLine.end(); nIt++ )
1574     {
1575       TIsoNode* node = *nIt;
1576       if ( node->IsUVComputed() || !node->IsMovable() )
1577         continue;
1578       gp_Vec2d aTgt[2], aNorm[2];
1579       double ratio[2];
1580       bool OK = true;
1581       for ( iDir = 0; iDir < 2; iDir++ )
1582       {
1583         TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1584         TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1585         if ( !bndNode1 || !bndNode2 ) {
1586           OK = false;
1587           break;
1588         }
1589         const int iCoord = 2 - iDir; // coord changing along an isoline
1590         double par1 = bndNode1->myInitUV.Coord( iCoord );
1591         double par2 = node->myInitUV.Coord( iCoord );
1592         double par3 = bndNode2->myInitUV.Coord( iCoord );
1593         ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1594
1595         gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1596         gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1597         if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1598         else                            tgt1.Reverse();
1599 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1600
1601         if ( ratio[ iDir ] < 0.5 )
1602           aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1603         else
1604           aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1605         if ( iDir == 1 )
1606           aNorm[ iDir ].Reverse();  // along iDir isoline
1607
1608         double angle = tgt1.Angle( tgt2 ); //  [-PI, PI]
1609         // maybe angle is more than |PI|
1610         if ( Abs( angle ) > PI / 2. ) {
1611           // check direction of the last but one perpendicular isoline
1612           TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1613           bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1614           bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1615           gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1616           if ( isoDir * tgt2 < 0 )
1617             isoDir.Reverse();
1618           double angle2 = tgt1.Angle( isoDir );
1619           //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1620           if (angle2 * angle < 0 && // check the sign of an angle close to PI
1621               Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1622             //MESSAGE("REVERSE ANGLE");
1623             angle = -angle;
1624           }
1625           if ( Abs( angle2 ) > Abs( angle ) ||
1626               ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1627             //MESSAGE("Add PI");
1628             // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1629             // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1630             // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1631             // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1632             // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<"  "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1633             angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1634           }
1635         }
1636         aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1637       } // loop on 2 dir
1638
1639       if ( OK ) {
1640         for ( iDir = 0; iDir < 2; iDir++ )
1641         {
1642           aTgt[iDir].Normalize();
1643           aNorm[1-iDir].Normalize();
1644           double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1645           r *= r;
1646           
1647           node->myDir[iDir] = //aTgt[iDir];
1648             aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1649         }
1650 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1651 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1652 //  cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<"  |  "
1653 //    << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1654       }
1655     } // loop on iso nodes
1656   } // loop on isolines
1657 */
1658   // Find nodes to start computing UV from
1659
1660   list< TIsoNode* > startNodes;
1661   list< TIsoNode* >::iterator nIt = bndNodes.end();
1662   TIsoNode* node = *(--nIt);
1663   TIsoNode* prevNode = *(--nIt);
1664   for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1665   {
1666     TIsoNode* nextNode = *nIt;
1667     gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1668     gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1669     double initAngle = initTgt1.Angle( initTgt2 );
1670     double angle = node->myDir[0].Angle( node->myDir[1] );
1671     if ( reversed ) angle = -angle;
1672     if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1673       // find a close internal node
1674       TIsoNode* nClose = 0;
1675       list< TIsoNode* > testNodes;
1676       testNodes.push_back( node );
1677       list< TIsoNode* >::iterator it = testNodes.begin();
1678       for ( ; !nClose && it != testNodes.end(); it++ )
1679       {
1680         for (int i = 0; i < 4; i++ )
1681         {
1682           nClose = (*it)->myNext[ i ];
1683           if ( nClose ) {
1684             if ( !nClose->IsUVComputed() )
1685               break;
1686             else {
1687               testNodes.push_back( nClose );
1688               nClose = 0;
1689             }
1690           }
1691         }
1692       }
1693       startNodes.push_back( nClose );
1694 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1695 //   node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1696 //   "initAngle: " << initAngle << " angle: " << angle << endl;
1697 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1698 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1699 //    node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1700 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1701     }
1702     prevNode = node;
1703     node = nextNode;
1704   }
1705
1706   // Compute starting UV of internal nodes
1707
1708   list < TIsoNode* > internNodes;
1709   bool needIteration = true;
1710   if ( startNodes.empty() ) {
1711     MESSAGE( " Starting UV by compUVByIsoIntersection()");
1712     needIteration = false;
1713     map < double, TIsoLine >& isos = isoMap[ 0 ];
1714     map < double, TIsoLine >::iterator isoIt = isos.begin();
1715     for ( ; isoIt != isos.end(); isoIt++ )
1716     {
1717       TIsoLine & isoLine = (*isoIt).second;
1718       TIsoLine::iterator nIt = isoLine.begin();
1719       for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1720       {
1721         TIsoNode* node = *nIt;
1722         if ( !node->IsUVComputed() && node->IsMovable() ) {
1723           internNodes.push_back( node );
1724           //bool isDeformed;
1725           if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1726                                         node->myUV, needIteration ))
1727             node->myUV = node->myInitUV;
1728         }
1729       }
1730     }
1731     if ( needIteration )
1732       for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1733       {
1734         TIsoNode* node = *nIt, *nClose = 0;
1735         list< TIsoNode* > testNodes;
1736         testNodes.push_back( node );
1737         list< TIsoNode* >::iterator it = testNodes.begin();
1738         for ( ; !nClose && it != testNodes.end(); it++ )
1739         {
1740           for (int i = 0; i < 4; i++ )
1741           {
1742             nClose = (*it)->myNext[ i ];
1743             if ( nClose ) {
1744               if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1745                 break;
1746               else {
1747                 testNodes.push_back( nClose );
1748                 nClose = 0;
1749               }
1750             }
1751           }
1752         }
1753         startNodes.push_back( nClose );
1754       }
1755   }
1756
1757   double aMin[2], aMax[2], step[2];
1758   uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1759   double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1760   step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1761   step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1762 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1763
1764   for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1765   {
1766     TIsoNode* prevN[2], *node = *nIt;
1767     if ( node->IsUVComputed() || !node->IsMovable() )
1768       continue;
1769     gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1770     int nbComp = 0, nbPrev = 0;
1771     for ( iDir = 0; iDir < 2; iDir++ )
1772     {
1773       TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1774       TIsoNode* n = node->GetNext( iDir, 0 );
1775       if ( n->IsUVComputed() )
1776         prevNode1 = n;
1777       else
1778         startNodes.push_back( n );
1779       n = node->GetNext( iDir, 1 );
1780       if ( n->IsUVComputed() )
1781         prevNode2 = n;
1782       else
1783         startNodes.push_back( n );
1784       if ( !prevNode1 ) {
1785         prevNode1 = prevNode2;
1786         prevNode2 = 0;
1787       }
1788       if ( prevNode1 ) nbPrev++;
1789       if ( prevNode2 ) nbPrev++;
1790       if ( prevNode1 ) {
1791         gp_XY dir;
1792           double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1793           double par = node->myInitUV.Coord( 2 - iDir );
1794           bool isEnd = ( prevPar > par );
1795 //          dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1796         //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1797           TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1798           gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1799           dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1800           dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1801         //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1802           //  cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1803           //     bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1804           //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1805             //" par: " << prevPar << endl;
1806           //           cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1807         //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1808         if ( prevNode2 ) {
1809           //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1810           gp_XY & uv1 = prevNode1->myUV;
1811           gp_XY & uv2 = prevNode2->myUV;
1812 //           dir = ( uv2 - uv1 );
1813 //           double len = dir.Modulus();
1814 //           if ( len > DBL_MIN )
1815 //             dir /= len * 0.5;
1816           double r = node->myRatio[ iDir ];
1817           newUV += uv1 * ( 1 - r ) + uv2 * r;
1818         }
1819         else {
1820           newUV += prevNode1->myUV + dir * step[ iDir ];
1821         }
1822         sumDir += dir;
1823         prevN[ iDir ] = prevNode1;
1824         nbComp++;
1825       }
1826     }
1827     newUV /= nbComp;
1828     node->myUV = newUV;
1829     //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1830
1831     // check if a quadrangle is not distorted
1832     if ( nbPrev > 1 ) {
1833       //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1834       if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1835       //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1836       //  cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1837         node->myUV = newUV;
1838       }
1839     }
1840     internNodes.push_back( node );
1841   }
1842   
1843   // Move nodes
1844
1845   static int maxNbIter = 100;
1846 #ifdef DEB_COMPUVBYELASTICISOLINES
1847 //   maxNbIter++;
1848   bool useNbMoveNode = 0;
1849   static int maxNbNodeMove = 100;
1850   maxNbNodeMove++;
1851   int nbNodeMove = 0;
1852   if ( !useNbMoveNode )
1853     maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1854 #endif    
1855   double maxMove;
1856   int nbIter = 0;
1857   do {
1858     if ( !needIteration) break;
1859 #ifdef DEB_COMPUVBYELASTICISOLINES
1860     if ( nbIter >= maxNbIter ) break;
1861 #endif
1862     maxMove = 0.0;
1863     list < TIsoNode* >::iterator nIt = internNodes.begin();
1864     for ( ; nIt != internNodes.end(); nIt++  ) {
1865 #ifdef DEB_COMPUVBYELASTICISOLINES
1866       if (useNbMoveNode )
1867         cout << nbNodeMove <<" =================================================="<<endl;
1868 #endif
1869       TIsoNode * node = *nIt;
1870       // make lines
1871       //gp_Lin2d line[2];
1872       gp_XY loc[2];
1873       for ( iDir = 0; iDir < 2; iDir++ )
1874       {
1875         gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
1876         gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
1877         double r = node->myRatio[ iDir ];
1878         loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
1879 //         line[ iDir ].SetLocation( loc[ iDir ] );
1880 //         line[ iDir ].SetDirection( node->myDir[ iDir ] );
1881       }
1882       // define ratio
1883       double locR[2] = { 0, 0 };
1884       for ( iDir = 0; iDir < 2; iDir++ )
1885       {
1886         const int iCoord = 2 - iDir; // coord changing along an isoline
1887         TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1888         TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1889         double par1 = bndNode1->myInitUV.Coord( iCoord );
1890         double par2 = node->myInitUV.Coord( iCoord );
1891         double par3 = bndNode2->myInitUV.Coord( iCoord );
1892         double r = ( par2 - par1 ) / ( par3 - par1 );
1893         r = Abs ( r - 0.5 ) * 2.0;  // [0,1] - distance from the middle
1894         locR[ iDir ] = ( 1 - r * r ) * 0.25;
1895       }
1896       //locR[0] = locR[1] = 0.25;
1897       // intersect the 2 lines and move a node
1898       //IntAna2d_AnaIntersection inter( line[0], line[1] );
1899       if ( /*inter.IsDone() && inter.NbPoints() ==*/ 1 )
1900       {
1901 //         double intR = 1 - locR[0] - locR[1];
1902 //         gp_XY newUV = inter.Point(1).Value().XY();
1903 //         if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
1904 //           newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
1905 //         else
1906 //           newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
1907         gp_XY newUV = 0.5 * ( loc[0] +  loc[1] );
1908         // avoid parallel isolines intersection
1909         checkQuads( node, newUV, reversed );
1910
1911         maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
1912         node->myUV = newUV;
1913       } // intersection found
1914 #ifdef DEB_COMPUVBYELASTICISOLINES
1915       if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
1916 #endif
1917     } // loop on internal nodes
1918 #ifdef DEB_COMPUVBYELASTICISOLINES
1919     if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
1920 #endif
1921   } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
1922
1923   MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
1924
1925   if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
1926     MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
1927 #ifndef DEB_COMPUVBYELASTICISOLINES
1928     return false;
1929 #endif
1930   }
1931
1932   // Set computed UV to points
1933
1934   for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1935     TPoint* point = *pIt;
1936     //gp_XY oldUV = point->myUV;
1937     double minDist = DBL_MAX;
1938     list < TIsoNode >::iterator nIt = nodes.begin();
1939     for ( ; nIt != nodes.end(); nIt++ ) {
1940       double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
1941       if ( dist < minDist ) {
1942         minDist = dist;
1943         point->myUV = (*nIt).myUV;
1944       }
1945     }
1946   }
1947       
1948     
1949   return true;
1950 }
1951
1952
1953 //=======================================================================
1954 //function : setFirstEdge
1955 //purpose  : choose the best first edge of theWire; return the summary distance
1956 //           between point UV computed by isolines intersection and
1957 //           eventual UV got from edge p-curves
1958 //=======================================================================
1959
1960 //#define DBG_SETFIRSTEDGE
1961 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
1962 {
1963   int iE, nbEdges = theWire.size();
1964   if ( nbEdges == 1 )
1965     return 0;
1966
1967   // Transform UVs computed by iso to fit bnd box of a wire
1968
1969   // max nb of points on an edge
1970   int maxNbPnt = 0;
1971   int eID = theFirstEdgeID;
1972   for ( iE = 0; iE < nbEdges; iE++ )
1973     maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
1974   
1975   // compute bnd boxes
1976   TopoDS_Face face = TopoDS::Face( myShape );
1977   Bnd_Box2d bndBox, eBndBox;
1978   eID = theFirstEdgeID;
1979   list< TopoDS_Edge >::iterator eIt;
1980   list< TPoint* >::iterator pIt;
1981   for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
1982   {
1983     // UV by isos stored in TPoint.myXYZ
1984     list< TPoint* > & ePoints = getShapePoints( eID++ );
1985     for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
1986       TPoint* p = (*pIt);
1987       bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
1988     }
1989     // UV by an edge p-curve
1990     double f, l;
1991     Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
1992     double dU = ( l - f ) / ( maxNbPnt - 1 );
1993     for ( int i = 0; i < maxNbPnt; i++ )
1994       eBndBox.Add( C2d->Value( f + i * dU ));
1995   }
1996
1997   // transform UVs by isos
1998   double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
1999   bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2000   eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2001 #ifdef DBG_SETFIRSTEDGE
2002   cout << "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2003     << eMinPar[1] << " - " << eMaxPar[1] << endl;
2004 #endif
2005   for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2006   {
2007     double dMin = eMinPar[i] - minPar[i];
2008     double dMax = eMaxPar[i] - maxPar[i];
2009     double dPar = maxPar[i] - minPar[i];
2010     eID = theFirstEdgeID;
2011     for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2012     {
2013       list< TPoint* > & ePoints = getShapePoints( eID++ );
2014       for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2015       {
2016         double par = (*pIt)->myXYZ.Coord( iC );
2017         double r = ( par - minPar[i] ) / dPar;
2018         par += ( 1 - r ) * dMin + r * dMax;
2019         (*pIt)->myXYZ.SetCoord( iC, par );
2020       }
2021     }
2022   }
2023
2024   TopoDS_Edge eBest;
2025   double minDist = DBL_MAX;
2026   for ( iE = 0 ; iE < nbEdges; iE++ )
2027   {
2028 #ifdef DBG_SETFIRSTEDGE
2029     cout << " VARIANT " << iE << endl;
2030 #endif
2031     // evaluate the distance between UV computed by the 2 methods:
2032     // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2033     double dist = 0;
2034     int eID = theFirstEdgeID;
2035     for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2036     {
2037       list< TPoint* > & ePoints = getShapePoints( eID++ );
2038       computeUVOnEdge( *eIt, ePoints );
2039       for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2040         TPoint* p = (*pIt);
2041         dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2042 #ifdef DBG_SETFIRSTEDGE
2043         cout << " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2044           p->myUV.X() << ", " << p->myUV.Y() << ") " << endl;
2045 #endif
2046       }
2047     }
2048 #ifdef DBG_SETFIRSTEDGE
2049     cout << "dist -- " << dist << endl;
2050 #endif
2051     if ( dist < minDist ) {
2052       minDist = dist;
2053       eBest = theWire.front();
2054     }
2055     // check variant with another first edge
2056     theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2057   }
2058   // put the best first edge to the theWire front
2059   if ( eBest != theWire.front() ) {
2060     eIt = find ( theWire.begin(), theWire.end(), eBest );
2061     theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2062   }
2063
2064   return minDist;
2065 }
2066
2067 //=======================================================================
2068 //function : sortSameSizeWires
2069 //purpose  : sort wires in theWireList from theFromWire until theToWire,
2070 //           the wires are set in the order to correspond to the order
2071 //           of boundaries; after sorting, edges in the wires are put
2072 //           in a good order, point UVs on edges are computed and points
2073 //           are appended to theEdgesPointsList
2074 //=======================================================================
2075
2076 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList &                theWireList,
2077                                        const TListOfEdgesList::iterator& theFromWire,
2078                                        const TListOfEdgesList::iterator& theToWire,
2079                                        const int                         theFirstEdgeID,
2080                                        list< list< TPoint* > >&          theEdgesPointsList )
2081 {
2082   TopoDS_Face F = TopoDS::Face( myShape );
2083   int iW, nbWires = 0;
2084   TListOfEdgesList::iterator wlIt = theFromWire;
2085   while ( wlIt++ != theToWire )
2086     nbWires++;
2087
2088   // Recompute key-point UVs by isolines intersection,
2089   // compute CG of key-points for each wire and bnd boxes of GCs
2090
2091   bool aBool;
2092   gp_XY orig( gp::Origin2d().XY() );
2093   vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2094   Bnd_Box2d bndBox, vBndBox;
2095   int eID = theFirstEdgeID;
2096   list< TopoDS_Edge >::iterator eIt;
2097   for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2098   {
2099     list< TopoDS_Edge > & wire = *wlIt;
2100     for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2101     {
2102       list< TPoint* > & ePoints = getShapePoints( eID++ );
2103       TPoint* p = ePoints.front();
2104       if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2105         MESSAGE("cant sortSameSizeWires()");
2106         return false;
2107       }
2108       gcVec[iW] += p->myUV;
2109       bndBox.Add( gp_Pnt2d( p->myUV ));
2110       TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2111       gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2112       vGcVec[iW] += vXY.XY();
2113       vBndBox.Add( vXY );
2114       // keep the computed UV to compare against by setFirstEdge()
2115       p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2116     }
2117     gcVec[iW] /= nbWires;
2118     vGcVec[iW] /= nbWires;
2119 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2120 //   " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2121   }
2122
2123   // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2124
2125   double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2126   bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2127   vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2128   for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2129   {
2130     double dMin = vMinPar[i] - minPar[i];
2131     double dMax = vMaxPar[i] - maxPar[i];
2132     double dPar = maxPar[i] - minPar[i];
2133     if ( Abs( dPar ) <= DBL_MIN )
2134       continue;
2135     for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2136       double par = gcVec[iW].Coord( iC );
2137       double r = ( par - minPar[i] ) / dPar;
2138       par += ( 1 - r ) * dMin + r * dMax;
2139       gcVec[iW].SetCoord( iC, par );
2140     }
2141   }
2142
2143   // Define boundary - wire correspondence by GC closeness
2144
2145   TListOfEdgesList tmpWList;
2146   tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2147   typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2148   TIntWirePosMap bndIndWirePosMap;
2149   vector< bool > bndFound( nbWires, false );
2150   for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2151   {
2152 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2153 //   " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2154     double minDist = DBL_MAX;
2155     gp_XY & wGc = vGcVec[ iW ];
2156     int bIndex;
2157     for ( int iB = 0; iB < nbWires; iB++ ) {
2158       if ( bndFound[ iB ] ) continue;
2159       double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2160       if ( dist < minDist ) {
2161         minDist = dist;
2162         bIndex = iB;
2163       }
2164     }
2165     bndFound[ bIndex ] = true;
2166     bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2167   }
2168
2169   // Treat each wire  
2170
2171   TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2172   eID = theFirstEdgeID;
2173   for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2174   {
2175     TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2176     list < TopoDS_Edge > & wire = ( *wirePos );
2177
2178     // choose the best first edge of a wire
2179     setFirstEdge( wire, eID );
2180     
2181     // compute eventual UV and fill theEdgesPointsList
2182     theEdgesPointsList.push_back( list< TPoint* >() );
2183     list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2184     for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2185     {
2186       list< TPoint* > & ePoints = getShapePoints( eID++ );
2187       computeUVOnEdge( *eIt, ePoints );
2188       edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2189     }
2190     // put wire back to theWireList
2191     wlIt = wirePos++;
2192     theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2193   }
2194
2195   return true;
2196 }
2197
2198 //=======================================================================
2199 //function : Apply
2200 //purpose  : Compute  nodes coordinates applying
2201 //           the loaded pattern to <theFace>. The first key-point
2202 //           will be mapped into <theVertexOnKeyPoint1>
2203 //=======================================================================
2204
2205 bool SMESH_Pattern::Apply (const TopoDS_Face&   theFace,
2206                            const TopoDS_Vertex& theVertexOnKeyPoint1,
2207                            const bool           theReverse)
2208 {
2209   MESSAGE(" ::Apply(face) " );
2210   TopoDS_Face face  = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2211   if ( !setShapeToMesh( face ))
2212     return false;
2213
2214   // find points on edges, it fills myNbKeyPntInBoundary
2215   if ( !findBoundaryPoints() )
2216     return false;
2217
2218   // Define the edges order so that the first edge starts at
2219   // theVertexOnKeyPoint1
2220
2221   list< TopoDS_Edge > eList;
2222   list< int >         nbVertexInWires;
2223   int nbWires = getOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2224   if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2225   {
2226     MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2227     return setErrorCode( ERR_APPLF_BAD_VERTEX );
2228   }
2229   // check nb wires and edges
2230   list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2231   l1.sort(); l2.sort();
2232   if ( l1 != l2 )
2233   {
2234     MESSAGE( "Wrong nb vertices in wires" );
2235     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2236   }
2237
2238   // here shapes get IDs, for the outer wire IDs are OK
2239   list<TopoDS_Edge>::iterator elIt = eList.begin();
2240   for ( ; elIt != eList.end(); elIt++ ) {
2241     myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2242     if ( BRep_Tool::IsClosed( *elIt, theFace ) )
2243       myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));
2244   }
2245   int nbVertices = myShapeIDMap.Extent();
2246
2247   //int nbSeamShapes = 0; // count twice seam edge and its vertices 
2248   for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2249     myShapeIDMap.Add( *elIt );
2250
2251   myShapeIDMap.Add( face );
2252
2253   if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent()/* + nbSeamShapes*/ ) {
2254     MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2255     return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2256   }
2257
2258   // points on edges to be used for UV computation of in-face points
2259   list< list< TPoint* > > edgesPointsList;
2260   edgesPointsList.push_back( list< TPoint* >() );
2261   list< TPoint* > * edgesPoints = & edgesPointsList.back();
2262   list< TPoint* >::iterator pIt;
2263
2264   // compute UV of points on the outer wire
2265   int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2266   for (iE = 0, elIt = eList.begin();
2267        iE < nbEdgesInOuterWire && elIt != eList.end();
2268        iE++, elIt++ )
2269   {
2270     list< TPoint* > & ePoints = getShapePoints( *elIt );
2271     // compute UV
2272     computeUVOnEdge( *elIt, ePoints );
2273     // collect on-edge points (excluding the last one)
2274     edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2275   }
2276
2277   // If there are several wires, define the order of edges of inner wires:
2278   // compute UV of inner edge-points using 2 methods: the one for in-face points
2279   // and the one for on-edge points and then choose the best edge order
2280   // by the best correspondance of the 2 results
2281   if ( nbWires > 1 )
2282   {
2283     // compute UV of inner edge-points using the method for in-face points
2284     // and devide eList into a list of separate wires
2285     bool aBool;
2286     list< list< TopoDS_Edge > > wireList;
2287     list<TopoDS_Edge>::iterator eIt = elIt;
2288     list<int>::iterator nbEIt = nbVertexInWires.begin();
2289     for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2290     {
2291       int nbEdges = *nbEIt;
2292       wireList.push_back( list< TopoDS_Edge >() );
2293       list< TopoDS_Edge > & wire = wireList.back();
2294       for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2295       {
2296         list< TPoint* > & ePoints = getShapePoints( *eIt );
2297         pIt = ePoints.begin();
2298         for (  pIt++; pIt != ePoints.end(); pIt++ ) {
2299           TPoint* p = (*pIt);
2300           if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2301             MESSAGE("cant Apply(face)");
2302             return false;
2303           }
2304           // keep the computed UV to compare against by setFirstEdge()
2305           p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2306         }
2307         wire.push_back( *eIt );
2308       }
2309     }
2310     // remove inner edges from eList
2311     eList.erase( elIt, eList.end() );
2312
2313     // sort wireList by nb edges in a wire
2314     sortBySize< TopoDS_Edge > ( wireList );
2315
2316     // an ID of the first edge of a boundary
2317     int id1 = nbVertices + nbEdgesInOuterWire + 1;
2318 //     if ( nbSeamShapes > 0 )
2319 //       id1 += 2; // 2 vertices more
2320
2321     // find points - edge correspondence for wires of unique size,
2322     // edge order within a wire should be defined only
2323
2324     list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2325     while ( wlIt != wireList.end() )
2326     {
2327       list< TopoDS_Edge >& wire = (*wlIt);
2328       int nbEdges = wire.size();
2329       wlIt++;
2330       if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2331       {
2332         // choose the best first edge of a wire
2333         setFirstEdge( wire, id1 );
2334
2335         // compute eventual UV and collect on-edge points
2336         edgesPointsList.push_back( list< TPoint* >() );
2337         edgesPoints = & edgesPointsList.back();
2338         int eID = id1;
2339         for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2340         {
2341           list< TPoint* > & ePoints = getShapePoints( eID++ );
2342           computeUVOnEdge( *eIt, ePoints );
2343           edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2344         }
2345       }
2346       id1 += nbEdges;
2347     }
2348
2349     // find boundary - wire correspondence for several wires of same size
2350     
2351     id1 = nbVertices + nbEdgesInOuterWire + 1;
2352     wlIt = wireList.begin();
2353     while ( wlIt != wireList.end() )
2354     {
2355       int nbSameSize = 0, nbEdges = (*wlIt).size();
2356       list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2357       wlIt2++;
2358       while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2359         nbSameSize++;
2360         wlIt2++;
2361       }
2362       if ( nbSameSize > 0 )
2363         if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2364           return false;
2365       wlIt = wlIt2;
2366       id1 += nbEdges * ( nbSameSize + 1 );
2367     }
2368
2369     // add well-ordered edges to eList
2370     
2371     for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2372     {
2373       list< TopoDS_Edge >& wire = (*wlIt);
2374       eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2375     }
2376
2377     // re-fill myShapeIDMap - all shapes get good IDs
2378
2379     myShapeIDMap.Clear();
2380     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2381       myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2382     for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2383       myShapeIDMap.Add( *elIt );
2384     myShapeIDMap.Add( face );
2385     
2386   } // there are inner wires
2387
2388   // Compute XYZ of on-edge points
2389
2390   TopLoc_Location loc;
2391   for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2392   {
2393     double f,l;
2394     Handle(Geom_Curve) C3d = BRep_Tool::Curve( *elIt, loc, f, l );
2395     const gp_Trsf & aTrsf = loc.Transformation();
2396     list< TPoint* > & ePoints = getShapePoints( iE++ );
2397     pIt = ePoints.begin();
2398     for ( pIt++; pIt != ePoints.end(); pIt++ )
2399     {
2400       TPoint* point = *pIt;
2401       point->myXYZ = C3d->Value( point->myU );
2402       if ( !loc.IsIdentity() )
2403         aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2404     }
2405   }
2406
2407   // Compute UV and XYZ of in-face points
2408
2409   // try to use a simple algo
2410   list< TPoint* > & fPoints = getShapePoints( face );
2411   bool isDeformed = false;
2412   for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2413     if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2414                                   (*pIt)->myUV, isDeformed )) {
2415       MESSAGE("cant Apply(face)");
2416       return false;
2417     }
2418   // try to use a complex algo if it is a difficult case
2419   if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2420   {
2421     for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2422       if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2423                                     (*pIt)->myUV, isDeformed )) {
2424         MESSAGE("cant Apply(face)");
2425         return false;
2426       }
2427   }
2428
2429   Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2430   const gp_Trsf & aTrsf = loc.Transformation();
2431   for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2432   {
2433     TPoint * point = *pIt;
2434     point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2435     if ( !loc.IsIdentity() )
2436       aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2437   }
2438
2439   myIsComputed = true;
2440
2441   return setErrorCode( ERR_OK );
2442 }
2443
2444 //=======================================================================
2445 //function : Load
2446 //purpose  : Create a pattern from the mesh built on <theBlock>
2447 //=======================================================================
2448
2449 bool SMESH_Pattern::Load (SMESH_Mesh*         theMesh,
2450                           const TopoDS_Shell& theBlock)
2451 {
2452   MESSAGE(" ::Load(volume) " );
2453   Clear();
2454   myIs2D = false;
2455   SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
2456
2457   // load shapes in myShapeIDMap
2458   SMESH_Block block;
2459   TopoDS_Vertex v1, v2;
2460   if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
2461     return setErrorCode( ERR_LOADV_BAD_SHAPE );
2462
2463   // count nodes
2464   int nbNodes = 0, shapeID;
2465   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
2466   {
2467     const TopoDS_Shape& S = myShapeIDMap( shapeID );
2468     SMESHDS_SubMesh * aSubMesh = aMeshDS->MeshElements( S );
2469     if ( aSubMesh )
2470       nbNodes += aSubMesh->NbNodes();
2471   }
2472   myPoints.resize( nbNodes );
2473
2474   // load U of points on edges
2475   TNodePointIDMap nodePointIDMap;
2476   int iPoint = 0;
2477   for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
2478   {
2479     const TopoDS_Shape& S = myShapeIDMap( shapeID );
2480     list< TPoint* > & shapePoints = getShapePoints( shapeID );
2481     SMESHDS_SubMesh * aSubMesh = aMeshDS->MeshElements( S );
2482     if ( ! aSubMesh ) continue;
2483     SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
2484     if ( !nIt->more() ) continue;
2485
2486       // store a node and a point
2487     while ( nIt->more() ) {
2488       const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nIt->next() );
2489       nodePointIDMap.insert( TNodePointIDMap::value_type( node, iPoint ));
2490       if ( block.IsVertexID( shapeID ))
2491         myKeyPointIDs.push_back( iPoint );
2492       TPoint* p = & myPoints[ iPoint++ ];
2493       shapePoints.push_back( p );
2494       p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
2495       p->myInitXYZ.SetCoord( 0,0,0 );
2496     }
2497     list< TPoint* >::iterator pIt = shapePoints.begin();
2498
2499     // compute init XYZ
2500     switch ( S.ShapeType() )
2501     {
2502     case TopAbs_VERTEX:
2503     case TopAbs_EDGE: {
2504
2505       for ( ; pIt != shapePoints.end(); pIt++ ) {
2506         double * coef = block.GetShapeCoef( shapeID );
2507         for ( int iCoord = 1; iCoord <= 3; iCoord++ )
2508           if ( coef[ iCoord - 1] > 0 )
2509             (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
2510       }
2511       if ( S.ShapeType() == TopAbs_VERTEX )
2512         break;
2513
2514       const TopoDS_Edge& edge = TopoDS::Edge( S );
2515       double f,l;
2516       BRep_Tool::Range( edge, f, l );
2517       int iCoord     = SMESH_Block::GetCoordIndOnEdge( shapeID );
2518       bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
2519       pIt = shapePoints.begin();
2520       nIt = aSubMesh->GetNodes();
2521       for ( ; nIt->more(); pIt++ )
2522       {
2523         const SMDS_MeshNode* node = 
2524           static_cast<const SMDS_MeshNode*>( nIt->next() );
2525         const SMDS_EdgePosition* epos =
2526           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
2527         double u = ( epos->GetUParameter() - f ) / ( l - f );
2528         (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
2529       }
2530       break;
2531     }
2532     default:
2533       for ( ; pIt != shapePoints.end(); pIt++ )
2534       {
2535         if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
2536           MESSAGE( "!block.ComputeParameters()" );
2537           return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
2538         }
2539       }
2540     }
2541   } // loop on block sub-shapes
2542
2543   // load elements
2544
2545   SMESHDS_SubMesh * aSubMesh = aMeshDS->MeshElements( theBlock );
2546   if ( aSubMesh )
2547   {
2548     SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
2549     while ( elemIt->more() ) {
2550       SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
2551       myElemPointIDs.push_back( list< int >() );
2552       list< int >& elemPoints = myElemPointIDs.back();
2553       while ( nIt->more() )
2554         elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
2555     }
2556   }
2557
2558   myIsBoundaryPointsFound = true;
2559
2560   return setErrorCode( ERR_OK );
2561 }
2562
2563 //=======================================================================
2564 //function : Apply
2565 //purpose  : Compute nodes coordinates applying
2566 //           the loaded pattern to <theBlock>. The (0,0,0) key-point
2567 //           will be mapped into <theVertex000>. The (0,0,1)
2568 //           fifth key-point will be mapped into <theVertex001>.
2569 //=======================================================================
2570
2571 bool SMESH_Pattern::Apply (const TopoDS_Shell&  theBlock,
2572                            const TopoDS_Vertex& theVertex000,
2573                            const TopoDS_Vertex& theVertex001)
2574 {
2575   MESSAGE(" ::Apply(volume) " );
2576
2577   if (!findBoundaryPoints()     || // bind ID to points
2578       !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
2579     return false;
2580
2581   SMESH_Block block;  // bind ID to shape
2582   if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
2583     return setErrorCode( ERR_APPLV_BAD_SHAPE );
2584
2585   // compute XYZ of points on shapes
2586
2587   for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
2588   {
2589     list< TPoint* > & shapePoints = getShapePoints( shapeID );
2590     list< TPoint* >::iterator pIt = shapePoints.begin();
2591     const TopoDS_Shape& S = myShapeIDMap( shapeID );
2592     switch ( S.ShapeType() )
2593     {
2594     case TopAbs_VERTEX: {
2595
2596       for ( ; pIt != shapePoints.end(); pIt++ )
2597         block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
2598       break;
2599     }
2600     case TopAbs_EDGE: {
2601
2602       for ( ; pIt != shapePoints.end(); pIt++ )
2603         block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
2604       break;
2605     }
2606     case TopAbs_FACE: {
2607
2608       for ( ; pIt != shapePoints.end(); pIt++ )
2609         block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
2610       break;
2611     }
2612     default:
2613       for ( ; pIt != shapePoints.end(); pIt++ )
2614         block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
2615     }
2616   } // loop on block sub-shapes
2617
2618   myIsComputed = true;
2619
2620   return setErrorCode( ERR_OK );
2621 }
2622
2623 //=======================================================================
2624 //function : MakeMesh
2625 //purpose  : Create nodes and elements in <theMesh> using nodes
2626 //           coordinates computed by either of Apply...() methods
2627 //=======================================================================
2628
2629 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh)
2630 {
2631   MESSAGE(" ::MakeMesh() " );
2632   if ( !myIsComputed )
2633     return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
2634
2635   SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
2636
2637   // clear elements and nodes existing on myShape
2638   SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( myShape );
2639   SMESHDS_SubMesh * aSubMeshDS = aMeshDS->MeshElements( myShape );
2640   if ( aSubMesh )
2641     aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
2642   else if ( aSubMeshDS )
2643   {
2644     SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
2645     while ( eIt->more() )
2646       aMeshDS->RemoveElement( eIt->next() );
2647     SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
2648     while ( nIt->more() )
2649       aMeshDS->RemoveNode( static_cast<const SMDS_MeshNode*>( nIt->next() ));
2650   }
2651
2652   // loop on sub-shapes of myShape: create nodes and build point-node map
2653   typedef map< TPoint*, const SMDS_MeshNode* > TPointNodeMap;
2654   TPointNodeMap pointNodeMap;
2655   map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
2656   for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
2657   {
2658     const TopoDS_Shape & S = myShapeIDMap( (*idPointIt).first );
2659     list< TPoint* > & points = (*idPointIt).second;
2660     SMESHDS_SubMesh * subMeshDS = aMeshDS->MeshElements( S );
2661     SMESH_subMesh * subMesh = theMesh->GetSubMeshContaining( myShape );
2662     list< TPoint* >::iterator pIt = points.begin();
2663     for ( ; pIt != points.end(); pIt++ )
2664     {
2665       TPoint* point = *pIt;
2666       if ( pointNodeMap.find( point ) != pointNodeMap.end() )
2667         continue;
2668       SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
2669                                               point->myXYZ.Y(),
2670                                               point->myXYZ.Z());
2671       pointNodeMap.insert( TPointNodeMap::value_type( point, node ));
2672       if ( subMeshDS ) {
2673         switch ( S.ShapeType() ) {
2674         case TopAbs_VERTEX: {
2675           aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S ));
2676           break;
2677         }
2678         case TopAbs_EDGE: {
2679           aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ));
2680           SMDS_EdgePosition* epos =
2681             dynamic_cast<SMDS_EdgePosition *>(node->GetPosition().get());
2682           epos->SetUParameter( point->myU );
2683           break;
2684         }
2685         case TopAbs_FACE: {
2686           aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ));
2687           SMDS_FacePosition* pos =
2688             dynamic_cast<SMDS_FacePosition *>(node->GetPosition().get());
2689           pos->SetUParameter( point->myUV.X() );
2690           pos->SetVParameter( point->myUV.Y() );
2691           break;
2692         }
2693         default:
2694           aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
2695         }
2696       }
2697     }
2698     // make that SMESH_subMesh::_computeState = COMPUTE_OK
2699     // so that operations with hypotheses will erase the mesh
2700     // being built
2701     if ( subMesh )
2702       subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
2703   }
2704
2705   // create elements
2706   list<list< int > >::iterator epIt = myElemPointIDs.begin();
2707   for ( ; epIt != myElemPointIDs.end(); epIt++ )
2708   {
2709     list< int > & elemPoints = *epIt;
2710     // retrieve nodes
2711     const SMDS_MeshNode* nodes[ 8 ];
2712     list< int >::iterator iIt = elemPoints.begin();
2713     int nbNodes;
2714     for ( nbNodes = 0; iIt != elemPoints.end(); iIt++ ) {
2715       nodes[ nbNodes++ ] = pointNodeMap[ & myPoints[ *iIt ]];
2716     }
2717     // add an element
2718     const SMDS_MeshElement* elem = 0;
2719     if ( myIs2D ) {
2720       switch ( nbNodes ) {
2721       case 3:
2722         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
2723       case 4:
2724         elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
2725       default:;
2726       }
2727     }
2728     else {
2729       switch ( nbNodes ) {
2730       case 4:
2731         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
2732       case 5:
2733         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
2734                                    nodes[4] ); break;
2735       case 6:
2736         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
2737                                    nodes[4], nodes[5] ); break;
2738       case 8:
2739         elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
2740                                    nodes[4], nodes[5], nodes[6], nodes[7] ); break;
2741       default:;
2742       }
2743     }
2744     if ( elem )
2745       aMeshDS->SetMeshElementOnShape( elem, myShape );
2746   }
2747
2748   return setErrorCode( ERR_OK );
2749 }
2750
2751
2752 //=======================================================================
2753 //function : arrangeBoundaries
2754 //purpose  : if there are several wires, arrange boundaryPoints so that
2755 //           the outer wire goes first and fix inner wires orientation
2756 //           update myKeyPointIDs to correspond to the order of key-points
2757 //           in boundaries; sort internal boundaries by the nb of key-points
2758 //=======================================================================
2759
2760 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
2761 {
2762   typedef list< list< TPoint* > >::iterator TListOfListIt;
2763   TListOfListIt bndIt;
2764   list< TPoint* >::iterator pIt;
2765
2766   int nbBoundaries = boundaryList.size();
2767   if ( nbBoundaries > 1 )
2768   {
2769     // sort boundaries by nb of key-points
2770     if ( nbBoundaries > 2 )
2771     {
2772       // move boundaries in tmp list
2773       list< list< TPoint* > > tmpList; 
2774       tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
2775       // make a map nb-key-points to boundary-position-in-tmpList,
2776       // boundary-positions get ordered in it
2777       typedef map< int, TListOfListIt > TNbKpBndPosMap;
2778       TNbKpBndPosMap nbKpBndPosMap;
2779       bndIt = tmpList.begin();
2780       list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
2781       for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
2782         int nb = *nbKpIt * nbBoundaries;
2783         while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
2784           nb++;
2785         nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
2786       }
2787       // move boundaries back to boundaryList
2788       TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
2789       for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
2790         TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
2791         TListOfListIt bndPos1 = bndPos2++;
2792         boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
2793       }
2794     }
2795
2796     // Look for the outer boundary: the one with the point with the least X
2797     double leastX = DBL_MAX;
2798     TListOfListIt outerBndPos;
2799     for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
2800     {
2801       list< TPoint* >& boundary = (*bndIt);
2802       for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
2803       {
2804         TPoint* point = *pIt;
2805         if ( point->myInitXYZ.X() < leastX ) {
2806           leastX = point->myInitXYZ.X();
2807           outerBndPos = bndIt;
2808         }
2809       }
2810     }
2811
2812     if ( outerBndPos != boundaryList.begin() )
2813       boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
2814
2815   } // if nbBoundaries > 1
2816                  
2817   // Check boundaries orientation and re-fill myKeyPointIDs
2818
2819   set< TPoint* > keyPointSet;
2820   list< int >::iterator kpIt = myKeyPointIDs.begin();
2821   for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
2822     keyPointSet.insert( & myPoints[ *kpIt ]);
2823   myKeyPointIDs.clear();
2824
2825   // update myNbKeyPntInBoundary also
2826   list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
2827
2828   for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
2829   {
2830     // find the point with the least X
2831     double leastX = DBL_MAX;
2832     list< TPoint* >::iterator xpIt;
2833     list< TPoint* >& boundary = (*bndIt);
2834     for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
2835     {
2836       TPoint* point = *pIt;
2837       if ( point->myInitXYZ.X() < leastX ) {
2838         leastX = point->myInitXYZ.X();
2839         xpIt = pIt;
2840       }
2841     }
2842     // find points next to the point with the least X
2843     TPoint* p = *xpIt, *pPrev, *pNext;
2844     if ( p == boundary.front() )
2845       pPrev = *(++boundary.rbegin());
2846     else {
2847       xpIt--;
2848       pPrev = *xpIt;
2849       xpIt++;
2850     }
2851     if ( p == boundary.back() )
2852       pNext = *(++boundary.begin());
2853     else {
2854       xpIt++;
2855       pNext = *xpIt;
2856     }
2857     // vectors of boundary direction near <p>
2858     gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
2859     double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
2860     if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
2861       double yPrev = v1.Y() / sqrt( sqMag1 );
2862       double yNext = v2.Y() / sqrt( sqMag2 );
2863       double sumY = yPrev + yNext;
2864       bool reverse;
2865       if ( bndIt == boundaryList.begin() ) // outer boundary
2866         reverse = sumY > 0;
2867       else
2868         reverse = sumY < 0;
2869       if ( reverse )
2870         boundary.reverse();
2871     }
2872
2873     // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
2874     (*nbKpIt) = 0; // count nb of key-points again
2875     pIt = boundary.begin();
2876     for ( ; pIt != boundary.end(); pIt++)
2877     {
2878       TPoint* point = *pIt;
2879       if ( keyPointSet.find( point ) == keyPointSet.end() )
2880         continue;
2881       // find an index of a keypoint
2882       int index = 0;
2883       vector< TPoint >::const_iterator pVecIt = myPoints.begin();
2884       for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
2885         if ( &(*pVecIt) == point )
2886           break;
2887       myKeyPointIDs.push_back( index );
2888       (*nbKpIt)++;
2889     }
2890     myKeyPointIDs.pop_back(); // remove the first key-point from the back
2891     (*nbKpIt)--;
2892
2893   } // loop on a list of boundaries
2894
2895   ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
2896 }
2897
2898 //=======================================================================
2899 //function : findBoundaryPoints
2900 //purpose  : if loaded from file, find points to map on edges and faces and
2901 //           compute their parameters
2902 //=======================================================================
2903
2904 bool SMESH_Pattern::findBoundaryPoints()
2905 {
2906   if ( myIsBoundaryPointsFound ) return true;
2907
2908   MESSAGE(" findBoundaryPoints() ");
2909
2910   if ( myIs2D )
2911   {
2912     set< TPoint* > pointsInElems;
2913
2914     // Find free links of elements:
2915     // put links of all elements in a set and remove links encountered twice
2916
2917     typedef pair< TPoint*, TPoint*> TLink;
2918     set< TLink > linkSet;
2919     list<list< int > >::iterator epIt = myElemPointIDs.begin();
2920     for ( ; epIt != myElemPointIDs.end(); epIt++ )
2921     {
2922       list< int > & elemPoints = *epIt;
2923       list< int >::iterator pIt = elemPoints.begin();
2924       int prevP = elemPoints.back();
2925       for ( ; pIt != elemPoints.end(); pIt++ ) {
2926         TPoint* p1 = & myPoints[ prevP ];
2927         TPoint* p2 = & myPoints[ *pIt ];
2928         TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
2929         ASSERT( link.first != link.second );
2930         pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
2931         if ( !itUniq.second )
2932           linkSet.erase( itUniq.first );
2933         prevP = *pIt;
2934
2935         pointsInElems.insert( p1 );
2936       }
2937     }
2938     // Now linkSet contains only free links,
2939     // find the points order that they have in boundaries
2940
2941     // 1. make a map of key-points
2942     set< TPoint* > keyPointSet;
2943     list< int >::iterator kpIt = myKeyPointIDs.begin();
2944     for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
2945       keyPointSet.insert( & myPoints[ *kpIt ]);
2946
2947     // 2. chain up boundary points
2948     list< list< TPoint* > > boundaryList;
2949     boundaryList.push_back( list< TPoint* >() );
2950     list< TPoint* > * boundary = & boundaryList.back();
2951
2952     TPoint *point1, *point2, *keypoint1;
2953     kpIt = myKeyPointIDs.begin();
2954     point1 = keypoint1 = & myPoints[ *kpIt++ ];
2955     // loop on free links: look for the next point
2956     int iKeyPoint = 0;
2957     set< TLink >::iterator lIt = linkSet.begin();
2958     while ( lIt != linkSet.end() )
2959     {
2960       if ( (*lIt).first == point1 )
2961         point2 = (*lIt).second;
2962       else if ( (*lIt).second == point1 )
2963         point2 = (*lIt).first;
2964       else {
2965         lIt++;
2966         continue;
2967       }
2968       linkSet.erase( lIt );
2969       lIt = linkSet.begin();
2970
2971       if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
2972       {
2973         boundary->push_back( point2 );
2974       }
2975       else // a key-point found
2976       {
2977         keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
2978         iKeyPoint++;
2979         if ( point2 != keypoint1 ) // its not the boundary end
2980         {
2981           boundary->push_back( point2 );
2982         }
2983         else  // the boundary end reached
2984         {
2985           boundary->push_front( keypoint1 );
2986           boundary->push_back( keypoint1 );
2987           myNbKeyPntInBoundary.push_back( iKeyPoint );
2988           if ( keyPointSet.empty() )
2989             break; // all boundaries containing key-points are found
2990
2991           // prepare to search for the next boundary
2992           boundaryList.push_back( list< TPoint* >() );
2993           boundary = & boundaryList.back();
2994           point2 = keypoint1 = (*keyPointSet.begin());
2995         }
2996       }
2997       point1 = point2;
2998     } // loop on the free links set
2999
3000     if ( boundary->empty() ) {
3001       MESSAGE(" a separate key-point");
3002       return setErrorCode( ERR_READ_BAD_KEY_POINT );
3003     }
3004
3005     // if there are several wires, arrange boundaryPoints so that
3006     // the outer wire goes first and fix inner wires orientation;
3007     // sort myKeyPointIDs to correspond to the order of key-points
3008     // in boundaries
3009     arrangeBoundaries( boundaryList );
3010
3011     // Find correspondence shape ID - points,
3012     // compute points parameter on edge
3013
3014     keyPointSet.clear();
3015     for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
3016       keyPointSet.insert( & myPoints[ *kpIt ]);
3017
3018     set< TPoint* > edgePointSet; // to find in-face points
3019     int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
3020     int edgeID = myKeyPointIDs.size() + 1;
3021
3022     list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
3023     for ( ; bndIt != boundaryList.end(); bndIt++ )
3024     {
3025       boundary = & (*bndIt);
3026       double edgeLength = 0;
3027       list< TPoint* >::iterator pIt = boundary->begin();
3028       getShapePoints( edgeID ).push_back( *pIt );
3029       for ( pIt++; pIt != boundary->end(); pIt++)
3030       {
3031         list< TPoint* > & edgePoints = getShapePoints( edgeID );
3032         TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
3033         TPoint* point = *pIt;
3034         edgePointSet.insert( point );
3035         if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
3036         {
3037           edgePoints.push_back( point );
3038           edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
3039           point->myInitU = edgeLength;
3040         }
3041         else // a key-point
3042         {
3043           // treat points on the edge which ends up: compute U [0,1]
3044           edgePoints.push_back( point );
3045           if ( edgePoints.size() > 2 ) {
3046             edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
3047             list< TPoint* >::iterator epIt = edgePoints.begin();
3048             for ( ; epIt != edgePoints.end(); epIt++ )
3049               (*epIt)->myInitU /= edgeLength;
3050           }
3051           // begin the next edge treatment
3052           edgeLength = 0;
3053           getShapePoints( vertexID++ ).push_back( point );
3054           edgeID++;
3055           if ( point != boundary->front() )
3056             getShapePoints( edgeID ).push_back( point );
3057         }
3058       }
3059     }
3060
3061     // find in-face points
3062     list< TPoint* > & facePoints = getShapePoints( edgeID );
3063     vector< TPoint >::iterator pVecIt = myPoints.begin();
3064     for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
3065       TPoint* point = &(*pVecIt);
3066       if ( edgePointSet.find( point ) == edgePointSet.end() &&
3067           pointsInElems.find( point ) != pointsInElems.end())
3068         facePoints.push_back( point );
3069     }
3070
3071   } // 2D case
3072
3073   else // 3D case
3074   {
3075     // bind points to shapes according to point parameters
3076     vector< TPoint >::iterator pVecIt = myPoints.begin();
3077     for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
3078       TPoint* point = &(*pVecIt);
3079       int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
3080       getShapePoints( shapeID ).push_back( point );
3081       // detect key-points
3082       if ( SMESH_Block::IsVertexID( shapeID ))
3083         myKeyPointIDs.push_back( i );        
3084     }
3085   }
3086
3087   myIsBoundaryPointsFound = true;
3088   return myIsBoundaryPointsFound;
3089 }
3090
3091 //=======================================================================
3092 //function : Clear
3093 //purpose  : clear fields
3094 //=======================================================================
3095
3096 void SMESH_Pattern::Clear()
3097 {
3098   myIsComputed = myIsBoundaryPointsFound = false;
3099
3100   myPoints.clear();
3101   myKeyPointIDs.clear();
3102   myElemPointIDs.clear();
3103   myShapeIDToPointsMap.clear();
3104   myShapeIDMap.Clear();
3105   myShape.Nullify();
3106   myNbKeyPntInBoundary.clear();
3107 }
3108
3109 //=======================================================================
3110 //function : setShapeToMesh
3111 //purpose  : set a shape to be meshed. Return True if meshing is possible
3112 //=======================================================================
3113
3114 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
3115 {
3116   if ( !IsLoaded() ) {
3117     MESSAGE( "Pattern not loaded" );
3118     return setErrorCode( ERR_APPL_NOT_LOADED );
3119   }
3120
3121   TopAbs_ShapeEnum aType = theShape.ShapeType();
3122   bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
3123   if ( !dimOk ) {
3124     MESSAGE( "Pattern dimention mismatch" );
3125     return setErrorCode( ERR_APPL_BAD_DIMENTION );
3126   }
3127
3128   // check if a face is closed
3129   int nbNodeOnSeamEdge = 0;
3130   if ( myIs2D ) {
3131     TopoDS_Face face = TopoDS::Face( theShape );
3132     TopExp_Explorer eExp( theShape, TopAbs_EDGE );
3133     for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() )
3134       if ( BRep_Tool::IsClosed( TopoDS::Edge( eExp.Current() ), face ))
3135         nbNodeOnSeamEdge = 2;
3136   }
3137     
3138   // check nb of vertices
3139   TopTools_IndexedMapOfShape vMap;
3140   TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
3141   if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
3142     MESSAGE( myKeyPointIDs.size() << " != " << vMap.Extent() );
3143     return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3144   }
3145
3146   myShapeIDMap.Clear();
3147   myShape = theShape;
3148   return true;
3149 }
3150
3151 //=======================================================================
3152 //function : GetMappedPoints
3153 //purpose  : Return nodes coordinates computed by Apply() method
3154 //=======================================================================
3155
3156 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints )
3157 {
3158   thePoints.clear();
3159   if ( !myIsComputed )
3160     return false;
3161
3162   vector< TPoint >::iterator pVecIt = myPoints.begin();
3163   for ( ; pVecIt != myPoints.end(); pVecIt++ )
3164     thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
3165
3166   return ( thePoints.size() > 0 );
3167 }
3168
3169
3170 //=======================================================================
3171 //function : GetPoints
3172 //purpose  : Return nodes coordinates of the pattern
3173 //=======================================================================
3174
3175 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
3176 {
3177   thePoints.clear();
3178
3179   if ( !IsLoaded() )
3180     return false;
3181
3182   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
3183   for ( ; pVecIt != myPoints.end(); pVecIt++ )
3184     thePoints.push_back( & (*pVecIt).myInitXYZ );
3185
3186   return ( thePoints.size() > 0 );
3187 }
3188
3189 //=======================================================================
3190 //function : getShapePoints
3191 //purpose  : return list of points located on theShape
3192 //=======================================================================
3193
3194 list< SMESH_Pattern::TPoint* > &
3195   SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
3196 {
3197   int aShapeID;
3198   if ( !myShapeIDMap.Contains( theShape ))
3199     aShapeID = myShapeIDMap.Add( theShape );
3200   else
3201     aShapeID = myShapeIDMap.FindIndex( theShape );
3202
3203   return myShapeIDToPointsMap[ aShapeID ];
3204 }
3205
3206 //=======================================================================
3207 //function : getShapePoints
3208 //purpose  : return list of points located on the shape
3209 //=======================================================================
3210
3211 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
3212 {
3213   return myShapeIDToPointsMap[ theShapeID ];
3214 }
3215
3216 //=======================================================================
3217 //function : DumpPoints
3218 //purpose  : Debug
3219 //=======================================================================
3220
3221 void SMESH_Pattern::DumpPoints() const
3222 {
3223 #ifdef _DEBUG_
3224   vector< TPoint >::const_iterator pVecIt = myPoints.begin();
3225   for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
3226     cout << i << ": " << *pVecIt;
3227 #endif
3228 }
3229
3230 //=======================================================================
3231 //function : TPoint()
3232 //purpose  : 
3233 //=======================================================================
3234
3235 SMESH_Pattern::TPoint::TPoint()
3236 {
3237 #ifdef _DEBUG_
3238   myInitXYZ.SetCoord(0,0,0);
3239   myInitUV.SetCoord(0.,0.);
3240   myInitU = 0;
3241   myXYZ.SetCoord(0,0,0);
3242   myUV.SetCoord(0.,0.);
3243   myU = 0;
3244 #endif
3245 }
3246
3247 //=======================================================================
3248 //function : operator <<
3249 //purpose  : 
3250 //=======================================================================
3251
3252 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
3253 {
3254   gp_XYZ xyz = p.myInitXYZ;
3255   OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
3256   gp_XY xy = p.myInitUV;
3257   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
3258   double u = p.myInitU;
3259   OS << " u( " <<  u << " )) " << &p << endl;
3260   xyz = p.myXYZ.XYZ();
3261   OS << "\t    ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
3262   xy = p.myUV;
3263   OS << " uv( " <<  xy.X() << " " << xy.Y() << " )";
3264   u = p.myU;
3265   OS << " u( " <<  u << " ))" << endl;
3266   
3267   return OS;
3268 }