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