1 // Copyright (C) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_Pattern.hxx
24 // Created : Mon Aug 2 10:30:00 2004
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_Pattern.hxx"
29 #include <BRepAdaptor_Curve.hxx>
30 #include <BRepTools.hxx>
31 #include <BRepTools_WireExplorer.hxx>
32 #include <BRep_Tool.hxx>
33 #include <Bnd_Box.hxx>
34 #include <Bnd_Box2d.hxx>
36 #include <Extrema_ExtPC.hxx>
37 #include <Extrema_GenExtPS.hxx>
38 #include <Extrema_POnSurf.hxx>
39 #include <Geom2d_Curve.hxx>
40 #include <GeomAdaptor_Surface.hxx>
41 #include <Geom_Curve.hxx>
42 #include <Geom_Surface.hxx>
43 #include <Precision.hxx>
44 #include <TopAbs_ShapeEnum.hxx>
46 #include <TopExp_Explorer.hxx>
47 #include <TopLoc_Location.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
50 #include <TopoDS_Edge.hxx>
51 #include <TopoDS_Face.hxx>
52 #include <TopoDS_Iterator.hxx>
53 #include <TopoDS_Shell.hxx>
54 #include <TopoDS_Vertex.hxx>
55 #include <TopoDS_Wire.hxx>
57 #include <gp_Lin2d.hxx>
58 #include <gp_Pnt2d.hxx>
59 #include <gp_Trsf.hxx>
63 #include "SMDS_EdgePosition.hxx"
64 #include "SMDS_FacePosition.hxx"
65 #include "SMDS_MeshElement.hxx"
66 #include "SMDS_MeshFace.hxx"
67 #include "SMDS_MeshNode.hxx"
68 #include "SMDS_VolumeTool.hxx"
69 #include "SMESHDS_Group.hxx"
70 #include "SMESHDS_Mesh.hxx"
71 #include "SMESHDS_SubMesh.hxx"
72 #include "SMESH_Block.hxx"
73 #include "SMESH_Mesh.hxx"
74 #include "SMESH_MesherHelper.hxx"
75 #include "SMESH_subMesh.hxx"
77 #include <Basics_Utils.hxx>
78 #include "utilities.h"
82 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
84 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
86 //=======================================================================
87 //function : SMESH_Pattern
89 //=======================================================================
91 SMESH_Pattern::SMESH_Pattern ()
94 //=======================================================================
97 //=======================================================================
99 static inline int getInt( const char * theSring )
101 if ( *theSring < '0' || *theSring > '9' )
105 int val = strtol( theSring, &ptr, 10 );
106 if ( ptr == theSring ||
107 // there must not be neither '.' nor ',' nor 'E' ...
108 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
114 //=======================================================================
115 //function : getDouble
117 //=======================================================================
119 static inline double getDouble( const char * theSring )
122 return strtod( theSring, &ptr );
125 //=======================================================================
126 //function : readLine
127 //purpose : Put token starting positions in theFields until '\n' or '\0'
128 // Return the number of the found tokens
129 //=======================================================================
131 static int readLine (list <const char*> & theFields,
132 const char* & theLineBeg,
133 const bool theClearFields )
135 if ( theClearFields )
140 /* switch ( symbol ) { */
141 /* case white-space: */
142 /* look for a non-space symbol; */
143 /* case string-end: */
146 /* case comment beginning: */
147 /* skip all till a line-end; */
149 /* put its position in theFields, skip till a white-space;*/
155 bool stopReading = false;
158 bool isNumber = false;
159 switch ( *theLineBeg )
161 case ' ': // white space
166 case '\n': // a line ends
167 stopReading = ( nbRead > 0 );
172 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
176 case '\0': // file ends
179 case '-': // real number
184 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
186 theFields.push_back( theLineBeg );
189 while (*theLineBeg != ' ' &&
190 *theLineBeg != '\n' &&
191 *theLineBeg != '\0');
195 return 0; // incorrect file format
201 } while ( !stopReading );
206 //=======================================================================
208 //purpose : Load a pattern from <theFile>
209 //=======================================================================
211 bool SMESH_Pattern::Load (const char* theFileContents)
213 MESSAGE("Load( file ) ");
215 Kernel_Utils::Localizer loc;
219 // ! This is a comment
220 // NB_POINTS ! 1 integer - the number of points in the pattern.
221 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
222 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
224 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
225 // ! elements description goes after all
226 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
231 const char* lineBeg = theFileContents;
232 list <const char*> fields;
233 const bool clearFields = true;
235 // NB_POINTS ! 1 integer - the number of points in the pattern.
237 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
238 MESSAGE("Error reading NB_POINTS");
239 return setErrorCode( ERR_READ_NB_POINTS );
241 int nbPoints = getInt( fields.front() );
243 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
245 // read the first point coordinates to define pattern dimention
246 int dim = readLine( fields, lineBeg, clearFields );
252 MESSAGE("Error reading points: wrong nb of coordinates");
253 return setErrorCode( ERR_READ_POINT_COORDS );
255 if ( nbPoints <= dim ) {
256 MESSAGE(" Too few points ");
257 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
260 // read the rest points
262 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
263 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
264 MESSAGE("Error reading points : wrong nb of coordinates ");
265 return setErrorCode( ERR_READ_POINT_COORDS );
267 // store point coordinates
268 myPoints.resize( nbPoints );
269 list <const char*>::iterator fIt = fields.begin();
270 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
272 TPoint & p = myPoints[ iPoint ];
273 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
275 double coord = getDouble( *fIt );
276 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
277 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
279 return setErrorCode( ERR_READ_3D_COORD );
281 p.myInitXYZ.SetCoord( iCoord, coord );
283 p.myInitUV.SetCoord( iCoord, coord );
287 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
290 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
291 MESSAGE("Error: missing key-points");
293 return setErrorCode( ERR_READ_NO_KEYPOINT );
296 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
298 int pointIndex = getInt( *fIt );
299 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
300 MESSAGE("Error: invalid point index " << pointIndex );
302 return setErrorCode( ERR_READ_BAD_INDEX );
304 if ( idSet.insert( pointIndex ).second ) // unique?
305 myKeyPointIDs.push_back( pointIndex );
309 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
311 while ( readLine( fields, lineBeg, clearFields ))
313 myElemPointIDs.push_back( TElemDef() );
314 TElemDef& elemPoints = myElemPointIDs.back();
315 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
317 int pointIndex = getInt( *fIt );
318 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
319 MESSAGE("Error: invalid point index " << pointIndex );
321 return setErrorCode( ERR_READ_BAD_INDEX );
323 elemPoints.push_back( pointIndex );
325 // check the nb of nodes in element
327 switch ( elemPoints.size() ) {
328 case 3: if ( !myIs2D ) Ok = false; break;
332 case 8: if ( myIs2D ) Ok = false; break;
336 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
338 return setErrorCode( ERR_READ_ELEM_POINTS );
341 if ( myElemPointIDs.empty() ) {
342 MESSAGE("Error: no elements");
344 return setErrorCode( ERR_READ_NO_ELEMS );
347 findBoundaryPoints(); // sort key-points
349 return setErrorCode( ERR_OK );
352 //=======================================================================
354 //purpose : Save the loaded pattern into the file <theFileName>
355 //=======================================================================
357 bool SMESH_Pattern::Save (ostream& theFile)
359 MESSAGE(" ::Save(file) " );
361 Kernel_Utils::Localizer loc;
364 MESSAGE(" Pattern not loaded ");
365 return setErrorCode( ERR_SAVE_NOT_LOADED );
368 theFile << "!!! SALOME Mesh Pattern file" << endl;
369 theFile << "!!!" << endl;
370 theFile << "!!! Nb of points:" << endl;
371 theFile << myPoints.size() << endl;
375 // theFile.width( 8 );
376 // theFile.setf(ios::fixed);// use 123.45 floating notation
377 // theFile.setf(ios::right);
378 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
379 // theFile.setf(ios::showpoint); // do not show trailing zeros
380 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
381 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
382 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
383 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
384 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
385 theFile << " !- " << i << endl; // point id to ease reading by a human being
389 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
390 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
391 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
392 theFile << " " << *kpIt;
393 if ( !myKeyPointIDs.empty() )
397 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
398 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
399 for ( ; epIt != myElemPointIDs.end(); epIt++ )
401 const TElemDef & elemPoints = *epIt;
402 TElemDef::const_iterator iIt = elemPoints.begin();
403 for ( ; iIt != elemPoints.end(); iIt++ )
404 theFile << " " << *iIt;
410 return setErrorCode( ERR_OK );
413 //=======================================================================
414 //function : sortBySize
415 //purpose : sort theListOfList by size
416 //=======================================================================
418 template<typename T> struct TSizeCmp {
419 bool operator ()( const list < T > & l1, const list < T > & l2 )
420 const { return l1.size() < l2.size(); }
423 template<typename T> void sortBySize( list< list < T > > & theListOfList )
425 if ( theListOfList.size() > 2 ) {
426 TSizeCmp< T > SizeCmp;
427 theListOfList.sort( SizeCmp );
431 //=======================================================================
434 //=======================================================================
436 static gp_XY project (const SMDS_MeshNode* theNode,
437 Extrema_GenExtPS & theProjectorPS)
439 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
440 theProjectorPS.Perform( P );
441 if ( !theProjectorPS.IsDone() ) {
442 MESSAGE( "SMESH_Pattern: point projection FAILED");
445 double u, v, minVal = DBL_MAX;
446 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
447 if ( theProjectorPS.Value( i ) < minVal ) {
448 minVal = theProjectorPS.Value( i );
449 theProjectorPS.Point( i ).Parameter( u, v );
451 return gp_XY( u, v );
454 //=======================================================================
455 //function : areNodesBound
456 //purpose : true if all nodes of faces are bound to shapes
457 //=======================================================================
459 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
461 while ( faceItr->more() )
463 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
464 while ( nIt->more() )
466 const SMDS_MeshNode* node = smdsNode( nIt->next() );
467 if (node->getshapeId() <1) {
475 //=======================================================================
476 //function : isMeshBoundToShape
477 //purpose : return true if all 2d elements are bound to shape
478 // if aFaceSubmesh != NULL, then check faces bound to it
479 // else check all faces in aMeshDS
480 //=======================================================================
482 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
483 SMESHDS_SubMesh * aFaceSubmesh,
484 const bool isMainShape)
487 // check that all faces are bound to aFaceSubmesh
488 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
492 // check face nodes binding
493 if ( aFaceSubmesh ) {
494 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
495 return areNodesBound( fIt );
497 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
498 return areNodesBound( fIt );
501 //=======================================================================
503 //purpose : Create a pattern from the mesh built on <theFace>.
504 // <theProject>==true makes override nodes positions
505 // on <theFace> computed by mesher
506 //=======================================================================
508 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
509 const TopoDS_Face& theFace,
512 MESSAGE(" ::Load(face) " );
516 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
517 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
518 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
519 SMESH_MesherHelper helper( *theMesh );
520 helper.SetSubShape( theFace );
522 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
523 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
524 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
526 MESSAGE( "No elements bound to the face");
527 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
530 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
532 // check if face is closed
533 bool isClosed = helper.HasSeam();
535 list<TopoDS_Edge> eList;
536 list<TopoDS_Edge>::iterator elIt;
537 SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
539 // check that requested or needed projection is possible
540 bool isMainShape = theMesh->IsMainShape( face );
541 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
542 bool canProject = ( nbElems ? true : isMainShape );
544 canProject = false; // so far
546 if ( ( theProject || needProject ) && !canProject )
547 return setErrorCode( ERR_LOADF_CANT_PROJECT );
549 Extrema_GenExtPS projector;
550 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
551 if ( theProject || needProject )
552 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
555 TNodePointIDMap nodePointIDMap;
556 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
560 MESSAGE("Project the submesh");
561 // ---------------------------------------------------------------
562 // The case where the submesh is projected to theFace
563 // ---------------------------------------------------------------
566 list< const SMDS_MeshElement* > faces;
568 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
569 while ( fIt->more() ) {
570 const SMDS_MeshElement* f = fIt->next();
571 if ( f && f->GetType() == SMDSAbs_Face )
572 faces.push_back( f );
576 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
577 while ( fIt->more() )
578 faces.push_back( fIt->next() );
581 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
582 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
583 for ( ; fIt != faces.end(); ++fIt )
585 myElemPointIDs.push_back( TElemDef() );
586 TElemDef& elemPoints = myElemPointIDs.back();
587 int nbNodes = (*fIt)->NbCornerNodes();
588 for ( int i = 0;i < nbNodes; ++i )
590 const SMDS_MeshElement* node = (*fIt)->GetNode( i );
591 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
592 if ( nIdIt->second == -1 )
594 elemPoints.push_back( iPoint );
595 nIdIt->second = iPoint++;
598 elemPoints.push_back( (*nIdIt).second );
601 myPoints.resize( iPoint );
603 // project all nodes of 2d elements to theFace
604 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
605 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
607 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
608 TPoint * p = & myPoints[ (*nIdIt).second ];
609 p->myInitUV = project( node, projector );
610 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
612 // find key-points: the points most close to UV of vertices
613 TopExp_Explorer vExp( face, TopAbs_VERTEX );
614 set<int> foundIndices;
615 for ( ; vExp.More(); vExp.Next() ) {
616 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
617 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
618 double minDist = DBL_MAX;
620 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
621 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
622 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
623 if ( dist < minDist ) {
628 if ( foundIndices.insert( index ).second ) // unique?
629 myKeyPointIDs.push_back( index );
631 myIsBoundaryPointsFound = false;
636 // ---------------------------------------------------------------------
637 // The case where a pattern is being made from the mesh built by mesher
638 // ---------------------------------------------------------------------
640 // Load shapes in the consequent order and count nb of points
643 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
644 int nbV = myShapeIDMap.Extent();
645 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
646 bool added = ( nbV < myShapeIDMap.Extent() );
647 if ( !added ) { // vertex encountered twice
648 // a seam vertex have two corresponding key points
649 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
652 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
653 nbNodes += eSubMesh->NbNodes() + 1;
656 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
657 myShapeIDMap.Add( *elIt );
659 myShapeIDMap.Add( face );
661 myPoints.resize( nbNodes );
663 // Load U of points on edges
665 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
667 TopoDS_Edge & edge = *elIt;
668 list< TPoint* > & ePoints = getShapePoints( edge );
670 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
671 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
673 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
674 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
675 // to make adjacent edges share key-point, we make v2 FORWARD too
676 // (as we have different points for same shape with different orienation)
679 // on closed face we must have REVERSED some of seam vertices
681 if ( helper.IsSeamShape( edge ) ) {
682 if ( helper.IsRealSeam( edge ) && !isForward ) {
683 // reverse on reversed SEAM edge
688 else { // on CLOSED edge (i.e. having one vertex with different orienations)
689 for ( int is2 = 0; is2 < 2; ++is2 ) {
690 TopoDS_Shape & v = is2 ? v2 : v1;
691 if ( helper.IsRealSeam( v ) ) {
692 // reverse or not depending on orientation of adjacent seam
694 list<TopoDS_Edge>::iterator eIt2 = elIt;
696 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
698 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
699 if ( seam.Orientation() == TopAbs_REVERSED )
706 // the forward key-point
707 list< TPoint* > * vPoint = & getShapePoints( v1 );
708 if ( vPoint->empty() )
710 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
711 if ( vSubMesh && vSubMesh->NbNodes() ) {
712 myKeyPointIDs.push_back( iPoint );
713 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
714 const SMDS_MeshNode* node = nIt->next();
715 if ( v1.Orientation() == TopAbs_REVERSED )
716 closeNodePointIDMap.insert( make_pair( node, iPoint ));
718 nodePointIDMap.insert( make_pair( node, iPoint ));
720 TPoint* keyPoint = &myPoints[ iPoint++ ];
721 vPoint->push_back( keyPoint );
723 keyPoint->myInitUV = project( node, projector );
725 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
726 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
729 if ( !vPoint->empty() )
730 ePoints.push_back( vPoint->front() );
733 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
734 if ( eSubMesh && eSubMesh->NbNodes() )
736 // loop on nodes of an edge: sort them by param on edge
737 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
738 TParamNodeMap paramNodeMap;
739 int nbMeduimNodes = 0;
740 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
741 while ( nIt->more() )
743 const SMDS_MeshNode* node = nIt->next();
744 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
748 const SMDS_EdgePosition* epos =
749 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
750 double u = epos->GetUParameter();
751 paramNodeMap.insert( make_pair( u, node ));
753 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
754 // wrong U on edge, project
756 BRepAdaptor_Curve aCurve( edge );
757 proj.Initialize( aCurve, f, l );
758 paramNodeMap.clear();
759 nIt = eSubMesh->GetNodes();
760 for ( int iNode = 0; nIt->more(); ++iNode ) {
761 const SMDS_MeshNode* node = nIt->next();
762 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
764 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
766 if ( proj.IsDone() ) {
767 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
768 if ( proj.IsMin( i )) {
769 u = proj.Point( i ).Parameter();
773 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
775 paramNodeMap.insert( make_pair( u, node ));
778 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
779 if ( paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
780 return setErrorCode(ERR_UNEXPECTED);
783 // put U in [0,1] so that the first key-point has U==0
784 bool isSeam = helper.IsRealSeam( edge );
786 TParamNodeMap::iterator unIt = paramNodeMap.begin();
787 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
788 while ( unIt != paramNodeMap.end() )
790 TPoint* p = & myPoints[ iPoint ];
791 ePoints.push_back( p );
792 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
793 if ( isSeam && !isForward )
794 closeNodePointIDMap.insert( make_pair( node, iPoint ));
796 nodePointIDMap.insert ( make_pair( node, iPoint ));
799 p->myInitUV = project( node, projector );
801 double u = isForward ? (*unIt).first : (*unRIt).first;
802 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
803 p->myInitUV = C2d->Value( u ).XY();
805 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
810 // the reverse key-point
811 vPoint = & getShapePoints( v2 );
812 if ( vPoint->empty() )
814 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
815 if ( vSubMesh && vSubMesh->NbNodes() ) {
816 myKeyPointIDs.push_back( iPoint );
817 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
818 const SMDS_MeshNode* node = nIt->next();
819 if ( v2.Orientation() == TopAbs_REVERSED )
820 closeNodePointIDMap.insert( make_pair( node, iPoint ));
822 nodePointIDMap.insert( make_pair( node, iPoint ));
824 TPoint* keyPoint = &myPoints[ iPoint++ ];
825 vPoint->push_back( keyPoint );
827 keyPoint->myInitUV = project( node, projector );
829 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
830 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
833 if ( !vPoint->empty() )
834 ePoints.push_back( vPoint->front() );
836 // compute U of edge-points
839 double totalDist = 0;
840 list< TPoint* >::iterator pIt = ePoints.begin();
841 TPoint* prevP = *pIt;
842 prevP->myInitU = totalDist;
843 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
845 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
846 p->myInitU = totalDist;
849 if ( totalDist > DBL_MIN)
850 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
852 p->myInitU /= totalDist;
855 } // loop on edges of a wire
857 // Load in-face points and elements
859 if ( fSubMesh && fSubMesh->NbElements() )
861 list< TPoint* > & fPoints = getShapePoints( face );
862 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
863 while ( nIt->more() )
865 const SMDS_MeshNode* node = nIt->next();
866 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
868 nodePointIDMap.insert( make_pair( node, iPoint ));
869 TPoint* p = &myPoints[ iPoint++ ];
870 fPoints.push_back( p );
872 p->myInitUV = project( node, projector );
874 const SMDS_FacePosition* pos =
875 static_cast<const SMDS_FacePosition*>(node->GetPosition());
876 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
878 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
881 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
882 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
883 while ( elemIt->more() )
885 const SMDS_MeshElement* elem = elemIt->next();
886 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
887 myElemPointIDs.push_back( TElemDef() );
888 TElemDef& elemPoints = myElemPointIDs.back();
889 // find point indices corresponding to element nodes
890 while ( nIt->more() )
892 const SMDS_MeshNode* node = smdsNode( nIt->next() );
893 n_id = nodePointIDMap.find( node );
894 if ( n_id == nodePointIDMap.end() )
895 continue; // medium node
896 iPoint = n_id->second; // point index of interest
897 // for a node on a seam edge there are two points
898 if ( helper.IsRealSeam( node->getshapeId() ) &&
899 ( n_id = closeNodePointIDMap.find( node )) != not_found )
901 TPoint & p1 = myPoints[ iPoint ];
902 TPoint & p2 = myPoints[ n_id->second ];
903 // Select point closest to the rest nodes of element in UV space
904 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
905 const SMDS_MeshNode* notSeamNode = 0;
906 // find node not on a seam edge
907 while ( nIt2->more() && !notSeamNode ) {
908 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
909 if ( !helper.IsSeamShape( n->getshapeId() ))
912 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
913 double dist1 = uv.SquareDistance( p1.myInitUV );
914 double dist2 = uv.SquareDistance( p2.myInitUV );
916 iPoint = n_id->second;
918 elemPoints.push_back( iPoint );
922 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
924 myIsBoundaryPointsFound = true;
927 // Assure that U range is proportional to V range
930 vector< TPoint >::iterator pVecIt = myPoints.begin();
931 for ( ; pVecIt != myPoints.end(); pVecIt++ )
932 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
933 double minU, minV, maxU, maxV;
934 bndBox.Get( minU, minV, maxU, maxV );
935 double dU = maxU - minU, dV = maxV - minV;
936 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
939 // define where is the problem, in the face or in the mesh
940 TopExp_Explorer vExp( face, TopAbs_VERTEX );
941 for ( ; vExp.More(); vExp.Next() ) {
942 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
945 bndBox.Get( minU, minV, maxU, maxV );
946 dU = maxU - minU, dV = maxV - minV;
947 if ( dU <= DBL_MIN || dV <= DBL_MIN )
949 return setErrorCode( ERR_LOADF_NARROW_FACE );
951 // mesh is projected onto a line, e.g.
952 return setErrorCode( ERR_LOADF_CANT_PROJECT );
954 double ratio = dU / dV, maxratio = 3, scale;
956 if ( ratio > maxratio ) {
957 scale = ratio / maxratio;
960 else if ( ratio < 1./maxratio ) {
961 scale = maxratio / ratio;
966 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
967 TPoint & p = *pVecIt;
968 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
969 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
972 if ( myElemPointIDs.empty() ) {
973 MESSAGE( "No elements bound to the face");
974 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
977 return setErrorCode( ERR_OK );
980 //=======================================================================
981 //function : computeUVOnEdge
982 //purpose : compute coordinates of points on theEdge
983 //=======================================================================
985 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
986 const list< TPoint* > & ePoints )
988 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
990 Handle(Geom2d_Curve) C2d =
991 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
993 ePoints.back()->myInitU = 1.0;
994 list< TPoint* >::const_iterator pIt = ePoints.begin();
995 for ( pIt++; pIt != ePoints.end(); pIt++ )
997 TPoint* point = *pIt;
999 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1000 point->myU = ( f * ( 1 - du ) + l * du );
1002 point->myUV = C2d->Value( point->myU ).XY();
1006 //=======================================================================
1007 //function : intersectIsolines
1009 //=======================================================================
1011 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1012 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1016 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1017 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1018 resUV = 0.5 * ( loc1 + loc2 );
1019 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1020 // SKL 26.07.2007 for NPAL16567
1021 double d1 = (uv11-uv12).Modulus();
1022 double d2 = (uv21-uv22).Modulus();
1023 // double delta = d1*d2*1e-6; PAL17233
1024 double delta = min( d1, d2 ) / 10.;
1025 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1027 // double len1 = ( uv11 - uv12 ).Modulus();
1028 // double len2 = ( uv21 - uv22 ).Modulus();
1029 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1033 // gp_Lin2d line1( uv11, uv12 - uv11 );
1034 // gp_Lin2d line2( uv21, uv22 - uv21 );
1035 // double angle = Abs( line1.Angle( line2 ) );
1037 // IntAna2d_AnaIntersection inter;
1038 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1039 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1041 // gp_Pnt2d interUV = inter.Point(1).Value();
1042 // resUV += interUV.XY();
1043 // inter.Perform( line1, line2 );
1044 // interUV = inter.Point(1).Value();
1045 // resUV += interUV.XY();
1050 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1051 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1056 //=======================================================================
1057 //function : compUVByIsoIntersection
1059 //=======================================================================
1061 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1062 const gp_XY& theInitUV,
1064 bool & theIsDeformed )
1066 // compute UV by intersection of 2 iso lines
1067 //gp_Lin2d isoLine[2];
1068 gp_XY uv1[2], uv2[2];
1070 const double zero = DBL_MIN;
1071 for ( int iIso = 0; iIso < 2; iIso++ )
1073 // to build an iso line:
1074 // find 2 pairs of consequent edge-points such that the range of their
1075 // initial parameters encloses the in-face point initial parameter
1076 gp_XY UV[2], initUV[2];
1077 int nbUV = 0, iCoord = iIso + 1;
1078 double initParam = theInitUV.Coord( iCoord );
1080 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1081 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1083 const list< TPoint* > & bndPoints = * bndIt;
1084 TPoint* prevP = bndPoints.back(); // this is the first point
1085 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1086 bool coincPrev = false;
1087 // loop on the edge-points
1088 for ( ; pIt != bndPoints.end(); pIt++ )
1090 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1091 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1092 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1093 if (!coincPrev && // ignore if initParam coincides with prev point param
1094 sumOfDiff > zero && // ignore if both points coincide with initParam
1095 prevParamDiff * paramDiff <= zero )
1097 // find UV in parametric space of theFace
1098 double r = Abs(prevParamDiff) / sumOfDiff;
1099 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1102 // throw away uv most distant from <theInitUV>
1103 gp_XY vec0 = initUV[0] - theInitUV;
1104 gp_XY vec1 = initUV[1] - theInitUV;
1105 gp_XY vec = uvInit - theInitUV;
1106 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1107 double dist0 = vec0.SquareModulus();
1108 double dist1 = vec1.SquareModulus();
1109 double dist = vec .SquareModulus();
1110 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1111 i = ( dist0 < dist1 ? 1 : 0 );
1112 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1113 i = 3; // theInitUV must remain between
1117 initUV[ i ] = uvInit;
1118 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1120 coincPrev = ( Abs(paramDiff) <= zero );
1127 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1128 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1129 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1130 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1132 // an iso line should be normal to UV[0] - UV[1] direction
1133 // and be located at the same relative distance as from initial ends
1134 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1136 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1137 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1138 //isoLine[ iIso ] = iso.Normal( isoLoc );
1139 uv1[ iIso ] = UV[0];
1140 uv2[ iIso ] = UV[1];
1143 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1144 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1145 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1146 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1153 // ==========================================================
1154 // structure representing a node of a grid of iso-poly-lines
1155 // ==========================================================
1162 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1163 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1164 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1165 TIsoNode(double initU, double initV):
1166 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1167 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1168 bool IsUVComputed() const
1169 { return myUV.X() != 1e100; }
1170 bool IsMovable() const
1171 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1172 void SetNotMovable()
1173 { myIsMovable = false; }
1174 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1175 { myBndNodes[ iDir + i * 2 ] = node; }
1176 TIsoNode* GetBoundaryNode(int iDir, int i)
1177 { return myBndNodes[ iDir + i * 2 ]; }
1178 void SetNext(TIsoNode* node, int iDir, int isForward)
1179 { myNext[ iDir + isForward * 2 ] = node; }
1180 TIsoNode* GetNext(int iDir, int isForward)
1181 { return myNext[ iDir + isForward * 2 ]; }
1184 //=======================================================================
1185 //function : getNextNode
1187 //=======================================================================
1189 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1191 TIsoNode* n = node->myNext[ dir ];
1192 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1193 n = 0;//node->myBndNodes[ dir ];
1194 // MESSAGE("getNextNode: use bnd for node "<<
1195 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1199 //=======================================================================
1200 //function : checkQuads
1201 //purpose : check if newUV destortes quadrangles around node,
1202 // and if ( crit == FIX_OLD ) fix newUV in this case
1203 //=======================================================================
1205 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1207 static bool checkQuads (const TIsoNode* node,
1209 const bool reversed,
1210 const int crit = FIX_OLD,
1211 double fixSize = 0.)
1213 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1214 int nbOldFix = 0, nbOldImpr = 0;
1215 double newBadRate = 0, oldBadRate = 0;
1216 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1217 int i, dir1 = 0, dir2 = 3;
1218 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1220 if ( dir2 > 3 ) dir2 = 0;
1222 // walking counterclockwise around a quad,
1223 // nodes are in the order: node, n[0], n[1], n[2]
1224 n[0] = getNextNode( node, dir1 );
1225 n[2] = getNextNode( node, dir2 );
1226 if ( !n[0] || !n[2] ) continue;
1227 n[1] = getNextNode( n[0], dir2 );
1228 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1229 bool isTriangle = ( !n[1] );
1231 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1233 // if ( fixSize != 0 ) {
1234 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1235 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1236 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1237 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1239 // check if a quadrangle is degenerated
1241 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1242 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1245 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1248 // find min size of the diagonal node-n[1]
1249 double minDiag = fixSize;
1250 if ( minDiag == 0. ) {
1251 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1252 if ( !isTriangle ) {
1253 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1254 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1256 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1257 minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1260 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1261 // ( behind means "to the right of")
1263 // 1. newUV is not behind 01 and 12 dirs
1264 // 2. or newUV is not behind 02 dir and n[2] is convex
1265 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1266 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1267 gp_Vec2d moveVec[3], outVec[3];
1268 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1270 bool isDiag = ( i == 2 );
1271 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1275 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1277 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1279 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1281 gp_Vec2d newDir( n[i]->myUV, newUV );
1282 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1284 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1285 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1286 if ( crit == FIX_OLD ) {
1287 wasIn[i] = ( outDir * oldDir < 0 );
1288 wasOk[i] = ( outDir * oldDir < -minDiag );
1290 newBadRate += outDir * newDir;
1292 oldBadRate += outDir * oldDir;
1295 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1296 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1297 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1298 moveVec[i] = ( oldDist - minDiag ) * outDir;
1303 // check if n[2] is convex
1306 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1308 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1309 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1310 newIsOk = ( newIsOk && isNewOk );
1311 newIsIn = ( newIsIn && isNewIn );
1313 if ( crit != FIX_OLD ) {
1314 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1315 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1319 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1320 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1321 oldIsIn = ( oldIsIn && isOldIn );
1322 oldIsOk = ( oldIsOk && isOldIn );
1325 if ( !isOldIn ) { // node is outside a quadrangle
1326 // move newUV inside a quadrangle
1327 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1328 // node and newUV are outside: push newUV inside
1330 if ( convex || isTriangle ) {
1331 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1334 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1335 double outSize = out.Magnitude();
1336 if ( outSize > DBL_MIN )
1339 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1340 uv = n[1]->myUV - minDiag * out.XY();
1342 oldUVFixed[ nbOldFix++ ] = uv;
1343 //node->myUV = newUV;
1345 else if ( !isOldOk ) {
1346 // try to fix old UV: move node inside as less as possible
1347 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1348 gp_XY uv1, uv2 = node->myUV;
1349 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1351 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1352 while ( !isOldOk ) {
1353 // find the least moveVec
1355 double minMove2 = 1e100;
1356 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1358 if ( moveVec[i].Coord(1) < 1e100 ) {
1359 double move2 = moveVec[i].SquareMagnitude();
1360 if ( move2 < minMove2 ) {
1369 // move node to newUV
1370 uv1 = node->myUV + moveVec[ iMin ].XY();
1371 uv2 += moveVec[ iMin ].XY();
1372 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1373 // check if uv1 is ok
1374 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1375 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1376 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1378 oldUVImpr[ nbOldImpr++ ] = uv1;
1380 // check if uv2 is ok
1381 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1382 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1383 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1385 oldUVImpr[ nbOldImpr++ ] = uv2;
1390 } // loop on 4 quadrangles around <node>
1392 if ( crit == CHECK_NEW_OK )
1394 if ( crit == CHECK_NEW_IN )
1403 if ( oldIsIn && nbOldImpr ) {
1404 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1405 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1406 gp_XY uv = oldUVImpr[ 0 ];
1407 for ( int i = 1; i < nbOldImpr; i++ )
1408 uv += oldUVImpr[ i ];
1410 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1415 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1418 if ( !oldIsIn && nbOldFix ) {
1419 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1420 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1421 gp_XY uv = oldUVFixed[ 0 ];
1422 for ( int i = 1; i < nbOldFix; i++ )
1423 uv += oldUVFixed[ i ];
1425 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1430 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1433 if ( newIsIn && oldIsIn )
1434 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1435 else if ( !newIsIn )
1442 //=======================================================================
1443 //function : compUVByElasticIsolines
1444 //purpose : compute UV as nodes of iso-poly-lines consisting of
1445 // segments keeping relative size as in the pattern
1446 //=======================================================================
1447 //#define DEB_COMPUVBYELASTICISOLINES
1448 bool SMESH_Pattern::
1449 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1450 const list< TPoint* >& thePntToCompute)
1452 return false; // PAL17233
1453 //cout << "============================== KEY POINTS =============================="<<endl;
1454 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1455 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1456 // TPoint& p = myPoints[ *kpIt ];
1457 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1458 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1460 //cout << "=============================="<<endl;
1462 // Define parameters of iso-grid nodes in U and V dir
1464 set< double > paramSet[ 2 ];
1465 list< list< TPoint* > >::const_iterator pListIt;
1466 list< TPoint* >::const_iterator pIt;
1467 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1468 const list< TPoint* > & pList = * pListIt;
1469 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1470 paramSet[0].insert( (*pIt)->myInitUV.X() );
1471 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1474 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1475 paramSet[0].insert( (*pIt)->myInitUV.X() );
1476 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1478 // unite close parameters and split too long segments
1481 for ( iDir = 0; iDir < 2; iDir++ )
1483 set< double > & params = paramSet[ iDir ];
1484 double range = ( *params.rbegin() - *params.begin() );
1485 double toler = range / 1e6;
1486 tol[ iDir ] = toler;
1487 // double maxSegment = range / params.size() / 2.;
1489 // set< double >::iterator parIt = params.begin();
1490 // double prevPar = *parIt;
1491 // for ( parIt++; parIt != params.end(); parIt++ )
1493 // double segLen = (*parIt) - prevPar;
1494 // if ( segLen < toler )
1495 // ;//params.erase( prevPar ); // unite
1496 // else if ( segLen > maxSegment )
1497 // params.insert( prevPar + 0.5 * segLen ); // split
1498 // prevPar = (*parIt);
1502 // Make nodes of a grid of iso-poly-lines
1504 list < TIsoNode > nodes;
1505 typedef list < TIsoNode *> TIsoLine;
1506 map < double, TIsoLine > isoMap[ 2 ];
1508 set< double > & params0 = paramSet[ 0 ];
1509 set< double >::iterator par0It = params0.begin();
1510 for ( ; par0It != params0.end(); par0It++ )
1512 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1513 set< double > & params1 = paramSet[ 1 ];
1514 set< double >::iterator par1It = params1.begin();
1515 for ( ; par1It != params1.end(); par1It++ )
1517 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1518 isoLine0.push_back( & nodes.back() );
1519 isoMap[1][ *par1It ].push_back( & nodes.back() );
1523 // Compute intersections of boundaries with iso-lines:
1524 // only boundary nodes will have computed UV so far
1527 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1528 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1529 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1531 const list< TPoint* > & bndPoints = * bndIt;
1532 TPoint* prevP = bndPoints.back(); // this is the first point
1533 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1534 // loop on the edge-points
1535 for ( ; pIt != bndPoints.end(); pIt++ )
1537 TPoint* point = *pIt;
1538 for ( iDir = 0; iDir < 2; iDir++ )
1540 const int iCoord = iDir + 1;
1541 const int iOtherCoord = 2 - iDir;
1542 double par1 = prevP->myInitUV.Coord( iCoord );
1543 double par2 = point->myInitUV.Coord( iCoord );
1544 double parDif = par2 - par1;
1545 if ( Abs( parDif ) <= DBL_MIN )
1547 // find iso-lines intersecting a bounadry
1548 double toler = tol[ 1 - iDir ];
1549 double minPar = Min ( par1, par2 );
1550 double maxPar = Max ( par1, par2 );
1551 map < double, TIsoLine >& isos = isoMap[ iDir ];
1552 map < double, TIsoLine >::iterator isoIt = isos.begin();
1553 for ( ; isoIt != isos.end(); isoIt++ )
1555 double isoParam = (*isoIt).first;
1556 if ( isoParam < minPar || isoParam > maxPar )
1558 double r = ( isoParam - par1 ) / parDif;
1559 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1560 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1561 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1562 // find existing node with otherPar or insert a new one
1563 TIsoLine & isoLine = (*isoIt).second;
1565 TIsoLine::iterator nIt = isoLine.begin();
1566 for ( ; nIt != isoLine.end(); nIt++ ) {
1567 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1568 if ( nodePar >= otherPar )
1572 if ( Abs( nodePar - otherPar ) <= toler )
1573 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1575 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1576 node = & nodes.back();
1577 isoLine.insert( nIt, node );
1579 node->SetNotMovable();
1581 uvBnd.Add( gp_Pnt2d( uv ));
1582 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1584 gp_XY tgt( point->myUV - prevP->myUV );
1585 if ( ::IsEqual( r, 1. ))
1586 node->myDir[ 0 ] = tgt;
1587 else if ( ::IsEqual( r, 0. ))
1588 node->myDir[ 1 ] = tgt;
1590 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1591 // keep boundary nodes corresponding to boundary points
1592 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1593 if ( bndNodes.empty() || bndNodes.back() != node )
1594 bndNodes.push_back( node );
1595 } // loop on isolines
1596 } // loop on 2 directions
1598 } // loop on boundary points
1599 } // loop on boundaries
1601 // Define orientation
1603 // find the point with the least X
1604 double leastX = DBL_MAX;
1605 TIsoNode * leftNode;
1606 list < TIsoNode >::iterator nodeIt = nodes.begin();
1607 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1608 TIsoNode & node = *nodeIt;
1609 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1610 leastX = node.myUV.X();
1613 // if ( node.IsUVComputed() ) {
1614 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1615 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1616 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1617 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1620 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1621 //SCRUTE( reversed );
1623 // Prepare internal nodes:
1625 // 2. compute ratios
1626 // 3. find boundary nodes for each node
1627 // 4. remove nodes out of the boundary
1628 for ( iDir = 0; iDir < 2; iDir++ )
1630 const int iCoord = 2 - iDir; // coord changing along an isoline
1631 map < double, TIsoLine >& isos = isoMap[ iDir ];
1632 map < double, TIsoLine >::iterator isoIt = isos.begin();
1633 for ( ; isoIt != isos.end(); isoIt++ )
1635 TIsoLine & isoLine = (*isoIt).second;
1636 bool firstCompNodeFound = false;
1637 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1638 nPrevIt = nIt = nNextIt = isoLine.begin();
1640 nNextIt++; nNextIt++;
1641 while ( nIt != isoLine.end() )
1643 // 1. connect prev - cur
1644 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1645 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1646 firstCompNodeFound = true;
1647 lastCompNodePos = nPrevIt;
1649 if ( firstCompNodeFound ) {
1650 node->SetNext( prevNode, iDir, 0 );
1651 prevNode->SetNext( node, iDir, 1 );
1654 if ( nNextIt != isoLine.end() ) {
1655 double par1 = prevNode->myInitUV.Coord( iCoord );
1656 double par2 = node->myInitUV.Coord( iCoord );
1657 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1658 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1660 // 3. find boundary nodes
1661 if ( node->IsUVComputed() )
1662 lastCompNodePos = nIt;
1663 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1664 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1665 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1666 if ( (*nIt2)->IsUVComputed() )
1668 if ( nIt2 != isoLine.end() ) {
1670 node->SetBoundaryNode( bndNode1, iDir, 0 );
1671 node->SetBoundaryNode( bndNode2, iDir, 1 );
1672 // cout << "--------------------------------------------------"<<endl;
1673 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1674 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1675 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1676 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1677 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1678 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1681 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1682 node->SetBoundaryNode( 0, iDir, 0 );
1683 node->SetBoundaryNode( 0, iDir, 1 );
1687 if ( nNextIt != isoLine.end() ) nNextIt++;
1688 // 4. remove nodes out of the boundary
1689 if ( !firstCompNodeFound )
1690 isoLine.pop_front();
1691 } // loop on isoLine nodes
1693 // remove nodes after the boundary
1694 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1695 // (*nIt)->SetNotMovable();
1696 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1697 } // loop on isolines
1698 } // loop on 2 directions
1700 // Compute local isoline direction for internal nodes
1703 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1704 map < double, TIsoLine >::iterator isoIt = isos.begin();
1705 for ( ; isoIt != isos.end(); isoIt++ )
1707 TIsoLine & isoLine = (*isoIt).second;
1708 TIsoLine::iterator nIt = isoLine.begin();
1709 for ( ; nIt != isoLine.end(); nIt++ )
1711 TIsoNode* node = *nIt;
1712 if ( node->IsUVComputed() || !node->IsMovable() )
1714 gp_Vec2d aTgt[2], aNorm[2];
1717 for ( iDir = 0; iDir < 2; iDir++ )
1719 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1720 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1721 if ( !bndNode1 || !bndNode2 ) {
1725 const int iCoord = 2 - iDir; // coord changing along an isoline
1726 double par1 = bndNode1->myInitUV.Coord( iCoord );
1727 double par2 = node->myInitUV.Coord( iCoord );
1728 double par3 = bndNode2->myInitUV.Coord( iCoord );
1729 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1731 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1732 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1733 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1734 else tgt1.Reverse();
1735 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1737 if ( ratio[ iDir ] < 0.5 )
1738 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1740 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1742 aNorm[ iDir ].Reverse(); // along iDir isoline
1744 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1745 // maybe angle is more than |PI|
1746 if ( Abs( angle ) > PI / 2. ) {
1747 // check direction of the last but one perpendicular isoline
1748 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1749 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1750 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1751 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1752 if ( isoDir * tgt2 < 0 )
1754 double angle2 = tgt1.Angle( isoDir );
1755 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1756 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1757 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1758 //MESSAGE("REVERSE ANGLE");
1761 if ( Abs( angle2 ) > Abs( angle ) ||
1762 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1763 //MESSAGE("Add PI");
1764 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1765 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1766 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1767 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1768 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1769 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1772 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1776 for ( iDir = 0; iDir < 2; iDir++ )
1778 aTgt[iDir].Normalize();
1779 aNorm[1-iDir].Normalize();
1780 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1783 node->myDir[iDir] = //aTgt[iDir];
1784 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1786 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1787 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1788 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1789 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1791 } // loop on iso nodes
1792 } // loop on isolines
1794 // Find nodes to start computing UV from
1796 list< TIsoNode* > startNodes;
1797 list< TIsoNode* >::iterator nIt = bndNodes.end();
1798 TIsoNode* node = *(--nIt);
1799 TIsoNode* prevNode = *(--nIt);
1800 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1802 TIsoNode* nextNode = *nIt;
1803 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1804 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1805 double initAngle = initTgt1.Angle( initTgt2 );
1806 double angle = node->myDir[0].Angle( node->myDir[1] );
1807 if ( reversed ) angle = -angle;
1808 if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1809 // find a close internal node
1810 TIsoNode* nClose = 0;
1811 list< TIsoNode* > testNodes;
1812 testNodes.push_back( node );
1813 list< TIsoNode* >::iterator it = testNodes.begin();
1814 for ( ; !nClose && it != testNodes.end(); it++ )
1816 for (int i = 0; i < 4; i++ )
1818 nClose = (*it)->myNext[ i ];
1820 if ( !nClose->IsUVComputed() )
1823 testNodes.push_back( nClose );
1829 startNodes.push_back( nClose );
1830 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1831 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1832 // "initAngle: " << initAngle << " angle: " << angle << endl;
1833 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1834 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1835 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1836 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1842 // Compute starting UV of internal nodes
1844 list < TIsoNode* > internNodes;
1845 bool needIteration = true;
1846 if ( startNodes.empty() ) {
1847 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1848 needIteration = false;
1849 map < double, TIsoLine >& isos = isoMap[ 0 ];
1850 map < double, TIsoLine >::iterator isoIt = isos.begin();
1851 for ( ; isoIt != isos.end(); isoIt++ )
1853 TIsoLine & isoLine = (*isoIt).second;
1854 TIsoLine::iterator nIt = isoLine.begin();
1855 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1857 TIsoNode* node = *nIt;
1858 if ( !node->IsUVComputed() && node->IsMovable() ) {
1859 internNodes.push_back( node );
1861 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1862 node->myUV, needIteration ))
1863 node->myUV = node->myInitUV;
1867 if ( needIteration )
1868 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1870 TIsoNode* node = *nIt, *nClose = 0;
1871 list< TIsoNode* > testNodes;
1872 testNodes.push_back( node );
1873 list< TIsoNode* >::iterator it = testNodes.begin();
1874 for ( ; !nClose && it != testNodes.end(); it++ )
1876 for (int i = 0; i < 4; i++ )
1878 nClose = (*it)->myNext[ i ];
1880 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1883 testNodes.push_back( nClose );
1889 startNodes.push_back( nClose );
1893 double aMin[2], aMax[2], step[2];
1894 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1895 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1896 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1897 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1898 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1900 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1902 TIsoNode* prevN[2], *node = *nIt;
1903 if ( node->IsUVComputed() || !node->IsMovable() )
1905 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1906 int nbComp = 0, nbPrev = 0;
1907 for ( iDir = 0; iDir < 2; iDir++ )
1909 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1910 TIsoNode* n = node->GetNext( iDir, 0 );
1911 if ( n->IsUVComputed() )
1914 startNodes.push_back( n );
1915 n = node->GetNext( iDir, 1 );
1916 if ( n->IsUVComputed() )
1919 startNodes.push_back( n );
1921 prevNode1 = prevNode2;
1924 if ( prevNode1 ) nbPrev++;
1925 if ( prevNode2 ) nbPrev++;
1928 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1929 double par = node->myInitUV.Coord( 2 - iDir );
1930 bool isEnd = ( prevPar > par );
1931 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1932 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1933 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1935 MESSAGE("Why we are here?");
1938 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1939 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1940 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1941 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1942 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1943 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1944 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1945 //" par: " << prevPar << endl;
1946 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1947 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1949 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1950 gp_XY & uv1 = prevNode1->myUV;
1951 gp_XY & uv2 = prevNode2->myUV;
1952 // dir = ( uv2 - uv1 );
1953 // double len = dir.Modulus();
1954 // if ( len > DBL_MIN )
1955 // dir /= len * 0.5;
1956 double r = node->myRatio[ iDir ];
1957 newUV += uv1 * ( 1 - r ) + uv2 * r;
1960 newUV += prevNode1->myUV + dir * step[ iDir ];
1963 prevN[ iDir ] = prevNode1;
1967 if ( !nbComp ) continue;
1970 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1972 // check if a quadrangle is not distorted
1974 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1975 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1976 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1977 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1981 internNodes.push_back( node );
1986 static int maxNbIter = 100;
1987 #ifdef DEB_COMPUVBYELASTICISOLINES
1989 bool useNbMoveNode = 0;
1990 static int maxNbNodeMove = 100;
1993 if ( !useNbMoveNode )
1994 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1999 if ( !needIteration) break;
2000 #ifdef DEB_COMPUVBYELASTICISOLINES
2001 if ( nbIter >= maxNbIter ) break;
2004 list < TIsoNode* >::iterator nIt = internNodes.begin();
2005 for ( ; nIt != internNodes.end(); nIt++ ) {
2006 #ifdef DEB_COMPUVBYELASTICISOLINES
2008 cout << nbNodeMove <<" =================================================="<<endl;
2010 TIsoNode * node = *nIt;
2014 for ( iDir = 0; iDir < 2; iDir++ )
2016 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2017 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2018 double r = node->myRatio[ iDir ];
2019 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2020 // line[ iDir ].SetLocation( loc[ iDir ] );
2021 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2024 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2025 double locR[2] = { 0, 0 };
2026 for ( iDir = 0; iDir < 2; iDir++ )
2028 const int iCoord = 2 - iDir; // coord changing along an isoline
2029 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2030 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2031 if ( !bndNode1 || !bndNode2 ) {
2034 double par1 = bndNode1->myInitUV.Coord( iCoord );
2035 double par2 = node->myInitUV.Coord( iCoord );
2036 double par3 = bndNode2->myInitUV.Coord( iCoord );
2037 double r = ( par2 - par1 ) / ( par3 - par1 );
2038 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2039 locR[ iDir ] = ( 1 - r * r ) * 0.25;
2041 //locR[0] = locR[1] = 0.25;
2042 // intersect the 2 lines and move a node
2043 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2044 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2046 // double intR = 1 - locR[0] - locR[1];
2047 // gp_XY newUV = inter.Point(1).Value().XY();
2048 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2049 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2051 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2052 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2053 // avoid parallel isolines intersection
2054 checkQuads( node, newUV, reversed );
2056 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2058 } // intersection found
2059 #ifdef DEB_COMPUVBYELASTICISOLINES
2060 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2062 } // loop on internal nodes
2063 #ifdef DEB_COMPUVBYELASTICISOLINES
2064 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2066 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2068 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2070 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2071 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2072 #ifndef DEB_COMPUVBYELASTICISOLINES
2077 // Set computed UV to points
2079 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2080 TPoint* point = *pIt;
2081 //gp_XY oldUV = point->myUV;
2082 double minDist = DBL_MAX;
2083 list < TIsoNode >::iterator nIt = nodes.begin();
2084 for ( ; nIt != nodes.end(); nIt++ ) {
2085 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2086 if ( dist < minDist ) {
2088 point->myUV = (*nIt).myUV;
2097 //=======================================================================
2098 //function : setFirstEdge
2099 //purpose : choose the best first edge of theWire; return the summary distance
2100 // between point UV computed by isolines intersection and
2101 // eventual UV got from edge p-curves
2102 //=======================================================================
2104 //#define DBG_SETFIRSTEDGE
2105 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2107 int iE, nbEdges = theWire.size();
2111 // Transform UVs computed by iso to fit bnd box of a wire
2113 // max nb of points on an edge
2115 int eID = theFirstEdgeID;
2116 for ( iE = 0; iE < nbEdges; iE++ )
2117 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2119 // compute bnd boxes
2120 TopoDS_Face face = TopoDS::Face( myShape );
2121 Bnd_Box2d bndBox, eBndBox;
2122 eID = theFirstEdgeID;
2123 list< TopoDS_Edge >::iterator eIt;
2124 list< TPoint* >::iterator pIt;
2125 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2127 // UV by isos stored in TPoint.myXYZ
2128 list< TPoint* > & ePoints = getShapePoints( eID++ );
2129 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2131 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2133 // UV by an edge p-curve
2135 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2136 double dU = ( l - f ) / ( maxNbPnt - 1 );
2137 for ( int i = 0; i < maxNbPnt; i++ )
2138 eBndBox.Add( C2d->Value( f + i * dU ));
2141 // transform UVs by isos
2142 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2143 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2144 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2145 #ifdef DBG_SETFIRSTEDGE
2146 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2147 << eMinPar[1] << " - " << eMaxPar[1] );
2149 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2151 double dMin = eMinPar[i] - minPar[i];
2152 double dMax = eMaxPar[i] - maxPar[i];
2153 double dPar = maxPar[i] - minPar[i];
2154 eID = theFirstEdgeID;
2155 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2157 list< TPoint* > & ePoints = getShapePoints( eID++ );
2158 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2160 double par = (*pIt)->myXYZ.Coord( iC );
2161 double r = ( par - minPar[i] ) / dPar;
2162 par += ( 1 - r ) * dMin + r * dMax;
2163 (*pIt)->myXYZ.SetCoord( iC, par );
2169 double minDist = DBL_MAX;
2170 for ( iE = 0 ; iE < nbEdges; iE++ )
2172 #ifdef DBG_SETFIRSTEDGE
2173 MESSAGE ( " VARIANT " << iE );
2175 // evaluate the distance between UV computed by the 2 methods:
2176 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2178 int eID = theFirstEdgeID;
2179 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2181 list< TPoint* > & ePoints = getShapePoints( eID++ );
2182 computeUVOnEdge( *eIt, ePoints );
2183 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2185 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2186 #ifdef DBG_SETFIRSTEDGE
2187 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2188 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2192 #ifdef DBG_SETFIRSTEDGE
2193 MESSAGE ( "dist -- " << dist );
2195 if ( dist < minDist ) {
2197 eBest = theWire.front();
2199 // check variant with another first edge
2200 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2202 // put the best first edge to the theWire front
2203 if ( eBest != theWire.front() ) {
2204 eIt = find ( theWire.begin(), theWire.end(), eBest );
2205 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2211 //=======================================================================
2212 //function : sortSameSizeWires
2213 //purpose : sort wires in theWireList from theFromWire until theToWire,
2214 // the wires are set in the order to correspond to the order
2215 // of boundaries; after sorting, edges in the wires are put
2216 // in a good order, point UVs on edges are computed and points
2217 // are appended to theEdgesPointsList
2218 //=======================================================================
2220 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2221 const TListOfEdgesList::iterator& theFromWire,
2222 const TListOfEdgesList::iterator& theToWire,
2223 const int theFirstEdgeID,
2224 list< list< TPoint* > >& theEdgesPointsList )
2226 TopoDS_Face F = TopoDS::Face( myShape );
2227 int iW, nbWires = 0;
2228 TListOfEdgesList::iterator wlIt = theFromWire;
2229 while ( wlIt++ != theToWire )
2232 // Recompute key-point UVs by isolines intersection,
2233 // compute CG of key-points for each wire and bnd boxes of GCs
2236 gp_XY orig( gp::Origin2d().XY() );
2237 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2238 Bnd_Box2d bndBox, vBndBox;
2239 int eID = theFirstEdgeID;
2240 list< TopoDS_Edge >::iterator eIt;
2241 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2243 list< TopoDS_Edge > & wire = *wlIt;
2244 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2246 list< TPoint* > & ePoints = getShapePoints( eID++ );
2247 TPoint* p = ePoints.front();
2248 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2249 MESSAGE("cant sortSameSizeWires()");
2252 gcVec[iW] += p->myUV;
2253 bndBox.Add( gp_Pnt2d( p->myUV ));
2254 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2255 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2256 vGcVec[iW] += vXY.XY();
2258 // keep the computed UV to compare against by setFirstEdge()
2259 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2261 gcVec[iW] /= nbWires;
2262 vGcVec[iW] /= nbWires;
2263 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2264 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2267 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2269 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2270 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2271 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2272 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2274 double dMin = vMinPar[i] - minPar[i];
2275 double dMax = vMaxPar[i] - maxPar[i];
2276 double dPar = maxPar[i] - minPar[i];
2277 if ( Abs( dPar ) <= DBL_MIN )
2279 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2280 double par = gcVec[iW].Coord( iC );
2281 double r = ( par - minPar[i] ) / dPar;
2282 par += ( 1 - r ) * dMin + r * dMax;
2283 gcVec[iW].SetCoord( iC, par );
2287 // Define boundary - wire correspondence by GC closeness
2289 TListOfEdgesList tmpWList;
2290 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2291 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2292 TIntWirePosMap bndIndWirePosMap;
2293 vector< bool > bndFound( nbWires, false );
2294 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2296 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2297 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2298 double minDist = DBL_MAX;
2299 gp_XY & wGc = vGcVec[ iW ];
2301 for ( int iB = 0; iB < nbWires; iB++ ) {
2302 if ( bndFound[ iB ] ) continue;
2303 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2304 if ( dist < minDist ) {
2309 bndFound[ bIndex ] = true;
2310 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2315 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2316 eID = theFirstEdgeID;
2317 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2319 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2320 list < TopoDS_Edge > & wire = ( *wirePos );
2322 // choose the best first edge of a wire
2323 setFirstEdge( wire, eID );
2325 // compute eventual UV and fill theEdgesPointsList
2326 theEdgesPointsList.push_back( list< TPoint* >() );
2327 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2328 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2330 list< TPoint* > & ePoints = getShapePoints( eID++ );
2331 computeUVOnEdge( *eIt, ePoints );
2332 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2334 // put wire back to theWireList
2336 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2342 //=======================================================================
2344 //purpose : Compute nodes coordinates applying
2345 // the loaded pattern to <theFace>. The first key-point
2346 // will be mapped into <theVertexOnKeyPoint1>
2347 //=======================================================================
2349 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2350 const TopoDS_Vertex& theVertexOnKeyPoint1,
2351 const bool theReverse)
2353 MESSAGE(" ::Apply(face) " );
2354 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2355 if ( !setShapeToMesh( face ))
2358 // find points on edges, it fills myNbKeyPntInBoundary
2359 if ( !findBoundaryPoints() )
2362 // Define the edges order so that the first edge starts at
2363 // theVertexOnKeyPoint1
2365 list< TopoDS_Edge > eList;
2366 list< int > nbVertexInWires;
2367 int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2368 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2370 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2371 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2373 // check nb wires and edges
2374 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2375 l1.sort(); l2.sort();
2378 MESSAGE( "Wrong nb vertices in wires" );
2379 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2382 // here shapes get IDs, for the outer wire IDs are OK
2383 list<TopoDS_Edge>::iterator elIt = eList.begin();
2384 for ( ; elIt != eList.end(); elIt++ ) {
2385 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2386 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2387 // BEGIN: jfa for bug 0019943
2390 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2391 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2393 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2394 if (we.Current().IsSame(*elIt)) {
2396 if (nbe == 2) isClosed1 = true;
2401 // END: jfa for bug 0019943
2403 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2405 int nbVertices = myShapeIDMap.Extent();
2407 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2408 myShapeIDMap.Add( *elIt );
2410 myShapeIDMap.Add( face );
2412 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2413 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2414 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2417 // points on edges to be used for UV computation of in-face points
2418 list< list< TPoint* > > edgesPointsList;
2419 edgesPointsList.push_back( list< TPoint* >() );
2420 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2421 list< TPoint* >::iterator pIt;
2423 // compute UV of points on the outer wire
2424 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2425 for (iE = 0, elIt = eList.begin();
2426 iE < nbEdgesInOuterWire && elIt != eList.end();
2429 list< TPoint* > & ePoints = getShapePoints( *elIt );
2431 computeUVOnEdge( *elIt, ePoints );
2432 // collect on-edge points (excluding the last one)
2433 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2436 // If there are several wires, define the order of edges of inner wires:
2437 // compute UV of inner edge-points using 2 methods: the one for in-face points
2438 // and the one for on-edge points and then choose the best edge order
2439 // by the best correspondance of the 2 results
2442 // compute UV of inner edge-points using the method for in-face points
2443 // and devide eList into a list of separate wires
2445 list< list< TopoDS_Edge > > wireList;
2446 list<TopoDS_Edge>::iterator eIt = elIt;
2447 list<int>::iterator nbEIt = nbVertexInWires.begin();
2448 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2450 int nbEdges = *nbEIt;
2451 wireList.push_back( list< TopoDS_Edge >() );
2452 list< TopoDS_Edge > & wire = wireList.back();
2453 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2455 list< TPoint* > & ePoints = getShapePoints( *eIt );
2456 pIt = ePoints.begin();
2457 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2459 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2460 MESSAGE("cant Apply(face)");
2463 // keep the computed UV to compare against by setFirstEdge()
2464 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2466 wire.push_back( *eIt );
2469 // remove inner edges from eList
2470 eList.erase( elIt, eList.end() );
2472 // sort wireList by nb edges in a wire
2473 sortBySize< TopoDS_Edge > ( wireList );
2475 // an ID of the first edge of a boundary
2476 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2477 // if ( nbSeamShapes > 0 )
2478 // id1 += 2; // 2 vertices more
2480 // find points - edge correspondence for wires of unique size,
2481 // edge order within a wire should be defined only
2483 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2484 while ( wlIt != wireList.end() )
2486 list< TopoDS_Edge >& wire = (*wlIt);
2487 int nbEdges = wire.size();
2489 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2491 // choose the best first edge of a wire
2492 setFirstEdge( wire, id1 );
2494 // compute eventual UV and collect on-edge points
2495 edgesPointsList.push_back( list< TPoint* >() );
2496 edgesPoints = & edgesPointsList.back();
2498 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2500 list< TPoint* > & ePoints = getShapePoints( eID++ );
2501 computeUVOnEdge( *eIt, ePoints );
2502 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2508 // find boundary - wire correspondence for several wires of same size
2510 id1 = nbVertices + nbEdgesInOuterWire + 1;
2511 wlIt = wireList.begin();
2512 while ( wlIt != wireList.end() )
2514 int nbSameSize = 0, nbEdges = (*wlIt).size();
2515 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2517 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2521 if ( nbSameSize > 0 )
2522 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2525 id1 += nbEdges * ( nbSameSize + 1 );
2528 // add well-ordered edges to eList
2530 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2532 list< TopoDS_Edge >& wire = (*wlIt);
2533 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2536 // re-fill myShapeIDMap - all shapes get good IDs
2538 myShapeIDMap.Clear();
2539 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2540 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2541 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2542 myShapeIDMap.Add( *elIt );
2543 myShapeIDMap.Add( face );
2545 } // there are inner wires
2547 // Compute XYZ of on-edge points
2549 TopLoc_Location loc;
2550 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2552 BRepAdaptor_Curve C3d( *elIt );
2553 list< TPoint* > & ePoints = getShapePoints( iE++ );
2554 pIt = ePoints.begin();
2555 for ( pIt++; pIt != ePoints.end(); pIt++ )
2557 TPoint* point = *pIt;
2558 point->myXYZ = C3d.Value( point->myU );
2562 // Compute UV and XYZ of in-face points
2564 // try to use a simple algo
2565 list< TPoint* > & fPoints = getShapePoints( face );
2566 bool isDeformed = false;
2567 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2568 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2569 (*pIt)->myUV, isDeformed )) {
2570 MESSAGE("cant Apply(face)");
2573 // try to use a complex algo if it is a difficult case
2574 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2576 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2577 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2578 (*pIt)->myUV, isDeformed )) {
2579 MESSAGE("cant Apply(face)");
2584 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2585 const gp_Trsf & aTrsf = loc.Transformation();
2586 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2588 TPoint * point = *pIt;
2589 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2590 if ( !loc.IsIdentity() )
2591 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2594 myIsComputed = true;
2596 return setErrorCode( ERR_OK );
2599 //=======================================================================
2601 //purpose : Compute nodes coordinates applying
2602 // the loaded pattern to <theFace>. The first key-point
2603 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2604 //=======================================================================
2606 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2607 const int theNodeIndexOnKeyPoint1,
2608 const bool theReverse)
2610 // MESSAGE(" ::Apply(MeshFace) " );
2612 if ( !IsLoaded() ) {
2613 MESSAGE( "Pattern not loaded" );
2614 return setErrorCode( ERR_APPL_NOT_LOADED );
2617 // check nb of nodes
2618 const int nbFaceNodes = theFace->NbCornerNodes();
2619 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2620 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2621 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2624 // find points on edges, it fills myNbKeyPntInBoundary
2625 if ( !findBoundaryPoints() )
2628 // check that there are no holes in a pattern
2629 if (myNbKeyPntInBoundary.size() > 1 ) {
2630 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2633 // Define the nodes order
2635 list< const SMDS_MeshNode* > nodes;
2636 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2637 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2639 while ( noIt->more() && iSub < nbFaceNodes ) {
2640 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2641 nodes.push_back( node );
2642 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2645 if ( n != nodes.end() ) {
2647 if ( n != --nodes.end() )
2648 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2651 else if ( n != nodes.begin() )
2652 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2654 list< gp_XYZ > xyzList;
2655 myOrderedNodes.resize( nbFaceNodes );
2656 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2657 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2658 myOrderedNodes[ iSub++] = *n;
2661 // Define a face plane
2663 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2664 gp_Pnt P ( *xyzIt++ );
2665 gp_Vec Vx( P, *xyzIt++ ), N;
2667 N = Vx ^ gp_Vec( P, *xyzIt++ );
2668 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2669 if ( N.SquareMagnitude() <= DBL_MIN )
2670 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2671 gp_Ax2 pos( P, N, Vx );
2673 // Compute UV of key-points on a plane
2674 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2676 gp_Vec vec ( pos.Location(), *xyzIt );
2677 TPoint* p = getShapePoints( iSub ).front();
2678 p->myUV.SetX( vec * pos.XDirection() );
2679 p->myUV.SetY( vec * pos.YDirection() );
2683 // points on edges to be used for UV computation of in-face points
2684 list< list< TPoint* > > edgesPointsList;
2685 edgesPointsList.push_back( list< TPoint* >() );
2686 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2687 list< TPoint* >::iterator pIt;
2689 // compute UV and XYZ of points on edges
2691 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2693 gp_XYZ& xyz1 = *xyzIt++;
2694 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2696 list< TPoint* > & ePoints = getShapePoints( iSub );
2697 ePoints.back()->myInitU = 1.0;
2698 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2699 while ( *pIt != ePoints.back() )
2702 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2703 gp_Vec vec ( pos.Location(), p->myXYZ );
2704 p->myUV.SetX( vec * pos.XDirection() );
2705 p->myUV.SetY( vec * pos.YDirection() );
2707 // collect on-edge points (excluding the last one)
2708 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2711 // Compute UV and XYZ of in-face points
2713 // try to use a simple algo to compute UV
2714 list< TPoint* > & fPoints = getShapePoints( iSub );
2715 bool isDeformed = false;
2716 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2717 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2718 (*pIt)->myUV, isDeformed )) {
2719 MESSAGE("cant Apply(face)");
2722 // try to use a complex algo if it is a difficult case
2723 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2725 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2726 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2727 (*pIt)->myUV, isDeformed )) {
2728 MESSAGE("cant Apply(face)");
2733 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2735 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2738 myIsComputed = true;
2740 return setErrorCode( ERR_OK );
2743 //=======================================================================
2745 //purpose : Compute nodes coordinates applying
2746 // the loaded pattern to <theFace>. The first key-point
2747 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2748 //=======================================================================
2750 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2751 const SMDS_MeshFace* theFace,
2752 const TopoDS_Shape& theSurface,
2753 const int theNodeIndexOnKeyPoint1,
2754 const bool theReverse)
2756 // MESSAGE(" ::Apply(MeshFace) " );
2757 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2758 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2760 const TopoDS_Face& face = TopoDS::Face( theSurface );
2761 TopLoc_Location loc;
2762 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2763 const gp_Trsf & aTrsf = loc.Transformation();
2765 if ( !IsLoaded() ) {
2766 MESSAGE( "Pattern not loaded" );
2767 return setErrorCode( ERR_APPL_NOT_LOADED );
2770 // check nb of nodes
2771 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2772 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2773 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2776 // find points on edges, it fills myNbKeyPntInBoundary
2777 if ( !findBoundaryPoints() )
2780 // check that there are no holes in a pattern
2781 if (myNbKeyPntInBoundary.size() > 1 ) {
2782 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2785 // Define the nodes order
2787 list< const SMDS_MeshNode* > nodes;
2788 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2789 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2791 while ( noIt->more() ) {
2792 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2793 nodes.push_back( node );
2794 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2797 if ( n != nodes.end() ) {
2799 if ( n != --nodes.end() )
2800 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2803 else if ( n != nodes.begin() )
2804 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2807 // find a node not on a seam edge, if necessary
2808 SMESH_MesherHelper helper( *theMesh );
2809 helper.SetSubShape( theSurface );
2810 const SMDS_MeshNode* inFaceNode = 0;
2811 if ( helper.GetNodeUVneedInFaceNode() )
2813 SMESH_MeshEditor editor( theMesh );
2814 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2815 int shapeID = editor.FindShape( *n );
2817 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2818 if ( !helper.IsSeamShape( shapeID ))
2823 // Set UV of key-points (i.e. of nodes of theFace )
2824 vector< gp_XY > keyUV( theFace->NbNodes() );
2825 myOrderedNodes.resize( theFace->NbNodes() );
2826 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2828 TPoint* p = getShapePoints( iSub ).front();
2829 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2830 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2832 keyUV[ iSub-1 ] = p->myUV;
2833 myOrderedNodes[ iSub-1 ] = *n;
2836 // points on edges to be used for UV computation of in-face points
2837 list< list< TPoint* > > edgesPointsList;
2838 edgesPointsList.push_back( list< TPoint* >() );
2839 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2840 list< TPoint* >::iterator pIt;
2842 // compute UV and XYZ of points on edges
2844 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2846 gp_XY& uv1 = keyUV[ i ];
2847 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2849 list< TPoint* > & ePoints = getShapePoints( iSub );
2850 ePoints.back()->myInitU = 1.0;
2851 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2852 while ( *pIt != ePoints.back() )
2855 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2856 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2857 if ( !loc.IsIdentity() )
2858 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2860 // collect on-edge points (excluding the last one)
2861 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2864 // Compute UV and XYZ of in-face points
2866 // try to use a simple algo to compute UV
2867 list< TPoint* > & fPoints = getShapePoints( iSub );
2868 bool isDeformed = false;
2869 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2870 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2871 (*pIt)->myUV, isDeformed )) {
2872 MESSAGE("cant Apply(face)");
2875 // try to use a complex algo if it is a difficult case
2876 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2878 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2879 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2880 (*pIt)->myUV, isDeformed )) {
2881 MESSAGE("cant Apply(face)");
2886 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2888 TPoint * point = *pIt;
2889 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2890 if ( !loc.IsIdentity() )
2891 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2894 myIsComputed = true;
2896 return setErrorCode( ERR_OK );
2899 //=======================================================================
2900 //function : undefinedXYZ
2902 //=======================================================================
2904 static const gp_XYZ& undefinedXYZ()
2906 static gp_XYZ xyz( 1.e100, 0., 0. );
2910 //=======================================================================
2911 //function : isDefined
2913 //=======================================================================
2915 inline static bool isDefined(const gp_XYZ& theXYZ)
2917 return theXYZ.X() < 1.e100;
2920 //=======================================================================
2922 //purpose : Compute nodes coordinates applying
2923 // the loaded pattern to <theFaces>. The first key-point
2924 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2925 //=======================================================================
2927 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2928 std::set<const SMDS_MeshFace*>& theFaces,
2929 const int theNodeIndexOnKeyPoint1,
2930 const bool theReverse)
2932 MESSAGE(" ::Apply(set<MeshFace>) " );
2934 if ( !IsLoaded() ) {
2935 MESSAGE( "Pattern not loaded" );
2936 return setErrorCode( ERR_APPL_NOT_LOADED );
2939 // find points on edges, it fills myNbKeyPntInBoundary
2940 if ( !findBoundaryPoints() )
2943 // check that there are no holes in a pattern
2944 if (myNbKeyPntInBoundary.size() > 1 ) {
2945 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2950 myElemXYZIDs.clear();
2951 myXYZIdToNodeMap.clear();
2953 myIdsOnBoundary.clear();
2954 myReverseConnectivity.clear();
2956 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2957 myElements.reserve( theFaces.size() );
2959 // to find point index
2960 map< TPoint*, int > pointIndex;
2961 for ( int i = 0; i < myPoints.size(); i++ )
2962 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2964 int ind1 = 0; // lowest point index for a face
2969 // SMESH_MeshEditor editor( theMesh );
2971 // apply to each face in theFaces set
2972 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2973 for ( ; face != theFaces.end(); ++face )
2975 // int curShapeId = editor.FindShape( *face );
2976 // if ( curShapeId != shapeID ) {
2977 // if ( curShapeId )
2978 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2981 // shapeID = curShapeId;
2984 if ( shape.IsNull() )
2985 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2987 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2989 MESSAGE( "Failed on " << *face );
2992 myElements.push_back( *face );
2994 // store computed points belonging to elements
2995 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2996 for ( ; ll != myElemPointIDs.end(); ++ll )
2998 myElemXYZIDs.push_back(TElemDef());
2999 TElemDef& xyzIds = myElemXYZIDs.back();
3000 TElemDef& pIds = *ll;
3001 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3002 int pIndex = *id + ind1;
3003 xyzIds.push_back( pIndex );
3004 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3005 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3008 // put points on links to myIdsOnBoundary,
3009 // they will be used to sew new elements on adjacent refined elements
3010 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3011 for ( int i = 0; i < nbNodes; i++ )
3013 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3014 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3015 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
3016 // make a link and a node set
3017 TNodeSet linkSet, node1Set;
3018 linkSet.insert( n1 );
3019 linkSet.insert( n2 );
3020 node1Set.insert( n1 );
3021 list< TPoint* >::iterator p = linkPoints.begin();
3023 // map the first link point to n1
3024 int nId = pointIndex[ *p ] + ind1;
3025 myXYZIdToNodeMap[ nId ] = n1;
3026 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3027 groups.push_back(list< int > ());
3028 groups.back().push_back( nId );
3030 // add the linkSet to the map
3031 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3032 groups.push_back(list< int > ());
3033 list< int >& indList = groups.back();
3034 // add points to the map excluding the end points
3035 for ( p++; *p != linkPoints.back(); p++ )
3036 indList.push_back( pointIndex[ *p ] + ind1 );
3038 ind1 += myPoints.size();
3041 return !myElemXYZIDs.empty();
3044 //=======================================================================
3046 //purpose : Compute nodes coordinates applying
3047 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3048 // will be mapped into <theNode000Index>-th node. The
3049 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3051 //=======================================================================
3053 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3054 const int theNode000Index,
3055 const int theNode001Index)
3057 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3059 if ( !IsLoaded() ) {
3060 MESSAGE( "Pattern not loaded" );
3061 return setErrorCode( ERR_APPL_NOT_LOADED );
3064 // bind ID to points
3065 if ( !findBoundaryPoints() )
3068 // check that there are no holes in a pattern
3069 if (myNbKeyPntInBoundary.size() > 1 ) {
3070 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3075 myElemXYZIDs.clear();
3076 myXYZIdToNodeMap.clear();
3078 myIdsOnBoundary.clear();
3079 myReverseConnectivity.clear();
3081 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3082 myElements.reserve( theVolumes.size() );
3084 // to find point index
3085 map< TPoint*, int > pointIndex;
3086 for ( int i = 0; i < myPoints.size(); i++ )
3087 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3089 int ind1 = 0; // lowest point index for an element
3091 // apply to each element in theVolumes set
3092 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3093 for ( ; vol != theVolumes.end(); ++vol )
3095 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3096 MESSAGE( "Failed on " << *vol );
3099 myElements.push_back( *vol );
3101 // store computed points belonging to elements
3102 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3103 for ( ; ll != myElemPointIDs.end(); ++ll )
3105 myElemXYZIDs.push_back(TElemDef());
3106 TElemDef& xyzIds = myElemXYZIDs.back();
3107 TElemDef& pIds = *ll;
3108 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3109 int pIndex = *id + ind1;
3110 xyzIds.push_back( pIndex );
3111 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3112 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3115 // put points on edges and faces to myIdsOnBoundary,
3116 // they will be used to sew new elements on adjacent refined elements
3117 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3119 // make a set of sub-points
3121 vector< int > subIDs;
3122 if ( SMESH_Block::IsVertexID( Id )) {
3123 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3125 else if ( SMESH_Block::IsEdgeID( Id )) {
3126 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3127 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3128 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3131 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3132 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3133 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3134 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3135 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3136 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3137 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3138 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3141 list< TPoint* > & points = getShapePoints( Id );
3142 list< TPoint* >::iterator p = points.begin();
3143 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3144 groups.push_back(list< int > ());
3145 list< int >& indList = groups.back();
3146 for ( ; p != points.end(); p++ )
3147 indList.push_back( pointIndex[ *p ] + ind1 );
3148 if ( subNodes.size() == 1 ) // vertex case
3149 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3151 ind1 += myPoints.size();
3154 return !myElemXYZIDs.empty();
3157 //=======================================================================
3159 //purpose : Create a pattern from the mesh built on <theBlock>
3160 //=======================================================================
3162 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3163 const TopoDS_Shell& theBlock)
3165 MESSAGE(" ::Load(volume) " );
3168 SMESHDS_SubMesh * aSubMesh;
3170 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3172 // load shapes in myShapeIDMap
3174 TopoDS_Vertex v1, v2;
3175 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3176 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3179 int nbNodes = 0, shapeID;
3180 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3182 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3183 aSubMesh = getSubmeshWithElements( theMesh, S );
3185 nbNodes += aSubMesh->NbNodes();
3187 myPoints.resize( nbNodes );
3189 // load U of points on edges
3190 TNodePointIDMap nodePointIDMap;
3192 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3194 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3195 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3196 aSubMesh = getSubmeshWithElements( theMesh, S );
3197 if ( ! aSubMesh ) continue;
3198 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3199 if ( !nIt->more() ) continue;
3201 // store a node and a point
3202 while ( nIt->more() ) {
3203 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3204 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3206 nodePointIDMap.insert( make_pair( node, iPoint ));
3207 if ( block.IsVertexID( shapeID ))
3208 myKeyPointIDs.push_back( iPoint );
3209 TPoint* p = & myPoints[ iPoint++ ];
3210 shapePoints.push_back( p );
3211 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3212 p->myInitXYZ.SetCoord( 0,0,0 );
3214 list< TPoint* >::iterator pIt = shapePoints.begin();
3217 switch ( S.ShapeType() )
3222 for ( ; pIt != shapePoints.end(); pIt++ ) {
3223 double * coef = block.GetShapeCoef( shapeID );
3224 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3225 if ( coef[ iCoord - 1] > 0 )
3226 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3228 if ( S.ShapeType() == TopAbs_VERTEX )
3231 const TopoDS_Edge& edge = TopoDS::Edge( S );
3233 BRep_Tool::Range( edge, f, l );
3234 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3235 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3236 pIt = shapePoints.begin();
3237 nIt = aSubMesh->GetNodes();
3238 for ( ; nIt->more(); pIt++ )
3240 const SMDS_MeshNode* node = nIt->next();
3241 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3243 const SMDS_EdgePosition* epos =
3244 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3245 double u = ( epos->GetUParameter() - f ) / ( l - f );
3246 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3251 for ( ; pIt != shapePoints.end(); pIt++ )
3253 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3254 MESSAGE( "!block.ComputeParameters()" );
3255 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3259 } // loop on block sub-shapes
3263 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3266 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3267 while ( elemIt->more() ) {
3268 const SMDS_MeshElement* elem = elemIt->next();
3269 myElemPointIDs.push_back( TElemDef() );
3270 TElemDef& elemPoints = myElemPointIDs.back();
3271 int nbNodes = elem->NbCornerNodes();
3272 for ( int i = 0;i < nbNodes; ++i )
3273 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3277 myIsBoundaryPointsFound = true;
3279 return setErrorCode( ERR_OK );
3282 //=======================================================================
3283 //function : getSubmeshWithElements
3284 //purpose : return submesh containing elements bound to theBlock in theMesh
3285 //=======================================================================
3287 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3288 const TopoDS_Shape& theShape)
3290 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3291 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3294 if ( theShape.ShapeType() == TopAbs_SHELL )
3296 // look for submesh of VOLUME
3297 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3298 for (; it.More(); it.Next()) {
3299 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3300 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3308 //=======================================================================
3310 //purpose : Compute nodes coordinates applying
3311 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3312 // will be mapped into <theVertex000>. The (0,0,1)
3313 // fifth key-point will be mapped into <theVertex001>.
3314 //=======================================================================
3316 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3317 const TopoDS_Vertex& theVertex000,
3318 const TopoDS_Vertex& theVertex001)
3320 MESSAGE(" ::Apply(volume) " );
3322 if (!findBoundaryPoints() || // bind ID to points
3323 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3326 SMESH_Block block; // bind ID to shape
3327 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3328 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3330 // compute XYZ of points on shapes
3332 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3334 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3335 list< TPoint* >::iterator pIt = shapePoints.begin();
3336 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3337 switch ( S.ShapeType() )
3339 case TopAbs_VERTEX: {
3341 for ( ; pIt != shapePoints.end(); pIt++ )
3342 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3347 for ( ; pIt != shapePoints.end(); pIt++ )
3348 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3353 for ( ; pIt != shapePoints.end(); pIt++ )
3354 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3358 for ( ; pIt != shapePoints.end(); pIt++ )
3359 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3361 } // loop on block sub-shapes
3363 myIsComputed = true;
3365 return setErrorCode( ERR_OK );
3368 //=======================================================================
3370 //purpose : Compute nodes coordinates applying
3371 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3372 // will be mapped into <theNode000Index>-th node. The
3373 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3375 //=======================================================================
3377 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3378 const int theNode000Index,
3379 const int theNode001Index)
3381 //MESSAGE(" ::Apply(MeshVolume) " );
3383 if (!findBoundaryPoints()) // bind ID to points
3386 SMESH_Block block; // bind ID to shape
3387 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3388 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3389 // compute XYZ of points on shapes
3391 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3393 list< TPoint* > & shapePoints = getShapePoints( ID );
3394 list< TPoint* >::iterator pIt = shapePoints.begin();
3396 if ( block.IsVertexID( ID ))
3397 for ( ; pIt != shapePoints.end(); pIt++ ) {
3398 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3400 else if ( block.IsEdgeID( ID ))
3401 for ( ; pIt != shapePoints.end(); pIt++ ) {
3402 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3404 else if ( block.IsFaceID( ID ))
3405 for ( ; pIt != shapePoints.end(); pIt++ ) {
3406 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3409 for ( ; pIt != shapePoints.end(); pIt++ )
3410 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3411 } // loop on block sub-shapes
3413 myIsComputed = true;
3415 return setErrorCode( ERR_OK );
3418 //=======================================================================
3419 //function : mergePoints
3420 //purpose : Merge XYZ on edges and/or faces.
3421 //=======================================================================
3423 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3425 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3426 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3428 list<list< int > >& groups = idListIt->second;
3429 if ( groups.size() < 2 )
3433 const TNodeSet& nodes = idListIt->first;
3434 double tol2 = 1.e-10;
3435 if ( nodes.size() > 1 ) {
3437 TNodeSet::const_iterator n = nodes.begin();
3438 for ( ; n != nodes.end(); ++n )
3439 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3440 double x, y, z, X, Y, Z;
3441 box.Get( x, y, z, X, Y, Z );
3442 gp_Pnt p( x, y, z ), P( X, Y, Z );
3443 tol2 = 1.e-4 * p.SquareDistance( P );
3446 // to unite groups on link
3447 bool unite = ( uniteGroups && nodes.size() == 2 );
3448 map< double, int > distIndMap;
3449 const SMDS_MeshNode* node = *nodes.begin();
3450 gp_Pnt P( node->X(), node->Y(), node->Z() );
3452 // compare points, replace indices
3454 list< int >::iterator ind1, ind2;
3455 list< list< int > >::iterator grpIt1, grpIt2;
3456 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3458 list< int >& indices1 = *grpIt1;
3460 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3462 list< int >& indices2 = *grpIt2;
3463 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3465 gp_XYZ& p1 = myXYZ[ *ind1 ];
3466 ind2 = indices2.begin();
3467 while ( ind2 != indices2.end() )
3469 gp_XYZ& p2 = myXYZ[ *ind2 ];
3470 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3471 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3473 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3474 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3475 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3476 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3478 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3479 myXYZ[ *ind2 ] = undefinedXYZ();
3480 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3482 ind2 = indices2.erase( ind2 );
3489 if ( unite ) { // sort indices using distIndMap
3490 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3492 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3493 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3494 distIndMap.insert( make_pair( dist, *ind1 ));
3498 if ( unite ) { // put all sorted indices into the first group
3499 list< int >& g = groups.front();
3501 map< double, int >::iterator dist_ind = distIndMap.begin();
3502 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3503 g.push_back( dist_ind->second );
3505 } // loop on myIdsOnBoundary
3508 //=======================================================================
3509 //function : makePolyElements
3510 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3511 //=======================================================================
3513 void SMESH_Pattern::
3514 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3515 const bool toCreatePolygons,
3516 const bool toCreatePolyedrs)
3518 myPolyElemXYZIDs.clear();
3519 myPolyElems.clear();
3520 myPolyElems.reserve( myIdsOnBoundary.size() );
3522 // make a set of refined elements
3523 TIDSortedElemSet avoidSet, elemSet;
3524 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3525 for(; itv!=myElements.end(); itv++) {
3526 const SMDS_MeshElement* el = (*itv);
3527 avoidSet.insert( el );
3529 //avoidSet.insert( myElements.begin(), myElements.end() );
3531 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3533 if ( toCreatePolygons )
3535 int lastFreeId = myXYZ.size();
3537 // loop on links of refined elements
3538 indListIt = myIdsOnBoundary.begin();
3539 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3541 const TNodeSet & linkNodes = indListIt->first;
3542 if ( linkNodes.size() != 2 )
3543 continue; // skip face
3544 const SMDS_MeshNode* n1 = * linkNodes.begin();
3545 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3547 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3548 if ( idGroups.empty() || idGroups.front().empty() )
3551 // find not refined face having n1-n2 link
3555 const SMDS_MeshElement* face =
3556 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3559 avoidSet.insert ( face );
3560 myPolyElems.push_back( face );
3562 // some links of <face> are split;
3563 // make list of xyz for <face>
3564 myPolyElemXYZIDs.push_back(TElemDef());
3565 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3566 // loop on links of a <face>
3567 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3568 int i = 0, nbNodes = face->NbNodes();
3569 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3570 while ( nIt->more() )
3571 nodes[ i++ ] = smdsNode( nIt->next() );
3572 nodes[ i ] = nodes[ 0 ];
3573 for ( i = 0; i < nbNodes; ++i )
3575 // look for point mapped on a link
3576 TNodeSet faceLinkNodes;
3577 faceLinkNodes.insert( nodes[ i ] );
3578 faceLinkNodes.insert( nodes[ i + 1 ] );
3579 if ( faceLinkNodes == linkNodes )
3580 nn_IdList = indListIt;
3582 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3583 // add face point ids
3584 faceNodeIds.push_back( ++lastFreeId );
3585 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3586 if ( nn_IdList != myIdsOnBoundary.end() )
3588 // there are points mapped on a link
3589 list< int >& mappedIds = nn_IdList->second.front();
3590 if ( isReversed( nodes[ i ], mappedIds ))
3591 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3593 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3595 } // loop on links of a <face>
3601 if ( myIs2D && idGroups.size() > 1 ) {
3603 // sew new elements on 2 refined elements sharing n1-n2 link
3605 list< int >& idsOnLink = idGroups.front();
3606 // temporarily add ids of link nodes to idsOnLink
3607 bool rev = isReversed( n1, idsOnLink );
3608 for ( int i = 0; i < 2; ++i )
3611 nodeSet.insert( i ? n2 : n1 );
3612 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3613 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3614 int nodeId = groups.front().front();
3616 if ( rev ) append = !append;
3618 idsOnLink.push_back( nodeId );
3620 idsOnLink.push_front( nodeId );
3622 list< int >::iterator id = idsOnLink.begin();
3623 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3625 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3626 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3627 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3629 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3630 // look for <id> in element definition
3631 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3632 ASSERT ( idDef != pIdList->end() );
3633 // look for 2 neighbour ids of <id> in element definition
3634 for ( int prev = 0; prev < 2; ++prev ) {
3635 TElemDef::iterator idDef2 = idDef;
3637 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3639 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3640 // look for idDef2 on a link starting from id
3641 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3642 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3643 // insert ids located on link between <id> and <id2>
3644 // into the element definition between idDef and idDef2
3646 for ( ; id2 != id; --id2 )
3647 pIdList->insert( idDef, *id2 );
3649 list< int >::iterator id1 = id;
3650 for ( ++id1, ++id2; id1 != id2; ++id1 )
3651 pIdList->insert( idDef2, *id1 );
3657 // remove ids of link nodes
3658 idsOnLink.pop_front();
3659 idsOnLink.pop_back();
3661 } // loop on myIdsOnBoundary
3662 } // if ( toCreatePolygons )
3664 if ( toCreatePolyedrs )
3666 // check volumes adjacent to the refined elements
3667 SMDS_VolumeTool volTool;
3668 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3669 for ( ; refinedElem != myElements.end(); ++refinedElem )
3671 // loop on nodes of refinedElem
3672 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3673 while ( nIt->more() ) {
3674 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3675 // loop on inverse elements of node
3676 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3677 while ( eIt->more() )
3679 const SMDS_MeshElement* elem = eIt->next();
3680 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3681 continue; // skip faces or refined elements
3682 // add polyhedron definition
3683 myPolyhedronQuantities.push_back(vector<int> ());
3684 myPolyElemXYZIDs.push_back(TElemDef());
3685 vector<int>& quantity = myPolyhedronQuantities.back();
3686 TElemDef & elemDef = myPolyElemXYZIDs.back();
3687 // get definitions of new elements on volume faces
3688 bool makePoly = false;
3689 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3691 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3692 volTool.NbFaceNodes( iF ),
3693 theNodes, elemDef, quantity))
3697 myPolyElems.push_back( elem );
3699 myPolyhedronQuantities.pop_back();
3700 myPolyElemXYZIDs.pop_back();
3708 //=======================================================================
3709 //function : getFacesDefinition
3710 //purpose : return faces definition for a volume face defined by theBndNodes
3711 //=======================================================================
3713 bool SMESH_Pattern::
3714 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3715 const int theNbBndNodes,
3716 const vector< const SMDS_MeshNode* >& theNodes,
3717 list< int >& theFaceDefs,
3718 vector<int>& theQuantity)
3720 bool makePoly = false;
3722 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3724 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3726 // make a set of all nodes on a face
3728 if ( !myIs2D ) { // for 2D, merge only edges
3729 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3730 if ( nn_IdList != myIdsOnBoundary.end() ) {
3731 list< int > & faceIds = nn_IdList->second.front();
3732 if ( !faceIds.empty() ) {
3734 ids.insert( faceIds.begin(), faceIds.end() );
3739 // add ids on links and bnd nodes
3740 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3741 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3742 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3744 // add id of iN-th bnd node
3746 nSet.insert( theBndNodes[ iN ] );
3747 nn_IdList = myIdsOnBoundary.find( nSet );
3748 int bndId = ++lastFreeId;
3749 if ( nn_IdList != myIdsOnBoundary.end() ) {
3750 bndId = nn_IdList->second.front().front();
3751 ids.insert( bndId );
3754 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3756 faceDef.push_back( bndId );
3757 // add ids on a link
3759 linkNodes.insert( theBndNodes[ iN ]);
3760 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3761 nn_IdList = myIdsOnBoundary.find( linkNodes );
3762 if ( nn_IdList != myIdsOnBoundary.end() ) {
3763 list< int > & linkIds = nn_IdList->second.front();
3764 if ( !linkIds.empty() )
3767 ids.insert( linkIds.begin(), linkIds.end() );
3768 if ( isReversed( theBndNodes[ iN ], linkIds ))
3769 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3771 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3776 // find faces definition of new volumes
3778 bool defsAdded = false;
3779 if ( !myIs2D ) { // for 2D, merge only edges
3780 SMDS_VolumeTool vol;
3781 set< TElemDef* > checkedVolDefs;
3782 set< int >::iterator id = ids.begin();
3783 for ( ; id != ids.end(); ++id )
3785 // definitions of volumes sharing id
3786 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3787 ASSERT( !defList.empty() );
3788 // loop on volume definitions
3789 list< TElemDef* >::iterator pIdList = defList.begin();
3790 for ( ; pIdList != defList.end(); ++pIdList)
3792 if ( !checkedVolDefs.insert( *pIdList ).second )
3793 continue; // skip already checked volume definition
3794 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3795 // loop on face defs of a volume
3796 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3797 if ( volType == SMDS_VolumeTool::UNKNOWN )
3799 int nbFaces = vol.NbFaces( volType );
3800 for ( int iF = 0; iF < nbFaces; ++iF )
3802 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3803 int iN, nbN = vol.NbFaceNodes( volType, iF );
3804 // check if all nodes of a faces are in <ids>
3806 for ( iN = 0; iN < nbN && all; ++iN ) {
3807 int nodeId = idVec[ nodeInds[ iN ]];
3808 all = ( ids.find( nodeId ) != ids.end() );
3811 // store a face definition
3812 for ( iN = 0; iN < nbN; ++iN ) {
3813 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3815 theQuantity.push_back( nbN );
3823 theQuantity.push_back( faceDef.size() );
3824 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3830 //=======================================================================
3831 //function : clearSubMesh
3833 //=======================================================================
3835 static bool clearSubMesh( SMESH_Mesh* theMesh,
3836 const TopoDS_Shape& theShape)
3838 bool removed = false;
3839 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3841 removed = !aSubMesh->IsEmpty();
3843 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3846 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3847 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3849 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3850 removed = eIt->more();
3851 while ( eIt->more() )
3852 aMeshDS->RemoveElement( eIt->next() );
3853 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3854 removed = removed || nIt->more();
3855 while ( nIt->more() )
3856 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3862 //=======================================================================
3863 //function : clearMesh
3864 //purpose : clear mesh elements existing on myShape in theMesh
3865 //=======================================================================
3867 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3870 if ( !myShape.IsNull() )
3872 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3873 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3874 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3876 clearSubMesh( theMesh, it.Value() );
3882 //=======================================================================
3883 //function : MakeMesh
3884 //purpose : Create nodes and elements in <theMesh> using nodes
3885 // coordinates computed by either of Apply...() methods
3886 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3887 // it does not care of nodes and elements already existing on
3888 // subshapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3889 //=======================================================================
3891 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3892 const bool toCreatePolygons,
3893 const bool toCreatePolyedrs)
3895 MESSAGE(" ::MakeMesh() " );
3896 if ( !myIsComputed )
3897 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3899 mergePoints( toCreatePolygons );
3901 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3903 // clear elements and nodes existing on myShape
3906 bool onMeshElements = ( !myElements.empty() );
3908 // Create missing nodes
3910 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3911 if ( onMeshElements )
3913 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3914 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3915 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3916 nodesVector[ i_node->first ] = i_node->second;
3918 for ( int i = 0; i < myXYZ.size(); ++i ) {
3919 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3920 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3927 nodesVector.resize( myPoints.size(), 0 );
3929 // to find point index
3930 map< TPoint*, int > pointIndex;
3931 for ( int i = 0; i < myPoints.size(); i++ )
3932 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3934 // loop on sub-shapes of myShape: create nodes
3935 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3936 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3939 //SMESHDS_SubMesh * subMeshDS = 0;
3940 if ( !myShapeIDMap.IsEmpty() ) {
3941 S = myShapeIDMap( idPointIt->first );
3942 //subMeshDS = aMeshDS->MeshElements( S );
3944 list< TPoint* > & points = idPointIt->second;
3945 list< TPoint* >::iterator pIt = points.begin();
3946 for ( ; pIt != points.end(); pIt++ )
3948 TPoint* point = *pIt;
3949 int pIndex = pointIndex[ point ];
3950 if ( nodesVector [ pIndex ] )
3952 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3955 nodesVector [ pIndex ] = node;
3957 if ( !S.IsNull() /*subMeshDS*/ ) {
3958 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3959 switch ( S.ShapeType() ) {
3960 case TopAbs_VERTEX: {
3961 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3964 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3967 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3968 point->myUV.X(), point->myUV.Y() ); break;
3971 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3980 if ( onMeshElements )
3982 // prepare data to create poly elements
3983 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3986 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3987 // sew old and new elements
3988 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3992 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3995 aMeshDS->compactMesh();
3997 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3998 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3999 // for ( ; i_sm != sm.end(); i_sm++ )
4001 // cout << " SM " << i_sm->first << " ";
4002 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4003 // //SMDS_ElemIteratorPtr GetElements();
4004 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4005 // while ( nit->more() )
4006 // cout << nit->next()->GetID() << " ";
4009 return setErrorCode( ERR_OK );
4012 //=======================================================================
4013 //function : createElements
4014 //purpose : add elements to the mesh
4015 //=======================================================================
4017 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4018 const vector<const SMDS_MeshNode* >& theNodesVector,
4019 const list< TElemDef > & theElemNodeIDs,
4020 const vector<const SMDS_MeshElement*>& theElements)
4022 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4023 SMESH_MeshEditor editor( theMesh );
4025 bool onMeshElements = !theElements.empty();
4027 // shapes and groups theElements are on
4028 vector< int > shapeIDs;
4029 vector< list< SMESHDS_Group* > > groups;
4030 set< const SMDS_MeshNode* > shellNodes;
4031 if ( onMeshElements )
4033 shapeIDs.resize( theElements.size() );
4034 groups.resize( theElements.size() );
4035 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4036 set<SMESHDS_GroupBase*>::const_iterator grIt;
4037 for ( int i = 0; i < theElements.size(); i++ )
4039 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4040 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4041 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4042 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4043 groups[ i ].push_back( group );
4046 // get all nodes bound to shells because their SpacePosition is not set
4047 // by SMESHDS_Mesh::SetNodeInVolume()
4048 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4049 if ( !aMainShape.IsNull() ) {
4050 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4051 for ( ; shellExp.More(); shellExp.Next() )
4053 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4055 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4056 while ( nIt->more() )
4057 shellNodes.insert( nIt->next() );
4062 // nb new elements per a refined element
4063 int nbNewElemsPerOld = 1;
4064 if ( onMeshElements )
4065 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4069 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4070 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4071 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4073 const TElemDef & elemNodeInd = *enIt;
4075 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4076 TElemDef::const_iterator id = elemNodeInd.begin();
4078 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4079 if ( *id < theNodesVector.size() )
4080 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4082 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4084 // dim of refined elem
4085 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4086 if ( onMeshElements ) {
4087 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4090 const SMDS_MeshElement* elem = 0;
4092 switch ( nbNodes ) {
4094 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4096 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4098 if ( !onMeshElements ) {// create a quadratic face
4099 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4100 nodes[4], nodes[5] ); break;
4101 } // else do not break but create a polygon
4103 if ( !onMeshElements ) {// create a quadratic face
4104 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4105 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4106 } // else do not break but create a polygon
4108 elem = aMeshDS->AddPolygonalFace( nodes );
4112 switch ( nbNodes ) {
4114 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4116 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4119 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4120 nodes[4], nodes[5] ); break;
4122 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4123 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4125 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4128 // set element on a shape
4129 if ( elem && onMeshElements ) // applied to mesh elements
4131 int shapeID = shapeIDs[ elemIndex ];
4132 if ( shapeID > 0 ) {
4133 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4134 // set nodes on a shape
4135 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4136 if ( S.ShapeType() == TopAbs_SOLID ) {
4137 TopoDS_Iterator shellIt( S );
4138 if ( shellIt.More() )
4139 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4141 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4142 while ( noIt->more() ) {
4143 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4144 if (!node->getshapeId() &&
4145 shellNodes.find( node ) == shellNodes.end() ) {
4146 if ( S.ShapeType() == TopAbs_FACE )
4147 aMeshDS->SetNodeOnFace( node, shapeID,
4148 Precision::Infinite(),// <- it's a sign that UV is not set
4149 Precision::Infinite());
4151 aMeshDS->SetNodeInVolume( node, shapeID );
4152 shellNodes.insert( node );
4157 // add elem in groups
4158 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4159 for ( ; g != groups[ elemIndex ].end(); ++g )
4160 (*g)->SMDSGroup().Add( elem );
4162 if ( elem && !myShape.IsNull() ) // applied to shape
4163 aMeshDS->SetMeshElementOnShape( elem, myShape );
4166 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4167 // so that operations with hypotheses will erase the mesh being built
4169 SMESH_subMesh * subMesh;
4170 if ( !myShape.IsNull() ) {
4171 subMesh = theMesh->GetSubMesh( myShape );
4173 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4175 if ( onMeshElements ) {
4176 list< int > elemIDs;
4177 for ( int i = 0; i < theElements.size(); i++ )
4179 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4181 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4183 elemIDs.push_back( theElements[ i ]->GetID() );
4185 // remove refined elements
4186 editor.Remove( elemIDs, false );
4190 //=======================================================================
4191 //function : isReversed
4192 //purpose : check xyz ids order in theIdsList taking into account
4193 // theFirstNode on a link
4194 //=======================================================================
4196 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4197 const list< int >& theIdsList) const
4199 if ( theIdsList.size() < 2 )
4202 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4204 list<int>::const_iterator id = theIdsList.begin();
4205 for ( int i = 0; i < 2; ++i, ++id ) {
4206 if ( *id < myXYZ.size() )
4207 P[ i ] = myXYZ[ *id ];
4209 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4210 i_n = myXYZIdToNodeMap.find( *id );
4211 ASSERT( i_n != myXYZIdToNodeMap.end() );
4212 const SMDS_MeshNode* n = i_n->second;
4213 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4216 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4220 //=======================================================================
4221 //function : arrangeBoundaries
4222 //purpose : if there are several wires, arrange boundaryPoints so that
4223 // the outer wire goes first and fix inner wires orientation
4224 // update myKeyPointIDs to correspond to the order of key-points
4225 // in boundaries; sort internal boundaries by the nb of key-points
4226 //=======================================================================
4228 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4230 typedef list< list< TPoint* > >::iterator TListOfListIt;
4231 TListOfListIt bndIt;
4232 list< TPoint* >::iterator pIt;
4234 int nbBoundaries = boundaryList.size();
4235 if ( nbBoundaries > 1 )
4237 // sort boundaries by nb of key-points
4238 if ( nbBoundaries > 2 )
4240 // move boundaries in tmp list
4241 list< list< TPoint* > > tmpList;
4242 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4243 // make a map nb-key-points to boundary-position-in-tmpList,
4244 // boundary-positions get ordered in it
4245 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4246 TNbKpBndPosMap nbKpBndPosMap;
4247 bndIt = tmpList.begin();
4248 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4249 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4250 int nb = *nbKpIt * nbBoundaries;
4251 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4253 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4255 // move boundaries back to boundaryList
4256 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4257 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4258 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4259 TListOfListIt bndPos1 = bndPos2++;
4260 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4264 // Look for the outer boundary: the one with the point with the least X
4265 double leastX = DBL_MAX;
4266 TListOfListIt outerBndPos;
4267 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4269 list< TPoint* >& boundary = (*bndIt);
4270 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4272 TPoint* point = *pIt;
4273 if ( point->myInitXYZ.X() < leastX ) {
4274 leastX = point->myInitXYZ.X();
4275 outerBndPos = bndIt;
4280 if ( outerBndPos != boundaryList.begin() )
4281 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4283 } // if nbBoundaries > 1
4285 // Check boundaries orientation and re-fill myKeyPointIDs
4287 set< TPoint* > keyPointSet;
4288 list< int >::iterator kpIt = myKeyPointIDs.begin();
4289 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4290 keyPointSet.insert( & myPoints[ *kpIt ]);
4291 myKeyPointIDs.clear();
4293 // update myNbKeyPntInBoundary also
4294 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4296 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4298 // find the point with the least X
4299 double leastX = DBL_MAX;
4300 list< TPoint* >::iterator xpIt;
4301 list< TPoint* >& boundary = (*bndIt);
4302 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4304 TPoint* point = *pIt;
4305 if ( point->myInitXYZ.X() < leastX ) {
4306 leastX = point->myInitXYZ.X();
4310 // find points next to the point with the least X
4311 TPoint* p = *xpIt, *pPrev, *pNext;
4312 if ( p == boundary.front() )
4313 pPrev = *(++boundary.rbegin());
4319 if ( p == boundary.back() )
4320 pNext = *(++boundary.begin());
4325 // vectors of boundary direction near <p>
4326 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4327 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4328 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4329 double yPrev = v1.Y() / sqrt( sqMag1 );
4330 double yNext = v2.Y() / sqrt( sqMag2 );
4331 double sumY = yPrev + yNext;
4333 if ( bndIt == boundaryList.begin() ) // outer boundary
4341 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4342 (*nbKpIt) = 0; // count nb of key-points again
4343 pIt = boundary.begin();
4344 for ( ; pIt != boundary.end(); pIt++)
4346 TPoint* point = *pIt;
4347 if ( keyPointSet.find( point ) == keyPointSet.end() )
4349 // find an index of a keypoint
4351 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4352 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4353 if ( &(*pVecIt) == point )
4355 myKeyPointIDs.push_back( index );
4358 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4361 } // loop on a list of boundaries
4363 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4366 //=======================================================================
4367 //function : findBoundaryPoints
4368 //purpose : if loaded from file, find points to map on edges and faces and
4369 // compute their parameters
4370 //=======================================================================
4372 bool SMESH_Pattern::findBoundaryPoints()
4374 if ( myIsBoundaryPointsFound ) return true;
4376 MESSAGE(" findBoundaryPoints() ");
4378 myNbKeyPntInBoundary.clear();
4382 set< TPoint* > pointsInElems;
4384 // Find free links of elements:
4385 // put links of all elements in a set and remove links encountered twice
4387 typedef pair< TPoint*, TPoint*> TLink;
4388 set< TLink > linkSet;
4389 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4390 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4392 TElemDef & elemPoints = *epIt;
4393 TElemDef::iterator pIt = elemPoints.begin();
4394 int prevP = elemPoints.back();
4395 for ( ; pIt != elemPoints.end(); pIt++ ) {
4396 TPoint* p1 = & myPoints[ prevP ];
4397 TPoint* p2 = & myPoints[ *pIt ];
4398 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4399 ASSERT( link.first != link.second );
4400 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4401 if ( !itUniq.second )
4402 linkSet.erase( itUniq.first );
4405 pointsInElems.insert( p1 );
4408 // Now linkSet contains only free links,
4409 // find the points order that they have in boundaries
4411 // 1. make a map of key-points
4412 set< TPoint* > keyPointSet;
4413 list< int >::iterator kpIt = myKeyPointIDs.begin();
4414 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4415 keyPointSet.insert( & myPoints[ *kpIt ]);
4417 // 2. chain up boundary points
4418 list< list< TPoint* > > boundaryList;
4419 boundaryList.push_back( list< TPoint* >() );
4420 list< TPoint* > * boundary = & boundaryList.back();
4422 TPoint *point1, *point2, *keypoint1;
4423 kpIt = myKeyPointIDs.begin();
4424 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4425 // loop on free links: look for the next point
4427 set< TLink >::iterator lIt = linkSet.begin();
4428 while ( lIt != linkSet.end() )
4430 if ( (*lIt).first == point1 )
4431 point2 = (*lIt).second;
4432 else if ( (*lIt).second == point1 )
4433 point2 = (*lIt).first;
4438 linkSet.erase( lIt );
4439 lIt = linkSet.begin();
4441 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4443 boundary->push_back( point2 );
4445 else // a key-point found
4447 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4449 if ( point2 != keypoint1 ) // its not the boundary end
4451 boundary->push_back( point2 );
4453 else // the boundary end reached
4455 boundary->push_front( keypoint1 );
4456 boundary->push_back( keypoint1 );
4457 myNbKeyPntInBoundary.push_back( iKeyPoint );
4458 if ( keyPointSet.empty() )
4459 break; // all boundaries containing key-points are found
4461 // prepare to search for the next boundary
4462 boundaryList.push_back( list< TPoint* >() );
4463 boundary = & boundaryList.back();
4464 point2 = keypoint1 = (*keyPointSet.begin());
4468 } // loop on the free links set
4470 if ( boundary->empty() ) {
4471 MESSAGE(" a separate key-point");
4472 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4475 // if there are several wires, arrange boundaryPoints so that
4476 // the outer wire goes first and fix inner wires orientation;
4477 // sort myKeyPointIDs to correspond to the order of key-points
4479 arrangeBoundaries( boundaryList );
4481 // Find correspondence shape ID - points,
4482 // compute points parameter on edge
4484 keyPointSet.clear();
4485 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4486 keyPointSet.insert( & myPoints[ *kpIt ]);
4488 set< TPoint* > edgePointSet; // to find in-face points
4489 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4490 int edgeID = myKeyPointIDs.size() + 1;
4492 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4493 for ( ; bndIt != boundaryList.end(); bndIt++ )
4495 boundary = & (*bndIt);
4496 double edgeLength = 0;
4497 list< TPoint* >::iterator pIt = boundary->begin();
4498 getShapePoints( edgeID ).push_back( *pIt );
4499 getShapePoints( vertexID++ ).push_back( *pIt );
4500 for ( pIt++; pIt != boundary->end(); pIt++)
4502 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4503 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4504 TPoint* point = *pIt;
4505 edgePointSet.insert( point );
4506 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4508 edgePoints.push_back( point );
4509 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4510 point->myInitU = edgeLength;
4514 // treat points on the edge which ends up: compute U [0,1]
4515 edgePoints.push_back( point );
4516 if ( edgePoints.size() > 2 ) {
4517 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4518 list< TPoint* >::iterator epIt = edgePoints.begin();
4519 for ( ; epIt != edgePoints.end(); epIt++ )
4520 (*epIt)->myInitU /= edgeLength;
4522 // begin the next edge treatment
4525 if ( point != boundary->front() ) { // not the first key-point again
4526 getShapePoints( edgeID ).push_back( point );
4527 getShapePoints( vertexID++ ).push_back( point );
4533 // find in-face points
4534 list< TPoint* > & facePoints = getShapePoints( edgeID );
4535 vector< TPoint >::iterator pVecIt = myPoints.begin();
4536 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4537 TPoint* point = &(*pVecIt);
4538 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4539 pointsInElems.find( point ) != pointsInElems.end())
4540 facePoints.push_back( point );
4547 // bind points to shapes according to point parameters
4548 vector< TPoint >::iterator pVecIt = myPoints.begin();
4549 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4550 TPoint* point = &(*pVecIt);
4551 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4552 getShapePoints( shapeID ).push_back( point );
4553 // detect key-points
4554 if ( SMESH_Block::IsVertexID( shapeID ))
4555 myKeyPointIDs.push_back( i );
4559 myIsBoundaryPointsFound = true;
4560 return myIsBoundaryPointsFound;
4563 //=======================================================================
4565 //purpose : clear fields
4566 //=======================================================================
4568 void SMESH_Pattern::Clear()
4570 myIsComputed = myIsBoundaryPointsFound = false;
4573 myKeyPointIDs.clear();
4574 myElemPointIDs.clear();
4575 myShapeIDToPointsMap.clear();
4576 myShapeIDMap.Clear();
4578 myNbKeyPntInBoundary.clear();
4581 myElemXYZIDs.clear();
4582 myXYZIdToNodeMap.clear();
4584 myOrderedNodes.clear();
4585 myPolyElems.clear();
4586 myPolyElemXYZIDs.clear();
4587 myPolyhedronQuantities.clear();
4588 myIdsOnBoundary.clear();
4589 myReverseConnectivity.clear();
4592 //================================================================================
4594 * \brief set ErrorCode and return true if it is Ok
4596 //================================================================================
4598 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4600 myErrorCode = theErrorCode;
4601 return myErrorCode == ERR_OK;
4604 //=======================================================================
4605 //function : setShapeToMesh
4606 //purpose : set a shape to be meshed. Return True if meshing is possible
4607 //=======================================================================
4609 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4611 if ( !IsLoaded() ) {
4612 MESSAGE( "Pattern not loaded" );
4613 return setErrorCode( ERR_APPL_NOT_LOADED );
4616 TopAbs_ShapeEnum aType = theShape.ShapeType();
4617 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4619 MESSAGE( "Pattern dimention mismatch" );
4620 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4623 // check if a face is closed
4624 int nbNodeOnSeamEdge = 0;
4626 TopTools_MapOfShape seamVertices;
4627 TopoDS_Face face = TopoDS::Face( theShape );
4628 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4629 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4630 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4631 if ( BRep_Tool::IsClosed(ee, face) ) {
4632 // seam edge and vertices encounter twice in theFace
4633 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4634 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4639 // check nb of vertices
4640 TopTools_IndexedMapOfShape vMap;
4641 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4642 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4643 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4644 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4647 myElements.clear(); // not refine elements
4648 myElemXYZIDs.clear();
4650 myShapeIDMap.Clear();
4655 //=======================================================================
4656 //function : GetMappedPoints
4657 //purpose : Return nodes coordinates computed by Apply() method
4658 //=======================================================================
4660 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4663 if ( !myIsComputed )
4666 if ( myElements.empty() ) { // applied to shape
4667 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4668 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4669 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4671 else { // applied to mesh elements
4672 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4673 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4674 for ( ; xyz != myXYZ.end(); ++xyz )
4675 if ( !isDefined( *xyz ))
4676 thePoints.push_back( definedXYZ );
4678 thePoints.push_back( & (*xyz) );
4680 return !thePoints.empty();
4684 //=======================================================================
4685 //function : GetPoints
4686 //purpose : Return nodes coordinates of the pattern
4687 //=======================================================================
4689 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4696 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4697 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4698 thePoints.push_back( & (*pVecIt).myInitXYZ );
4700 return ( thePoints.size() > 0 );
4703 //=======================================================================
4704 //function : getShapePoints
4705 //purpose : return list of points located on theShape
4706 //=======================================================================
4708 list< SMESH_Pattern::TPoint* > &
4709 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4712 if ( !myShapeIDMap.Contains( theShape ))
4713 aShapeID = myShapeIDMap.Add( theShape );
4715 aShapeID = myShapeIDMap.FindIndex( theShape );
4717 return myShapeIDToPointsMap[ aShapeID ];
4720 //=======================================================================
4721 //function : getShapePoints
4722 //purpose : return list of points located on the shape
4723 //=======================================================================
4725 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4727 return myShapeIDToPointsMap[ theShapeID ];
4730 //=======================================================================
4731 //function : DumpPoints
4733 //=======================================================================
4735 void SMESH_Pattern::DumpPoints() const
4738 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4739 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4740 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4744 //=======================================================================
4745 //function : TPoint()
4747 //=======================================================================
4749 SMESH_Pattern::TPoint::TPoint()
4752 myInitXYZ.SetCoord(0,0,0);
4753 myInitUV.SetCoord(0.,0.);
4755 myXYZ.SetCoord(0,0,0);
4756 myUV.SetCoord(0.,0.);
4761 //=======================================================================
4762 //function : operator <<
4764 //=======================================================================
4766 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4768 gp_XYZ xyz = p.myInitXYZ;
4769 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4770 gp_XY xy = p.myInitUV;
4771 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4772 double u = p.myInitU;
4773 OS << " u( " << u << " )) " << &p << endl;
4774 xyz = p.myXYZ.XYZ();
4775 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4777 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4779 OS << " u( " << u << " ))" << endl;