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