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