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