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