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