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