1 // Copyright (C) 2007-2011 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 *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 ];
1966 if ( !nbComp ) continue;
1969 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1971 // check if a quadrangle is not distorted
1973 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1974 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1975 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1976 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1980 internNodes.push_back( node );
1985 static int maxNbIter = 100;
1986 #ifdef DEB_COMPUVBYELASTICISOLINES
1988 bool useNbMoveNode = 0;
1989 static int maxNbNodeMove = 100;
1992 if ( !useNbMoveNode )
1993 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1998 if ( !needIteration) break;
1999 #ifdef DEB_COMPUVBYELASTICISOLINES
2000 if ( nbIter >= maxNbIter ) break;
2003 list < TIsoNode* >::iterator nIt = internNodes.begin();
2004 for ( ; nIt != internNodes.end(); nIt++ ) {
2005 #ifdef DEB_COMPUVBYELASTICISOLINES
2007 cout << nbNodeMove <<" =================================================="<<endl;
2009 TIsoNode * node = *nIt;
2013 for ( iDir = 0; iDir < 2; iDir++ )
2015 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2016 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2017 double r = node->myRatio[ iDir ];
2018 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2019 // line[ iDir ].SetLocation( loc[ iDir ] );
2020 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2023 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2024 // double locR[2] = { 0, 0 };
2025 for ( iDir = 0; iDir < 2; iDir++ )
2027 const int iCoord = 2 - iDir; // coord changing along an isoline
2028 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2029 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2030 if ( !bndNode1 || !bndNode2 ) {
2033 double par1 = bndNode1->myInitUV.Coord( iCoord );
2034 double par2 = node->myInitUV.Coord( iCoord );
2035 double par3 = bndNode2->myInitUV.Coord( iCoord );
2036 double r = ( par2 - par1 ) / ( par3 - par1 );
2037 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2038 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2040 //locR[0] = locR[1] = 0.25;
2041 // intersect the 2 lines and move a node
2042 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2043 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2045 // double intR = 1 - locR[0] - locR[1];
2046 // gp_XY newUV = inter.Point(1).Value().XY();
2047 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2048 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2050 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2051 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2052 // avoid parallel isolines intersection
2053 checkQuads( node, newUV, reversed );
2055 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2057 } // intersection found
2058 #ifdef DEB_COMPUVBYELASTICISOLINES
2059 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2061 } // loop on internal nodes
2062 #ifdef DEB_COMPUVBYELASTICISOLINES
2063 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2065 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2067 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2069 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2070 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2071 #ifndef DEB_COMPUVBYELASTICISOLINES
2076 // Set computed UV to points
2078 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2079 TPoint* point = *pIt;
2080 //gp_XY oldUV = point->myUV;
2081 double minDist = DBL_MAX;
2082 list < TIsoNode >::iterator nIt = nodes.begin();
2083 for ( ; nIt != nodes.end(); nIt++ ) {
2084 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2085 if ( dist < minDist ) {
2087 point->myUV = (*nIt).myUV;
2096 //=======================================================================
2097 //function : setFirstEdge
2098 //purpose : choose the best first edge of theWire; return the summary distance
2099 // between point UV computed by isolines intersection and
2100 // eventual UV got from edge p-curves
2101 //=======================================================================
2103 //#define DBG_SETFIRSTEDGE
2104 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2106 int iE, nbEdges = theWire.size();
2110 // Transform UVs computed by iso to fit bnd box of a wire
2112 // max nb of points on an edge
2114 int eID = theFirstEdgeID;
2115 for ( iE = 0; iE < nbEdges; iE++ )
2116 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2118 // compute bnd boxes
2119 TopoDS_Face face = TopoDS::Face( myShape );
2120 Bnd_Box2d bndBox, eBndBox;
2121 eID = theFirstEdgeID;
2122 list< TopoDS_Edge >::iterator eIt;
2123 list< TPoint* >::iterator pIt;
2124 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2126 // UV by isos stored in TPoint.myXYZ
2127 list< TPoint* > & ePoints = getShapePoints( eID++ );
2128 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2130 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2132 // UV by an edge p-curve
2134 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2135 double dU = ( l - f ) / ( maxNbPnt - 1 );
2136 for ( int i = 0; i < maxNbPnt; i++ )
2137 eBndBox.Add( C2d->Value( f + i * dU ));
2140 // transform UVs by isos
2141 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2142 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2143 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2144 #ifdef DBG_SETFIRSTEDGE
2145 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2146 << eMinPar[1] << " - " << eMaxPar[1] );
2148 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2150 double dMin = eMinPar[i] - minPar[i];
2151 double dMax = eMaxPar[i] - maxPar[i];
2152 double dPar = maxPar[i] - minPar[i];
2153 eID = theFirstEdgeID;
2154 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2156 list< TPoint* > & ePoints = getShapePoints( eID++ );
2157 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2159 double par = (*pIt)->myXYZ.Coord( iC );
2160 double r = ( par - minPar[i] ) / dPar;
2161 par += ( 1 - r ) * dMin + r * dMax;
2162 (*pIt)->myXYZ.SetCoord( iC, par );
2168 double minDist = DBL_MAX;
2169 for ( iE = 0 ; iE < nbEdges; iE++ )
2171 #ifdef DBG_SETFIRSTEDGE
2172 MESSAGE ( " VARIANT " << iE );
2174 // evaluate the distance between UV computed by the 2 methods:
2175 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2177 int eID = theFirstEdgeID;
2178 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2180 list< TPoint* > & ePoints = getShapePoints( eID++ );
2181 computeUVOnEdge( *eIt, ePoints );
2182 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2184 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2185 #ifdef DBG_SETFIRSTEDGE
2186 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2187 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2191 #ifdef DBG_SETFIRSTEDGE
2192 MESSAGE ( "dist -- " << dist );
2194 if ( dist < minDist ) {
2196 eBest = theWire.front();
2198 // check variant with another first edge
2199 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2201 // put the best first edge to the theWire front
2202 if ( eBest != theWire.front() ) {
2203 eIt = find ( theWire.begin(), theWire.end(), eBest );
2204 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2210 //=======================================================================
2211 //function : sortSameSizeWires
2212 //purpose : sort wires in theWireList from theFromWire until theToWire,
2213 // the wires are set in the order to correspond to the order
2214 // of boundaries; after sorting, edges in the wires are put
2215 // in a good order, point UVs on edges are computed and points
2216 // are appended to theEdgesPointsList
2217 //=======================================================================
2219 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2220 const TListOfEdgesList::iterator& theFromWire,
2221 const TListOfEdgesList::iterator& theToWire,
2222 const int theFirstEdgeID,
2223 list< list< TPoint* > >& theEdgesPointsList )
2225 TopoDS_Face F = TopoDS::Face( myShape );
2226 int iW, nbWires = 0;
2227 TListOfEdgesList::iterator wlIt = theFromWire;
2228 while ( wlIt++ != theToWire )
2231 // Recompute key-point UVs by isolines intersection,
2232 // compute CG of key-points for each wire and bnd boxes of GCs
2235 gp_XY orig( gp::Origin2d().XY() );
2236 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2237 Bnd_Box2d bndBox, vBndBox;
2238 int eID = theFirstEdgeID;
2239 list< TopoDS_Edge >::iterator eIt;
2240 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2242 list< TopoDS_Edge > & wire = *wlIt;
2243 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2245 list< TPoint* > & ePoints = getShapePoints( eID++ );
2246 TPoint* p = ePoints.front();
2247 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2248 MESSAGE("cant sortSameSizeWires()");
2251 gcVec[iW] += p->myUV;
2252 bndBox.Add( gp_Pnt2d( p->myUV ));
2253 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2254 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2255 vGcVec[iW] += vXY.XY();
2257 // keep the computed UV to compare against by setFirstEdge()
2258 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2260 gcVec[iW] /= nbWires;
2261 vGcVec[iW] /= nbWires;
2262 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2263 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2266 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2268 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2269 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2270 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2271 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2273 double dMin = vMinPar[i] - minPar[i];
2274 double dMax = vMaxPar[i] - maxPar[i];
2275 double dPar = maxPar[i] - minPar[i];
2276 if ( Abs( dPar ) <= DBL_MIN )
2278 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2279 double par = gcVec[iW].Coord( iC );
2280 double r = ( par - minPar[i] ) / dPar;
2281 par += ( 1 - r ) * dMin + r * dMax;
2282 gcVec[iW].SetCoord( iC, par );
2286 // Define boundary - wire correspondence by GC closeness
2288 TListOfEdgesList tmpWList;
2289 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2290 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2291 TIntWirePosMap bndIndWirePosMap;
2292 vector< bool > bndFound( nbWires, false );
2293 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2295 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2296 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2297 double minDist = DBL_MAX;
2298 gp_XY & wGc = vGcVec[ iW ];
2300 for ( int iB = 0; iB < nbWires; iB++ ) {
2301 if ( bndFound[ iB ] ) continue;
2302 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2303 if ( dist < minDist ) {
2308 bndFound[ bIndex ] = true;
2309 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2314 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2315 eID = theFirstEdgeID;
2316 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2318 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2319 list < TopoDS_Edge > & wire = ( *wirePos );
2321 // choose the best first edge of a wire
2322 setFirstEdge( wire, eID );
2324 // compute eventual UV and fill theEdgesPointsList
2325 theEdgesPointsList.push_back( list< TPoint* >() );
2326 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2327 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2329 list< TPoint* > & ePoints = getShapePoints( eID++ );
2330 computeUVOnEdge( *eIt, ePoints );
2331 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2333 // put wire back to theWireList
2335 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2341 //=======================================================================
2343 //purpose : Compute nodes coordinates applying
2344 // the loaded pattern to <theFace>. The first key-point
2345 // will be mapped into <theVertexOnKeyPoint1>
2346 //=======================================================================
2348 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2349 const TopoDS_Vertex& theVertexOnKeyPoint1,
2350 const bool theReverse)
2352 MESSAGE(" ::Apply(face) " );
2353 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2354 if ( !setShapeToMesh( face ))
2357 // find points on edges, it fills myNbKeyPntInBoundary
2358 if ( !findBoundaryPoints() )
2361 // Define the edges order so that the first edge starts at
2362 // theVertexOnKeyPoint1
2364 list< TopoDS_Edge > eList;
2365 list< int > nbVertexInWires;
2366 int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2367 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2369 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2370 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2372 // check nb wires and edges
2373 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2374 l1.sort(); l2.sort();
2377 MESSAGE( "Wrong nb vertices in wires" );
2378 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2381 // here shapes get IDs, for the outer wire IDs are OK
2382 list<TopoDS_Edge>::iterator elIt = eList.begin();
2383 for ( ; elIt != eList.end(); elIt++ ) {
2384 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2385 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2386 // BEGIN: jfa for bug 0019943
2389 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2390 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2392 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2393 if (we.Current().IsSame(*elIt)) {
2395 if (nbe == 2) isClosed1 = true;
2400 // END: jfa for bug 0019943
2402 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2404 int nbVertices = myShapeIDMap.Extent();
2406 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2407 myShapeIDMap.Add( *elIt );
2409 myShapeIDMap.Add( face );
2411 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2412 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2413 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2416 // points on edges to be used for UV computation of in-face points
2417 list< list< TPoint* > > edgesPointsList;
2418 edgesPointsList.push_back( list< TPoint* >() );
2419 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2420 list< TPoint* >::iterator pIt;
2422 // compute UV of points on the outer wire
2423 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2424 for (iE = 0, elIt = eList.begin();
2425 iE < nbEdgesInOuterWire && elIt != eList.end();
2428 list< TPoint* > & ePoints = getShapePoints( *elIt );
2430 computeUVOnEdge( *elIt, ePoints );
2431 // collect on-edge points (excluding the last one)
2432 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2435 // If there are several wires, define the order of edges of inner wires:
2436 // compute UV of inner edge-points using 2 methods: the one for in-face points
2437 // and the one for on-edge points and then choose the best edge order
2438 // by the best correspondance of the 2 results
2441 // compute UV of inner edge-points using the method for in-face points
2442 // and devide eList into a list of separate wires
2444 list< list< TopoDS_Edge > > wireList;
2445 list<TopoDS_Edge>::iterator eIt = elIt;
2446 list<int>::iterator nbEIt = nbVertexInWires.begin();
2447 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2449 int nbEdges = *nbEIt;
2450 wireList.push_back( list< TopoDS_Edge >() );
2451 list< TopoDS_Edge > & wire = wireList.back();
2452 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2454 list< TPoint* > & ePoints = getShapePoints( *eIt );
2455 pIt = ePoints.begin();
2456 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2458 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2459 MESSAGE("cant Apply(face)");
2462 // keep the computed UV to compare against by setFirstEdge()
2463 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2465 wire.push_back( *eIt );
2468 // remove inner edges from eList
2469 eList.erase( elIt, eList.end() );
2471 // sort wireList by nb edges in a wire
2472 sortBySize< TopoDS_Edge > ( wireList );
2474 // an ID of the first edge of a boundary
2475 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2476 // if ( nbSeamShapes > 0 )
2477 // id1 += 2; // 2 vertices more
2479 // find points - edge correspondence for wires of unique size,
2480 // edge order within a wire should be defined only
2482 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2483 while ( wlIt != wireList.end() )
2485 list< TopoDS_Edge >& wire = (*wlIt);
2486 int nbEdges = wire.size();
2488 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2490 // choose the best first edge of a wire
2491 setFirstEdge( wire, id1 );
2493 // compute eventual UV and collect on-edge points
2494 edgesPointsList.push_back( list< TPoint* >() );
2495 edgesPoints = & edgesPointsList.back();
2497 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2499 list< TPoint* > & ePoints = getShapePoints( eID++ );
2500 computeUVOnEdge( *eIt, ePoints );
2501 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2507 // find boundary - wire correspondence for several wires of same size
2509 id1 = nbVertices + nbEdgesInOuterWire + 1;
2510 wlIt = wireList.begin();
2511 while ( wlIt != wireList.end() )
2513 int nbSameSize = 0, nbEdges = (*wlIt).size();
2514 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2516 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2520 if ( nbSameSize > 0 )
2521 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2524 id1 += nbEdges * ( nbSameSize + 1 );
2527 // add well-ordered edges to eList
2529 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2531 list< TopoDS_Edge >& wire = (*wlIt);
2532 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2535 // re-fill myShapeIDMap - all shapes get good IDs
2537 myShapeIDMap.Clear();
2538 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2539 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2540 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2541 myShapeIDMap.Add( *elIt );
2542 myShapeIDMap.Add( face );
2544 } // there are inner wires
2546 // Compute XYZ of on-edge points
2548 TopLoc_Location loc;
2549 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2551 BRepAdaptor_Curve C3d( *elIt );
2552 list< TPoint* > & ePoints = getShapePoints( iE++ );
2553 pIt = ePoints.begin();
2554 for ( pIt++; pIt != ePoints.end(); pIt++ )
2556 TPoint* point = *pIt;
2557 point->myXYZ = C3d.Value( point->myU );
2561 // Compute UV and XYZ of in-face points
2563 // try to use a simple algo
2564 list< TPoint* > & fPoints = getShapePoints( face );
2565 bool isDeformed = false;
2566 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2567 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2568 (*pIt)->myUV, isDeformed )) {
2569 MESSAGE("cant Apply(face)");
2572 // try to use a complex algo if it is a difficult case
2573 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2575 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2576 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2577 (*pIt)->myUV, isDeformed )) {
2578 MESSAGE("cant Apply(face)");
2583 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2584 const gp_Trsf & aTrsf = loc.Transformation();
2585 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2587 TPoint * point = *pIt;
2588 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2589 if ( !loc.IsIdentity() )
2590 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2593 myIsComputed = true;
2595 return setErrorCode( ERR_OK );
2598 //=======================================================================
2600 //purpose : Compute nodes coordinates applying
2601 // the loaded pattern to <theFace>. The first key-point
2602 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2603 //=======================================================================
2605 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2606 const int theNodeIndexOnKeyPoint1,
2607 const bool theReverse)
2609 // MESSAGE(" ::Apply(MeshFace) " );
2611 if ( !IsLoaded() ) {
2612 MESSAGE( "Pattern not loaded" );
2613 return setErrorCode( ERR_APPL_NOT_LOADED );
2616 // check nb of nodes
2617 const int nbFaceNodes = theFace->NbCornerNodes();
2618 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2619 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2620 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2623 // find points on edges, it fills myNbKeyPntInBoundary
2624 if ( !findBoundaryPoints() )
2627 // check that there are no holes in a pattern
2628 if (myNbKeyPntInBoundary.size() > 1 ) {
2629 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2632 // Define the nodes order
2634 list< const SMDS_MeshNode* > nodes;
2635 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2636 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2638 while ( noIt->more() && iSub < nbFaceNodes ) {
2639 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2640 nodes.push_back( node );
2641 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2644 if ( n != nodes.end() ) {
2646 if ( n != --nodes.end() )
2647 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2650 else if ( n != nodes.begin() )
2651 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2653 list< gp_XYZ > xyzList;
2654 myOrderedNodes.resize( nbFaceNodes );
2655 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2656 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2657 myOrderedNodes[ iSub++] = *n;
2660 // Define a face plane
2662 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2663 gp_Pnt P ( *xyzIt++ );
2664 gp_Vec Vx( P, *xyzIt++ ), N;
2666 N = Vx ^ gp_Vec( P, *xyzIt++ );
2667 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2668 if ( N.SquareMagnitude() <= DBL_MIN )
2669 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2670 gp_Ax2 pos( P, N, Vx );
2672 // Compute UV of key-points on a plane
2673 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2675 gp_Vec vec ( pos.Location(), *xyzIt );
2676 TPoint* p = getShapePoints( iSub ).front();
2677 p->myUV.SetX( vec * pos.XDirection() );
2678 p->myUV.SetY( vec * pos.YDirection() );
2682 // points on edges to be used for UV computation of in-face points
2683 list< list< TPoint* > > edgesPointsList;
2684 edgesPointsList.push_back( list< TPoint* >() );
2685 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2686 list< TPoint* >::iterator pIt;
2688 // compute UV and XYZ of points on edges
2690 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2692 gp_XYZ& xyz1 = *xyzIt++;
2693 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2695 list< TPoint* > & ePoints = getShapePoints( iSub );
2696 ePoints.back()->myInitU = 1.0;
2697 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2698 while ( *pIt != ePoints.back() )
2701 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2702 gp_Vec vec ( pos.Location(), p->myXYZ );
2703 p->myUV.SetX( vec * pos.XDirection() );
2704 p->myUV.SetY( vec * pos.YDirection() );
2706 // collect on-edge points (excluding the last one)
2707 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2710 // Compute UV and XYZ of in-face points
2712 // try to use a simple algo to compute UV
2713 list< TPoint* > & fPoints = getShapePoints( iSub );
2714 bool isDeformed = false;
2715 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2716 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2717 (*pIt)->myUV, isDeformed )) {
2718 MESSAGE("cant Apply(face)");
2721 // try to use a complex algo if it is a difficult case
2722 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2724 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2725 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2726 (*pIt)->myUV, isDeformed )) {
2727 MESSAGE("cant Apply(face)");
2732 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2734 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2737 myIsComputed = true;
2739 return setErrorCode( ERR_OK );
2742 //=======================================================================
2744 //purpose : Compute nodes coordinates applying
2745 // the loaded pattern to <theFace>. The first key-point
2746 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2747 //=======================================================================
2749 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2750 const SMDS_MeshFace* theFace,
2751 const TopoDS_Shape& theSurface,
2752 const int theNodeIndexOnKeyPoint1,
2753 const bool theReverse)
2755 // MESSAGE(" ::Apply(MeshFace) " );
2756 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2757 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2759 const TopoDS_Face& face = TopoDS::Face( theSurface );
2760 TopLoc_Location loc;
2761 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2762 const gp_Trsf & aTrsf = loc.Transformation();
2764 if ( !IsLoaded() ) {
2765 MESSAGE( "Pattern not loaded" );
2766 return setErrorCode( ERR_APPL_NOT_LOADED );
2769 // check nb of nodes
2770 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2771 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2772 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2775 // find points on edges, it fills myNbKeyPntInBoundary
2776 if ( !findBoundaryPoints() )
2779 // check that there are no holes in a pattern
2780 if (myNbKeyPntInBoundary.size() > 1 ) {
2781 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2784 // Define the nodes order
2786 list< const SMDS_MeshNode* > nodes;
2787 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2788 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2790 while ( noIt->more() ) {
2791 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2792 nodes.push_back( node );
2793 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2796 if ( n != nodes.end() ) {
2798 if ( n != --nodes.end() )
2799 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2802 else if ( n != nodes.begin() )
2803 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2806 // find a node not on a seam edge, if necessary
2807 SMESH_MesherHelper helper( *theMesh );
2808 helper.SetSubShape( theSurface );
2809 const SMDS_MeshNode* inFaceNode = 0;
2810 if ( helper.GetNodeUVneedInFaceNode() )
2812 SMESH_MeshEditor editor( theMesh );
2813 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2814 int shapeID = editor.FindShape( *n );
2816 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2817 if ( !helper.IsSeamShape( shapeID ))
2822 // Set UV of key-points (i.e. of nodes of theFace )
2823 vector< gp_XY > keyUV( theFace->NbNodes() );
2824 myOrderedNodes.resize( theFace->NbNodes() );
2825 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2827 TPoint* p = getShapePoints( iSub ).front();
2828 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2829 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2831 keyUV[ iSub-1 ] = p->myUV;
2832 myOrderedNodes[ iSub-1 ] = *n;
2835 // points on edges to be used for UV computation of in-face points
2836 list< list< TPoint* > > edgesPointsList;
2837 edgesPointsList.push_back( list< TPoint* >() );
2838 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2839 list< TPoint* >::iterator pIt;
2841 // compute UV and XYZ of points on edges
2843 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2845 gp_XY& uv1 = keyUV[ i ];
2846 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2848 list< TPoint* > & ePoints = getShapePoints( iSub );
2849 ePoints.back()->myInitU = 1.0;
2850 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2851 while ( *pIt != ePoints.back() )
2854 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2855 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2856 if ( !loc.IsIdentity() )
2857 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2859 // collect on-edge points (excluding the last one)
2860 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2863 // Compute UV and XYZ of in-face points
2865 // try to use a simple algo to compute UV
2866 list< TPoint* > & fPoints = getShapePoints( iSub );
2867 bool isDeformed = false;
2868 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2869 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2870 (*pIt)->myUV, isDeformed )) {
2871 MESSAGE("cant Apply(face)");
2874 // try to use a complex algo if it is a difficult case
2875 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2877 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2878 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2879 (*pIt)->myUV, isDeformed )) {
2880 MESSAGE("cant Apply(face)");
2885 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2887 TPoint * point = *pIt;
2888 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2889 if ( !loc.IsIdentity() )
2890 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2893 myIsComputed = true;
2895 return setErrorCode( ERR_OK );
2898 //=======================================================================
2899 //function : undefinedXYZ
2901 //=======================================================================
2903 static const gp_XYZ& undefinedXYZ()
2905 static gp_XYZ xyz( 1.e100, 0., 0. );
2909 //=======================================================================
2910 //function : isDefined
2912 //=======================================================================
2914 inline static bool isDefined(const gp_XYZ& theXYZ)
2916 return theXYZ.X() < 1.e100;
2919 //=======================================================================
2921 //purpose : Compute nodes coordinates applying
2922 // the loaded pattern to <theFaces>. The first key-point
2923 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2924 //=======================================================================
2926 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2927 std::set<const SMDS_MeshFace*>& theFaces,
2928 const int theNodeIndexOnKeyPoint1,
2929 const bool theReverse)
2931 MESSAGE(" ::Apply(set<MeshFace>) " );
2933 if ( !IsLoaded() ) {
2934 MESSAGE( "Pattern not loaded" );
2935 return setErrorCode( ERR_APPL_NOT_LOADED );
2938 // find points on edges, it fills myNbKeyPntInBoundary
2939 if ( !findBoundaryPoints() )
2942 // check that there are no holes in a pattern
2943 if (myNbKeyPntInBoundary.size() > 1 ) {
2944 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2949 myElemXYZIDs.clear();
2950 myXYZIdToNodeMap.clear();
2952 myIdsOnBoundary.clear();
2953 myReverseConnectivity.clear();
2955 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2956 myElements.reserve( theFaces.size() );
2958 // to find point index
2959 map< TPoint*, int > pointIndex;
2960 for ( int i = 0; i < myPoints.size(); i++ )
2961 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2963 int ind1 = 0; // lowest point index for a face
2968 // SMESH_MeshEditor editor( theMesh );
2970 // apply to each face in theFaces set
2971 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2972 for ( ; face != theFaces.end(); ++face )
2974 // int curShapeId = editor.FindShape( *face );
2975 // if ( curShapeId != shapeID ) {
2976 // if ( curShapeId )
2977 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2980 // shapeID = curShapeId;
2983 if ( shape.IsNull() )
2984 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2986 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2988 MESSAGE( "Failed on " << *face );
2991 myElements.push_back( *face );
2993 // store computed points belonging to elements
2994 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2995 for ( ; ll != myElemPointIDs.end(); ++ll )
2997 myElemXYZIDs.push_back(TElemDef());
2998 TElemDef& xyzIds = myElemXYZIDs.back();
2999 TElemDef& pIds = *ll;
3000 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3001 int pIndex = *id + ind1;
3002 xyzIds.push_back( pIndex );
3003 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3004 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3007 // put points on links to myIdsOnBoundary,
3008 // they will be used to sew new elements on adjacent refined elements
3009 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3010 for ( int i = 0; i < nbNodes; i++ )
3012 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3013 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3014 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
3015 // make a link and a node set
3016 TNodeSet linkSet, node1Set;
3017 linkSet.insert( n1 );
3018 linkSet.insert( n2 );
3019 node1Set.insert( n1 );
3020 list< TPoint* >::iterator p = linkPoints.begin();
3022 // map the first link point to n1
3023 int nId = pointIndex[ *p ] + ind1;
3024 myXYZIdToNodeMap[ nId ] = n1;
3025 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3026 groups.push_back(list< int > ());
3027 groups.back().push_back( nId );
3029 // add the linkSet to the map
3030 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3031 groups.push_back(list< int > ());
3032 list< int >& indList = groups.back();
3033 // add points to the map excluding the end points
3034 for ( p++; *p != linkPoints.back(); p++ )
3035 indList.push_back( pointIndex[ *p ] + ind1 );
3037 ind1 += myPoints.size();
3040 return !myElemXYZIDs.empty();
3043 //=======================================================================
3045 //purpose : Compute nodes coordinates applying
3046 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3047 // will be mapped into <theNode000Index>-th node. The
3048 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3050 //=======================================================================
3052 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3053 const int theNode000Index,
3054 const int theNode001Index)
3056 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3058 if ( !IsLoaded() ) {
3059 MESSAGE( "Pattern not loaded" );
3060 return setErrorCode( ERR_APPL_NOT_LOADED );
3063 // bind ID to points
3064 if ( !findBoundaryPoints() )
3067 // check that there are no holes in a pattern
3068 if (myNbKeyPntInBoundary.size() > 1 ) {
3069 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3074 myElemXYZIDs.clear();
3075 myXYZIdToNodeMap.clear();
3077 myIdsOnBoundary.clear();
3078 myReverseConnectivity.clear();
3080 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3081 myElements.reserve( theVolumes.size() );
3083 // to find point index
3084 map< TPoint*, int > pointIndex;
3085 for ( int i = 0; i < myPoints.size(); i++ )
3086 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3088 int ind1 = 0; // lowest point index for an element
3090 // apply to each element in theVolumes set
3091 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3092 for ( ; vol != theVolumes.end(); ++vol )
3094 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3095 MESSAGE( "Failed on " << *vol );
3098 myElements.push_back( *vol );
3100 // store computed points belonging to elements
3101 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3102 for ( ; ll != myElemPointIDs.end(); ++ll )
3104 myElemXYZIDs.push_back(TElemDef());
3105 TElemDef& xyzIds = myElemXYZIDs.back();
3106 TElemDef& pIds = *ll;
3107 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3108 int pIndex = *id + ind1;
3109 xyzIds.push_back( pIndex );
3110 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3111 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3114 // put points on edges and faces to myIdsOnBoundary,
3115 // they will be used to sew new elements on adjacent refined elements
3116 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3118 // make a set of sub-points
3120 vector< int > subIDs;
3121 if ( SMESH_Block::IsVertexID( Id )) {
3122 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3124 else if ( SMESH_Block::IsEdgeID( Id )) {
3125 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3126 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3127 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3130 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3131 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3132 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3133 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3134 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3135 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3136 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3137 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3140 list< TPoint* > & points = getShapePoints( Id );
3141 list< TPoint* >::iterator p = points.begin();
3142 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3143 groups.push_back(list< int > ());
3144 list< int >& indList = groups.back();
3145 for ( ; p != points.end(); p++ )
3146 indList.push_back( pointIndex[ *p ] + ind1 );
3147 if ( subNodes.size() == 1 ) // vertex case
3148 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3150 ind1 += myPoints.size();
3153 return !myElemXYZIDs.empty();
3156 //=======================================================================
3158 //purpose : Create a pattern from the mesh built on <theBlock>
3159 //=======================================================================
3161 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3162 const TopoDS_Shell& theBlock)
3164 MESSAGE(" ::Load(volume) " );
3167 SMESHDS_SubMesh * aSubMesh;
3169 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3171 // load shapes in myShapeIDMap
3173 TopoDS_Vertex v1, v2;
3174 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3175 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3178 int nbNodes = 0, shapeID;
3179 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3181 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3182 aSubMesh = getSubmeshWithElements( theMesh, S );
3184 nbNodes += aSubMesh->NbNodes();
3186 myPoints.resize( nbNodes );
3188 // load U of points on edges
3189 TNodePointIDMap nodePointIDMap;
3191 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3193 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3194 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3195 aSubMesh = getSubmeshWithElements( theMesh, S );
3196 if ( ! aSubMesh ) continue;
3197 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3198 if ( !nIt->more() ) continue;
3200 // store a node and a point
3201 while ( nIt->more() ) {
3202 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3203 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3205 nodePointIDMap.insert( make_pair( node, iPoint ));
3206 if ( block.IsVertexID( shapeID ))
3207 myKeyPointIDs.push_back( iPoint );
3208 TPoint* p = & myPoints[ iPoint++ ];
3209 shapePoints.push_back( p );
3210 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3211 p->myInitXYZ.SetCoord( 0,0,0 );
3213 list< TPoint* >::iterator pIt = shapePoints.begin();
3216 switch ( S.ShapeType() )
3221 for ( ; pIt != shapePoints.end(); pIt++ ) {
3222 double * coef = block.GetShapeCoef( shapeID );
3223 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3224 if ( coef[ iCoord - 1] > 0 )
3225 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3227 if ( S.ShapeType() == TopAbs_VERTEX )
3230 const TopoDS_Edge& edge = TopoDS::Edge( S );
3232 BRep_Tool::Range( edge, f, l );
3233 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3234 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3235 pIt = shapePoints.begin();
3236 nIt = aSubMesh->GetNodes();
3237 for ( ; nIt->more(); pIt++ )
3239 const SMDS_MeshNode* node = nIt->next();
3240 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3242 const SMDS_EdgePosition* epos =
3243 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3244 double u = ( epos->GetUParameter() - f ) / ( l - f );
3245 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3250 for ( ; pIt != shapePoints.end(); pIt++ )
3252 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3253 MESSAGE( "!block.ComputeParameters()" );
3254 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3258 } // loop on block sub-shapes
3262 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3265 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3266 while ( elemIt->more() ) {
3267 const SMDS_MeshElement* elem = elemIt->next();
3268 myElemPointIDs.push_back( TElemDef() );
3269 TElemDef& elemPoints = myElemPointIDs.back();
3270 int nbNodes = elem->NbCornerNodes();
3271 for ( int i = 0;i < nbNodes; ++i )
3272 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3276 myIsBoundaryPointsFound = true;
3278 return setErrorCode( ERR_OK );
3281 //=======================================================================
3282 //function : getSubmeshWithElements
3283 //purpose : return submesh containing elements bound to theBlock in theMesh
3284 //=======================================================================
3286 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3287 const TopoDS_Shape& theShape)
3289 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3290 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3293 if ( theShape.ShapeType() == TopAbs_SHELL )
3295 // look for submesh of VOLUME
3296 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3297 for (; it.More(); it.Next()) {
3298 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3299 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3307 //=======================================================================
3309 //purpose : Compute nodes coordinates applying
3310 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3311 // will be mapped into <theVertex000>. The (0,0,1)
3312 // fifth key-point will be mapped into <theVertex001>.
3313 //=======================================================================
3315 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3316 const TopoDS_Vertex& theVertex000,
3317 const TopoDS_Vertex& theVertex001)
3319 MESSAGE(" ::Apply(volume) " );
3321 if (!findBoundaryPoints() || // bind ID to points
3322 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3325 SMESH_Block block; // bind ID to shape
3326 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3327 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3329 // compute XYZ of points on shapes
3331 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3333 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3334 list< TPoint* >::iterator pIt = shapePoints.begin();
3335 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3336 switch ( S.ShapeType() )
3338 case TopAbs_VERTEX: {
3340 for ( ; pIt != shapePoints.end(); pIt++ )
3341 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3346 for ( ; pIt != shapePoints.end(); pIt++ )
3347 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3352 for ( ; pIt != shapePoints.end(); pIt++ )
3353 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3357 for ( ; pIt != shapePoints.end(); pIt++ )
3358 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3360 } // loop on block sub-shapes
3362 myIsComputed = true;
3364 return setErrorCode( ERR_OK );
3367 //=======================================================================
3369 //purpose : Compute nodes coordinates applying
3370 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3371 // will be mapped into <theNode000Index>-th node. The
3372 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3374 //=======================================================================
3376 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3377 const int theNode000Index,
3378 const int theNode001Index)
3380 //MESSAGE(" ::Apply(MeshVolume) " );
3382 if (!findBoundaryPoints()) // bind ID to points
3385 SMESH_Block block; // bind ID to shape
3386 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3387 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3388 // compute XYZ of points on shapes
3390 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3392 list< TPoint* > & shapePoints = getShapePoints( ID );
3393 list< TPoint* >::iterator pIt = shapePoints.begin();
3395 if ( block.IsVertexID( ID ))
3396 for ( ; pIt != shapePoints.end(); pIt++ ) {
3397 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3399 else if ( block.IsEdgeID( ID ))
3400 for ( ; pIt != shapePoints.end(); pIt++ ) {
3401 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3403 else if ( block.IsFaceID( ID ))
3404 for ( ; pIt != shapePoints.end(); pIt++ ) {
3405 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3408 for ( ; pIt != shapePoints.end(); pIt++ )
3409 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3410 } // loop on block sub-shapes
3412 myIsComputed = true;
3414 return setErrorCode( ERR_OK );
3417 //=======================================================================
3418 //function : mergePoints
3419 //purpose : Merge XYZ on edges and/or faces.
3420 //=======================================================================
3422 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3424 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3425 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3427 list<list< int > >& groups = idListIt->second;
3428 if ( groups.size() < 2 )
3432 const TNodeSet& nodes = idListIt->first;
3433 double tol2 = 1.e-10;
3434 if ( nodes.size() > 1 ) {
3436 TNodeSet::const_iterator n = nodes.begin();
3437 for ( ; n != nodes.end(); ++n )
3438 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3439 double x, y, z, X, Y, Z;
3440 box.Get( x, y, z, X, Y, Z );
3441 gp_Pnt p( x, y, z ), P( X, Y, Z );
3442 tol2 = 1.e-4 * p.SquareDistance( P );
3445 // to unite groups on link
3446 bool unite = ( uniteGroups && nodes.size() == 2 );
3447 map< double, int > distIndMap;
3448 const SMDS_MeshNode* node = *nodes.begin();
3449 gp_Pnt P( node->X(), node->Y(), node->Z() );
3451 // compare points, replace indices
3453 list< int >::iterator ind1, ind2;
3454 list< list< int > >::iterator grpIt1, grpIt2;
3455 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3457 list< int >& indices1 = *grpIt1;
3459 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3461 list< int >& indices2 = *grpIt2;
3462 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3464 gp_XYZ& p1 = myXYZ[ *ind1 ];
3465 ind2 = indices2.begin();
3466 while ( ind2 != indices2.end() )
3468 gp_XYZ& p2 = myXYZ[ *ind2 ];
3469 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3470 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3472 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3473 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3474 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3475 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3477 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3478 myXYZ[ *ind2 ] = undefinedXYZ();
3479 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3481 ind2 = indices2.erase( ind2 );
3488 if ( unite ) { // sort indices using distIndMap
3489 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3491 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3492 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3493 distIndMap.insert( make_pair( dist, *ind1 ));
3497 if ( unite ) { // put all sorted indices into the first group
3498 list< int >& g = groups.front();
3500 map< double, int >::iterator dist_ind = distIndMap.begin();
3501 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3502 g.push_back( dist_ind->second );
3504 } // loop on myIdsOnBoundary
3507 //=======================================================================
3508 //function : makePolyElements
3509 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3510 //=======================================================================
3512 void SMESH_Pattern::
3513 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3514 const bool toCreatePolygons,
3515 const bool toCreatePolyedrs)
3517 myPolyElemXYZIDs.clear();
3518 myPolyElems.clear();
3519 myPolyElems.reserve( myIdsOnBoundary.size() );
3521 // make a set of refined elements
3522 TIDSortedElemSet avoidSet, elemSet;
3523 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3524 for(; itv!=myElements.end(); itv++) {
3525 const SMDS_MeshElement* el = (*itv);
3526 avoidSet.insert( el );
3528 //avoidSet.insert( myElements.begin(), myElements.end() );
3530 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3532 if ( toCreatePolygons )
3534 int lastFreeId = myXYZ.size();
3536 // loop on links of refined elements
3537 indListIt = myIdsOnBoundary.begin();
3538 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3540 const TNodeSet & linkNodes = indListIt->first;
3541 if ( linkNodes.size() != 2 )
3542 continue; // skip face
3543 const SMDS_MeshNode* n1 = * linkNodes.begin();
3544 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3546 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3547 if ( idGroups.empty() || idGroups.front().empty() )
3550 // find not refined face having n1-n2 link
3554 const SMDS_MeshElement* face =
3555 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3558 avoidSet.insert ( face );
3559 myPolyElems.push_back( face );
3561 // some links of <face> are split;
3562 // make list of xyz for <face>
3563 myPolyElemXYZIDs.push_back(TElemDef());
3564 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3565 // loop on links of a <face>
3566 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3567 int i = 0, nbNodes = face->NbNodes();
3568 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3569 while ( nIt->more() )
3570 nodes[ i++ ] = smdsNode( nIt->next() );
3571 nodes[ i ] = nodes[ 0 ];
3572 for ( i = 0; i < nbNodes; ++i )
3574 // look for point mapped on a link
3575 TNodeSet faceLinkNodes;
3576 faceLinkNodes.insert( nodes[ i ] );
3577 faceLinkNodes.insert( nodes[ i + 1 ] );
3578 if ( faceLinkNodes == linkNodes )
3579 nn_IdList = indListIt;
3581 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3582 // add face point ids
3583 faceNodeIds.push_back( ++lastFreeId );
3584 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3585 if ( nn_IdList != myIdsOnBoundary.end() )
3587 // there are points mapped on a link
3588 list< int >& mappedIds = nn_IdList->second.front();
3589 if ( isReversed( nodes[ i ], mappedIds ))
3590 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3592 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3594 } // loop on links of a <face>
3600 if ( myIs2D && idGroups.size() > 1 ) {
3602 // sew new elements on 2 refined elements sharing n1-n2 link
3604 list< int >& idsOnLink = idGroups.front();
3605 // temporarily add ids of link nodes to idsOnLink
3606 bool rev = isReversed( n1, idsOnLink );
3607 for ( int i = 0; i < 2; ++i )
3610 nodeSet.insert( i ? n2 : n1 );
3611 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3612 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3613 int nodeId = groups.front().front();
3615 if ( rev ) append = !append;
3617 idsOnLink.push_back( nodeId );
3619 idsOnLink.push_front( nodeId );
3621 list< int >::iterator id = idsOnLink.begin();
3622 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3624 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3625 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3626 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3628 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3629 // look for <id> in element definition
3630 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3631 ASSERT ( idDef != pIdList->end() );
3632 // look for 2 neighbour ids of <id> in element definition
3633 for ( int prev = 0; prev < 2; ++prev ) {
3634 TElemDef::iterator idDef2 = idDef;
3636 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3638 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3639 // look for idDef2 on a link starting from id
3640 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3641 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3642 // insert ids located on link between <id> and <id2>
3643 // into the element definition between idDef and idDef2
3645 for ( ; id2 != id; --id2 )
3646 pIdList->insert( idDef, *id2 );
3648 list< int >::iterator id1 = id;
3649 for ( ++id1, ++id2; id1 != id2; ++id1 )
3650 pIdList->insert( idDef2, *id1 );
3656 // remove ids of link nodes
3657 idsOnLink.pop_front();
3658 idsOnLink.pop_back();
3660 } // loop on myIdsOnBoundary
3661 } // if ( toCreatePolygons )
3663 if ( toCreatePolyedrs )
3665 // check volumes adjacent to the refined elements
3666 SMDS_VolumeTool volTool;
3667 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3668 for ( ; refinedElem != myElements.end(); ++refinedElem )
3670 // loop on nodes of refinedElem
3671 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3672 while ( nIt->more() ) {
3673 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3674 // loop on inverse elements of node
3675 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3676 while ( eIt->more() )
3678 const SMDS_MeshElement* elem = eIt->next();
3679 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3680 continue; // skip faces or refined elements
3681 // add polyhedron definition
3682 myPolyhedronQuantities.push_back(vector<int> ());
3683 myPolyElemXYZIDs.push_back(TElemDef());
3684 vector<int>& quantity = myPolyhedronQuantities.back();
3685 TElemDef & elemDef = myPolyElemXYZIDs.back();
3686 // get definitions of new elements on volume faces
3687 bool makePoly = false;
3688 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3690 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3691 volTool.NbFaceNodes( iF ),
3692 theNodes, elemDef, quantity))
3696 myPolyElems.push_back( elem );
3698 myPolyhedronQuantities.pop_back();
3699 myPolyElemXYZIDs.pop_back();
3707 //=======================================================================
3708 //function : getFacesDefinition
3709 //purpose : return faces definition for a volume face defined by theBndNodes
3710 //=======================================================================
3712 bool SMESH_Pattern::
3713 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3714 const int theNbBndNodes,
3715 const vector< const SMDS_MeshNode* >& theNodes,
3716 list< int >& theFaceDefs,
3717 vector<int>& theQuantity)
3719 bool makePoly = false;
3721 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3723 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3725 // make a set of all nodes on a face
3727 if ( !myIs2D ) { // for 2D, merge only edges
3728 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3729 if ( nn_IdList != myIdsOnBoundary.end() ) {
3730 list< int > & faceIds = nn_IdList->second.front();
3731 if ( !faceIds.empty() ) {
3733 ids.insert( faceIds.begin(), faceIds.end() );
3738 // add ids on links and bnd nodes
3739 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3740 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3741 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3743 // add id of iN-th bnd node
3745 nSet.insert( theBndNodes[ iN ] );
3746 nn_IdList = myIdsOnBoundary.find( nSet );
3747 int bndId = ++lastFreeId;
3748 if ( nn_IdList != myIdsOnBoundary.end() ) {
3749 bndId = nn_IdList->second.front().front();
3750 ids.insert( bndId );
3753 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3755 faceDef.push_back( bndId );
3756 // add ids on a link
3758 linkNodes.insert( theBndNodes[ iN ]);
3759 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3760 nn_IdList = myIdsOnBoundary.find( linkNodes );
3761 if ( nn_IdList != myIdsOnBoundary.end() ) {
3762 list< int > & linkIds = nn_IdList->second.front();
3763 if ( !linkIds.empty() )
3766 ids.insert( linkIds.begin(), linkIds.end() );
3767 if ( isReversed( theBndNodes[ iN ], linkIds ))
3768 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3770 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3775 // find faces definition of new volumes
3777 bool defsAdded = false;
3778 if ( !myIs2D ) { // for 2D, merge only edges
3779 SMDS_VolumeTool vol;
3780 set< TElemDef* > checkedVolDefs;
3781 set< int >::iterator id = ids.begin();
3782 for ( ; id != ids.end(); ++id )
3784 // definitions of volumes sharing id
3785 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3786 ASSERT( !defList.empty() );
3787 // loop on volume definitions
3788 list< TElemDef* >::iterator pIdList = defList.begin();
3789 for ( ; pIdList != defList.end(); ++pIdList)
3791 if ( !checkedVolDefs.insert( *pIdList ).second )
3792 continue; // skip already checked volume definition
3793 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3794 // loop on face defs of a volume
3795 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3796 if ( volType == SMDS_VolumeTool::UNKNOWN )
3798 int nbFaces = vol.NbFaces( volType );
3799 for ( int iF = 0; iF < nbFaces; ++iF )
3801 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3802 int iN, nbN = vol.NbFaceNodes( volType, iF );
3803 // check if all nodes of a faces are in <ids>
3805 for ( iN = 0; iN < nbN && all; ++iN ) {
3806 int nodeId = idVec[ nodeInds[ iN ]];
3807 all = ( ids.find( nodeId ) != ids.end() );
3810 // store a face definition
3811 for ( iN = 0; iN < nbN; ++iN ) {
3812 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3814 theQuantity.push_back( nbN );
3822 theQuantity.push_back( faceDef.size() );
3823 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3829 //=======================================================================
3830 //function : clearSubMesh
3832 //=======================================================================
3834 static bool clearSubMesh( SMESH_Mesh* theMesh,
3835 const TopoDS_Shape& theShape)
3837 bool removed = false;
3838 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3840 removed = !aSubMesh->IsEmpty();
3842 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3845 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3846 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3848 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3849 removed = eIt->more();
3850 while ( eIt->more() )
3851 aMeshDS->RemoveElement( eIt->next() );
3852 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3853 removed = removed || nIt->more();
3854 while ( nIt->more() )
3855 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3861 //=======================================================================
3862 //function : clearMesh
3863 //purpose : clear mesh elements existing on myShape in theMesh
3864 //=======================================================================
3866 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3869 if ( !myShape.IsNull() )
3871 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3872 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3873 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3875 clearSubMesh( theMesh, it.Value() );
3881 //=======================================================================
3882 //function : MakeMesh
3883 //purpose : Create nodes and elements in <theMesh> using nodes
3884 // coordinates computed by either of Apply...() methods
3885 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3886 // it does not care of nodes and elements already existing on
3887 // subshapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3888 //=======================================================================
3890 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3891 const bool toCreatePolygons,
3892 const bool toCreatePolyedrs)
3894 MESSAGE(" ::MakeMesh() " );
3895 if ( !myIsComputed )
3896 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3898 mergePoints( toCreatePolygons );
3900 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3902 // clear elements and nodes existing on myShape
3905 bool onMeshElements = ( !myElements.empty() );
3907 // Create missing nodes
3909 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3910 if ( onMeshElements )
3912 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3913 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3914 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3915 nodesVector[ i_node->first ] = i_node->second;
3917 for ( int i = 0; i < myXYZ.size(); ++i ) {
3918 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3919 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3926 nodesVector.resize( myPoints.size(), 0 );
3928 // to find point index
3929 map< TPoint*, int > pointIndex;
3930 for ( int i = 0; i < myPoints.size(); i++ )
3931 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3933 // loop on sub-shapes of myShape: create nodes
3934 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3935 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3938 //SMESHDS_SubMesh * subMeshDS = 0;
3939 if ( !myShapeIDMap.IsEmpty() ) {
3940 S = myShapeIDMap( idPointIt->first );
3941 //subMeshDS = aMeshDS->MeshElements( S );
3943 list< TPoint* > & points = idPointIt->second;
3944 list< TPoint* >::iterator pIt = points.begin();
3945 for ( ; pIt != points.end(); pIt++ )
3947 TPoint* point = *pIt;
3948 int pIndex = pointIndex[ point ];
3949 if ( nodesVector [ pIndex ] )
3951 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3954 nodesVector [ pIndex ] = node;
3956 if ( !S.IsNull() /*subMeshDS*/ ) {
3957 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3958 switch ( S.ShapeType() ) {
3959 case TopAbs_VERTEX: {
3960 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3963 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3966 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3967 point->myUV.X(), point->myUV.Y() ); break;
3970 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3979 if ( onMeshElements )
3981 // prepare data to create poly elements
3982 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3985 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3986 // sew old and new elements
3987 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3991 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3994 aMeshDS->compactMesh();
3996 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3997 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3998 // for ( ; i_sm != sm.end(); i_sm++ )
4000 // cout << " SM " << i_sm->first << " ";
4001 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4002 // //SMDS_ElemIteratorPtr GetElements();
4003 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4004 // while ( nit->more() )
4005 // cout << nit->next()->GetID() << " ";
4008 return setErrorCode( ERR_OK );
4011 //=======================================================================
4012 //function : createElements
4013 //purpose : add elements to the mesh
4014 //=======================================================================
4016 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4017 const vector<const SMDS_MeshNode* >& theNodesVector,
4018 const list< TElemDef > & theElemNodeIDs,
4019 const vector<const SMDS_MeshElement*>& theElements)
4021 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4022 SMESH_MeshEditor editor( theMesh );
4024 bool onMeshElements = !theElements.empty();
4026 // shapes and groups theElements are on
4027 vector< int > shapeIDs;
4028 vector< list< SMESHDS_Group* > > groups;
4029 set< const SMDS_MeshNode* > shellNodes;
4030 if ( onMeshElements )
4032 shapeIDs.resize( theElements.size() );
4033 groups.resize( theElements.size() );
4034 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4035 set<SMESHDS_GroupBase*>::const_iterator grIt;
4036 for ( int i = 0; i < theElements.size(); i++ )
4038 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4039 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4040 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4041 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4042 groups[ i ].push_back( group );
4045 // get all nodes bound to shells because their SpacePosition is not set
4046 // by SMESHDS_Mesh::SetNodeInVolume()
4047 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4048 if ( !aMainShape.IsNull() ) {
4049 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4050 for ( ; shellExp.More(); shellExp.Next() )
4052 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4054 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4055 while ( nIt->more() )
4056 shellNodes.insert( nIt->next() );
4061 // nb new elements per a refined element
4062 int nbNewElemsPerOld = 1;
4063 if ( onMeshElements )
4064 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4068 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4069 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4070 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4072 const TElemDef & elemNodeInd = *enIt;
4074 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4075 TElemDef::const_iterator id = elemNodeInd.begin();
4077 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4078 if ( *id < theNodesVector.size() )
4079 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4081 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4083 // dim of refined elem
4084 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4085 if ( onMeshElements ) {
4086 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4089 const SMDS_MeshElement* elem = 0;
4091 switch ( nbNodes ) {
4093 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4095 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4097 if ( !onMeshElements ) {// create a quadratic face
4098 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4099 nodes[4], nodes[5] ); break;
4100 } // else do not break but create a polygon
4102 if ( !onMeshElements ) {// create a quadratic face
4103 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4104 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4105 } // else do not break but create a polygon
4107 elem = aMeshDS->AddPolygonalFace( nodes );
4111 switch ( nbNodes ) {
4113 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4115 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4118 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4119 nodes[4], nodes[5] ); break;
4121 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4122 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4124 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4127 // set element on a shape
4128 if ( elem && onMeshElements ) // applied to mesh elements
4130 int shapeID = shapeIDs[ elemIndex ];
4131 if ( shapeID > 0 ) {
4132 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4133 // set nodes on a shape
4134 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4135 if ( S.ShapeType() == TopAbs_SOLID ) {
4136 TopoDS_Iterator shellIt( S );
4137 if ( shellIt.More() )
4138 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4140 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4141 while ( noIt->more() ) {
4142 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4143 if (!node->getshapeId() &&
4144 shellNodes.find( node ) == shellNodes.end() ) {
4145 if ( S.ShapeType() == TopAbs_FACE )
4146 aMeshDS->SetNodeOnFace( node, shapeID,
4147 Precision::Infinite(),// <- it's a sign that UV is not set
4148 Precision::Infinite());
4150 aMeshDS->SetNodeInVolume( node, shapeID );
4151 shellNodes.insert( node );
4156 // add elem in groups
4157 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4158 for ( ; g != groups[ elemIndex ].end(); ++g )
4159 (*g)->SMDSGroup().Add( elem );
4161 if ( elem && !myShape.IsNull() ) // applied to shape
4162 aMeshDS->SetMeshElementOnShape( elem, myShape );
4165 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4166 // so that operations with hypotheses will erase the mesh being built
4168 SMESH_subMesh * subMesh;
4169 if ( !myShape.IsNull() ) {
4170 subMesh = theMesh->GetSubMesh( myShape );
4172 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4174 if ( onMeshElements ) {
4175 list< int > elemIDs;
4176 for ( int i = 0; i < theElements.size(); i++ )
4178 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4180 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4182 elemIDs.push_back( theElements[ i ]->GetID() );
4184 // remove refined elements
4185 editor.Remove( elemIDs, false );
4189 //=======================================================================
4190 //function : isReversed
4191 //purpose : check xyz ids order in theIdsList taking into account
4192 // theFirstNode on a link
4193 //=======================================================================
4195 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4196 const list< int >& theIdsList) const
4198 if ( theIdsList.size() < 2 )
4201 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4203 list<int>::const_iterator id = theIdsList.begin();
4204 for ( int i = 0; i < 2; ++i, ++id ) {
4205 if ( *id < myXYZ.size() )
4206 P[ i ] = myXYZ[ *id ];
4208 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4209 i_n = myXYZIdToNodeMap.find( *id );
4210 ASSERT( i_n != myXYZIdToNodeMap.end() );
4211 const SMDS_MeshNode* n = i_n->second;
4212 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4215 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4219 //=======================================================================
4220 //function : arrangeBoundaries
4221 //purpose : if there are several wires, arrange boundaryPoints so that
4222 // the outer wire goes first and fix inner wires orientation
4223 // update myKeyPointIDs to correspond to the order of key-points
4224 // in boundaries; sort internal boundaries by the nb of key-points
4225 //=======================================================================
4227 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4229 typedef list< list< TPoint* > >::iterator TListOfListIt;
4230 TListOfListIt bndIt;
4231 list< TPoint* >::iterator pIt;
4233 int nbBoundaries = boundaryList.size();
4234 if ( nbBoundaries > 1 )
4236 // sort boundaries by nb of key-points
4237 if ( nbBoundaries > 2 )
4239 // move boundaries in tmp list
4240 list< list< TPoint* > > tmpList;
4241 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4242 // make a map nb-key-points to boundary-position-in-tmpList,
4243 // boundary-positions get ordered in it
4244 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4245 TNbKpBndPosMap nbKpBndPosMap;
4246 bndIt = tmpList.begin();
4247 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4248 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4249 int nb = *nbKpIt * nbBoundaries;
4250 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4252 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4254 // move boundaries back to boundaryList
4255 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4256 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4257 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4258 TListOfListIt bndPos1 = bndPos2++;
4259 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4263 // Look for the outer boundary: the one with the point with the least X
4264 double leastX = DBL_MAX;
4265 TListOfListIt outerBndPos;
4266 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4268 list< TPoint* >& boundary = (*bndIt);
4269 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4271 TPoint* point = *pIt;
4272 if ( point->myInitXYZ.X() < leastX ) {
4273 leastX = point->myInitXYZ.X();
4274 outerBndPos = bndIt;
4279 if ( outerBndPos != boundaryList.begin() )
4280 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4282 } // if nbBoundaries > 1
4284 // Check boundaries orientation and re-fill myKeyPointIDs
4286 set< TPoint* > keyPointSet;
4287 list< int >::iterator kpIt = myKeyPointIDs.begin();
4288 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4289 keyPointSet.insert( & myPoints[ *kpIt ]);
4290 myKeyPointIDs.clear();
4292 // update myNbKeyPntInBoundary also
4293 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4295 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4297 // find the point with the least X
4298 double leastX = DBL_MAX;
4299 list< TPoint* >::iterator xpIt;
4300 list< TPoint* >& boundary = (*bndIt);
4301 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4303 TPoint* point = *pIt;
4304 if ( point->myInitXYZ.X() < leastX ) {
4305 leastX = point->myInitXYZ.X();
4309 // find points next to the point with the least X
4310 TPoint* p = *xpIt, *pPrev, *pNext;
4311 if ( p == boundary.front() )
4312 pPrev = *(++boundary.rbegin());
4318 if ( p == boundary.back() )
4319 pNext = *(++boundary.begin());
4324 // vectors of boundary direction near <p>
4325 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4326 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4327 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4328 double yPrev = v1.Y() / sqrt( sqMag1 );
4329 double yNext = v2.Y() / sqrt( sqMag2 );
4330 double sumY = yPrev + yNext;
4332 if ( bndIt == boundaryList.begin() ) // outer boundary
4340 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4341 (*nbKpIt) = 0; // count nb of key-points again
4342 pIt = boundary.begin();
4343 for ( ; pIt != boundary.end(); pIt++)
4345 TPoint* point = *pIt;
4346 if ( keyPointSet.find( point ) == keyPointSet.end() )
4348 // find an index of a keypoint
4350 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4351 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4352 if ( &(*pVecIt) == point )
4354 myKeyPointIDs.push_back( index );
4357 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4360 } // loop on a list of boundaries
4362 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4365 //=======================================================================
4366 //function : findBoundaryPoints
4367 //purpose : if loaded from file, find points to map on edges and faces and
4368 // compute their parameters
4369 //=======================================================================
4371 bool SMESH_Pattern::findBoundaryPoints()
4373 if ( myIsBoundaryPointsFound ) return true;
4375 MESSAGE(" findBoundaryPoints() ");
4377 myNbKeyPntInBoundary.clear();
4381 set< TPoint* > pointsInElems;
4383 // Find free links of elements:
4384 // put links of all elements in a set and remove links encountered twice
4386 typedef pair< TPoint*, TPoint*> TLink;
4387 set< TLink > linkSet;
4388 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4389 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4391 TElemDef & elemPoints = *epIt;
4392 TElemDef::iterator pIt = elemPoints.begin();
4393 int prevP = elemPoints.back();
4394 for ( ; pIt != elemPoints.end(); pIt++ ) {
4395 TPoint* p1 = & myPoints[ prevP ];
4396 TPoint* p2 = & myPoints[ *pIt ];
4397 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4398 ASSERT( link.first != link.second );
4399 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4400 if ( !itUniq.second )
4401 linkSet.erase( itUniq.first );
4404 pointsInElems.insert( p1 );
4407 // Now linkSet contains only free links,
4408 // find the points order that they have in boundaries
4410 // 1. make a map of key-points
4411 set< TPoint* > keyPointSet;
4412 list< int >::iterator kpIt = myKeyPointIDs.begin();
4413 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4414 keyPointSet.insert( & myPoints[ *kpIt ]);
4416 // 2. chain up boundary points
4417 list< list< TPoint* > > boundaryList;
4418 boundaryList.push_back( list< TPoint* >() );
4419 list< TPoint* > * boundary = & boundaryList.back();
4421 TPoint *point1, *point2, *keypoint1;
4422 kpIt = myKeyPointIDs.begin();
4423 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4424 // loop on free links: look for the next point
4426 set< TLink >::iterator lIt = linkSet.begin();
4427 while ( lIt != linkSet.end() )
4429 if ( (*lIt).first == point1 )
4430 point2 = (*lIt).second;
4431 else if ( (*lIt).second == point1 )
4432 point2 = (*lIt).first;
4437 linkSet.erase( lIt );
4438 lIt = linkSet.begin();
4440 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4442 boundary->push_back( point2 );
4444 else // a key-point found
4446 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4448 if ( point2 != keypoint1 ) // its not the boundary end
4450 boundary->push_back( point2 );
4452 else // the boundary end reached
4454 boundary->push_front( keypoint1 );
4455 boundary->push_back( keypoint1 );
4456 myNbKeyPntInBoundary.push_back( iKeyPoint );
4457 if ( keyPointSet.empty() )
4458 break; // all boundaries containing key-points are found
4460 // prepare to search for the next boundary
4461 boundaryList.push_back( list< TPoint* >() );
4462 boundary = & boundaryList.back();
4463 point2 = keypoint1 = (*keyPointSet.begin());
4467 } // loop on the free links set
4469 if ( boundary->empty() ) {
4470 MESSAGE(" a separate key-point");
4471 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4474 // if there are several wires, arrange boundaryPoints so that
4475 // the outer wire goes first and fix inner wires orientation;
4476 // sort myKeyPointIDs to correspond to the order of key-points
4478 arrangeBoundaries( boundaryList );
4480 // Find correspondence shape ID - points,
4481 // compute points parameter on edge
4483 keyPointSet.clear();
4484 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4485 keyPointSet.insert( & myPoints[ *kpIt ]);
4487 set< TPoint* > edgePointSet; // to find in-face points
4488 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4489 int edgeID = myKeyPointIDs.size() + 1;
4491 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4492 for ( ; bndIt != boundaryList.end(); bndIt++ )
4494 boundary = & (*bndIt);
4495 double edgeLength = 0;
4496 list< TPoint* >::iterator pIt = boundary->begin();
4497 getShapePoints( edgeID ).push_back( *pIt );
4498 getShapePoints( vertexID++ ).push_back( *pIt );
4499 for ( pIt++; pIt != boundary->end(); pIt++)
4501 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4502 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4503 TPoint* point = *pIt;
4504 edgePointSet.insert( point );
4505 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4507 edgePoints.push_back( point );
4508 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4509 point->myInitU = edgeLength;
4513 // treat points on the edge which ends up: compute U [0,1]
4514 edgePoints.push_back( point );
4515 if ( edgePoints.size() > 2 ) {
4516 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4517 list< TPoint* >::iterator epIt = edgePoints.begin();
4518 for ( ; epIt != edgePoints.end(); epIt++ )
4519 (*epIt)->myInitU /= edgeLength;
4521 // begin the next edge treatment
4524 if ( point != boundary->front() ) { // not the first key-point again
4525 getShapePoints( edgeID ).push_back( point );
4526 getShapePoints( vertexID++ ).push_back( point );
4532 // find in-face points
4533 list< TPoint* > & facePoints = getShapePoints( edgeID );
4534 vector< TPoint >::iterator pVecIt = myPoints.begin();
4535 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4536 TPoint* point = &(*pVecIt);
4537 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4538 pointsInElems.find( point ) != pointsInElems.end())
4539 facePoints.push_back( point );
4546 // bind points to shapes according to point parameters
4547 vector< TPoint >::iterator pVecIt = myPoints.begin();
4548 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4549 TPoint* point = &(*pVecIt);
4550 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4551 getShapePoints( shapeID ).push_back( point );
4552 // detect key-points
4553 if ( SMESH_Block::IsVertexID( shapeID ))
4554 myKeyPointIDs.push_back( i );
4558 myIsBoundaryPointsFound = true;
4559 return myIsBoundaryPointsFound;
4562 //=======================================================================
4564 //purpose : clear fields
4565 //=======================================================================
4567 void SMESH_Pattern::Clear()
4569 myIsComputed = myIsBoundaryPointsFound = false;
4572 myKeyPointIDs.clear();
4573 myElemPointIDs.clear();
4574 myShapeIDToPointsMap.clear();
4575 myShapeIDMap.Clear();
4577 myNbKeyPntInBoundary.clear();
4580 myElemXYZIDs.clear();
4581 myXYZIdToNodeMap.clear();
4583 myOrderedNodes.clear();
4584 myPolyElems.clear();
4585 myPolyElemXYZIDs.clear();
4586 myPolyhedronQuantities.clear();
4587 myIdsOnBoundary.clear();
4588 myReverseConnectivity.clear();
4591 //================================================================================
4593 * \brief set ErrorCode and return true if it is Ok
4595 //================================================================================
4597 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4599 myErrorCode = theErrorCode;
4600 return myErrorCode == ERR_OK;
4603 //=======================================================================
4604 //function : setShapeToMesh
4605 //purpose : set a shape to be meshed. Return True if meshing is possible
4606 //=======================================================================
4608 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4610 if ( !IsLoaded() ) {
4611 MESSAGE( "Pattern not loaded" );
4612 return setErrorCode( ERR_APPL_NOT_LOADED );
4615 TopAbs_ShapeEnum aType = theShape.ShapeType();
4616 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4618 MESSAGE( "Pattern dimention mismatch" );
4619 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4622 // check if a face is closed
4623 int nbNodeOnSeamEdge = 0;
4625 TopTools_MapOfShape seamVertices;
4626 TopoDS_Face face = TopoDS::Face( theShape );
4627 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4628 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4629 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4630 if ( BRep_Tool::IsClosed(ee, face) ) {
4631 // seam edge and vertices encounter twice in theFace
4632 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4633 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4638 // check nb of vertices
4639 TopTools_IndexedMapOfShape vMap;
4640 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4641 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4642 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4643 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4646 myElements.clear(); // not refine elements
4647 myElemXYZIDs.clear();
4649 myShapeIDMap.Clear();
4654 //=======================================================================
4655 //function : GetMappedPoints
4656 //purpose : Return nodes coordinates computed by Apply() method
4657 //=======================================================================
4659 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4662 if ( !myIsComputed )
4665 if ( myElements.empty() ) { // applied to shape
4666 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4667 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4668 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4670 else { // applied to mesh elements
4671 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4672 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4673 for ( ; xyz != myXYZ.end(); ++xyz )
4674 if ( !isDefined( *xyz ))
4675 thePoints.push_back( definedXYZ );
4677 thePoints.push_back( & (*xyz) );
4679 return !thePoints.empty();
4683 //=======================================================================
4684 //function : GetPoints
4685 //purpose : Return nodes coordinates of the pattern
4686 //=======================================================================
4688 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4695 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4696 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4697 thePoints.push_back( & (*pVecIt).myInitXYZ );
4699 return ( thePoints.size() > 0 );
4702 //=======================================================================
4703 //function : getShapePoints
4704 //purpose : return list of points located on theShape
4705 //=======================================================================
4707 list< SMESH_Pattern::TPoint* > &
4708 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4711 if ( !myShapeIDMap.Contains( theShape ))
4712 aShapeID = myShapeIDMap.Add( theShape );
4714 aShapeID = myShapeIDMap.FindIndex( theShape );
4716 return myShapeIDToPointsMap[ aShapeID ];
4719 //=======================================================================
4720 //function : getShapePoints
4721 //purpose : return list of points located on the shape
4722 //=======================================================================
4724 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4726 return myShapeIDToPointsMap[ theShapeID ];
4729 //=======================================================================
4730 //function : DumpPoints
4732 //=======================================================================
4734 void SMESH_Pattern::DumpPoints() const
4737 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4738 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4739 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4743 //=======================================================================
4744 //function : TPoint()
4746 //=======================================================================
4748 SMESH_Pattern::TPoint::TPoint()
4751 myInitXYZ.SetCoord(0,0,0);
4752 myInitUV.SetCoord(0.,0.);
4754 myXYZ.SetCoord(0,0,0);
4755 myUV.SetCoord(0.,0.);
4760 //=======================================================================
4761 //function : operator <<
4763 //=======================================================================
4765 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4767 gp_XYZ xyz = p.myInitXYZ;
4768 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4769 gp_XY xy = p.myInitUV;
4770 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4771 double u = p.myInitU;
4772 OS << " u( " << u << " )) " << &p << endl;
4773 xyz = p.myXYZ.XYZ();
4774 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4776 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4778 OS << " u( " << u << " ))" << endl;