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