1 // Copyright (C) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_Pattern.hxx
24 // Created : Mon Aug 2 10:30:00 2004
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_Pattern.hxx"
29 #include <BRepAdaptor_Curve.hxx>
30 #include <BRepTools.hxx>
31 #include <BRepTools_WireExplorer.hxx>
32 #include <BRep_Tool.hxx>
33 #include <Bnd_Box.hxx>
34 #include <Bnd_Box2d.hxx>
36 #include <Extrema_ExtPC.hxx>
37 #include <Extrema_GenExtPS.hxx>
38 #include <Extrema_POnSurf.hxx>
39 #include <Geom2d_Curve.hxx>
40 #include <GeomAdaptor_Surface.hxx>
41 #include <Geom_Curve.hxx>
42 #include <Geom_Surface.hxx>
43 #include <TopAbs_ShapeEnum.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopLoc_Location.hxx>
47 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TopoDS_Edge.hxx>
50 #include <TopoDS_Face.hxx>
51 #include <TopoDS_Iterator.hxx>
52 #include <TopoDS_Shell.hxx>
53 #include <TopoDS_Vertex.hxx>
54 #include <TopoDS_Wire.hxx>
56 #include <gp_Lin2d.hxx>
57 #include <gp_Pnt2d.hxx>
58 #include <gp_Trsf.hxx>
62 #include "SMDS_EdgePosition.hxx"
63 #include "SMDS_FacePosition.hxx"
64 #include "SMDS_MeshElement.hxx"
65 #include "SMDS_MeshFace.hxx"
66 #include "SMDS_MeshNode.hxx"
67 #include "SMDS_VolumeTool.hxx"
68 #include "SMESHDS_Group.hxx"
69 #include "SMESHDS_Mesh.hxx"
70 #include "SMESHDS_SubMesh.hxx"
71 #include "SMESH_Block.hxx"
72 #include "SMESH_Mesh.hxx"
73 #include "SMESH_MesherHelper.hxx"
74 #include "SMESH_subMesh.hxx"
76 #include <Basics_Utils.hxx>
77 #include "utilities.h"
81 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
83 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
85 //=======================================================================
86 //function : SMESH_Pattern
88 //=======================================================================
90 SMESH_Pattern::SMESH_Pattern ()
93 //=======================================================================
96 //=======================================================================
98 static inline int getInt( const char * theSring )
100 if ( *theSring < '0' || *theSring > '9' )
104 int val = strtol( theSring, &ptr, 10 );
105 if ( ptr == theSring ||
106 // there must not be neither '.' nor ',' nor 'E' ...
107 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
113 //=======================================================================
114 //function : getDouble
116 //=======================================================================
118 static inline double getDouble( const char * theSring )
121 return strtod( theSring, &ptr );
124 //=======================================================================
125 //function : readLine
126 //purpose : Put token starting positions in theFields until '\n' or '\0'
127 // Return the number of the found tokens
128 //=======================================================================
130 static int readLine (list <const char*> & theFields,
131 const char* & theLineBeg,
132 const bool theClearFields )
134 if ( theClearFields )
139 /* switch ( symbol ) { */
140 /* case white-space: */
141 /* look for a non-space symbol; */
142 /* case string-end: */
145 /* case comment beginning: */
146 /* skip all till a line-end; */
148 /* put its position in theFields, skip till a white-space;*/
154 bool stopReading = false;
157 bool isNumber = false;
158 switch ( *theLineBeg )
160 case ' ': // white space
165 case '\n': // a line ends
166 stopReading = ( nbRead > 0 );
171 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
175 case '\0': // file ends
178 case '-': // real number
183 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
185 theFields.push_back( theLineBeg );
188 while (*theLineBeg != ' ' &&
189 *theLineBeg != '\n' &&
190 *theLineBeg != '\0');
194 return 0; // incorrect file format
200 } while ( !stopReading );
205 //=======================================================================
207 //purpose : Load a pattern from <theFile>
208 //=======================================================================
210 bool SMESH_Pattern::Load (const char* theFileContents)
212 MESSAGE("Load( file ) ");
214 Kernel_Utils::Localizer loc;
218 // ! This is a comment
219 // NB_POINTS ! 1 integer - the number of points in the pattern.
220 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
221 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
223 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
224 // ! elements description goes after all
225 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
230 const char* lineBeg = theFileContents;
231 list <const char*> fields;
232 const bool clearFields = true;
234 // NB_POINTS ! 1 integer - the number of points in the pattern.
236 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
237 MESSAGE("Error reading NB_POINTS");
238 return setErrorCode( ERR_READ_NB_POINTS );
240 int nbPoints = getInt( fields.front() );
242 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
244 // read the first point coordinates to define pattern dimention
245 int dim = readLine( fields, lineBeg, clearFields );
251 MESSAGE("Error reading points: wrong nb of coordinates");
252 return setErrorCode( ERR_READ_POINT_COORDS );
254 if ( nbPoints <= dim ) {
255 MESSAGE(" Too few points ");
256 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
259 // read the rest points
261 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
262 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
263 MESSAGE("Error reading points : wrong nb of coordinates ");
264 return setErrorCode( ERR_READ_POINT_COORDS );
266 // store point coordinates
267 myPoints.resize( nbPoints );
268 list <const char*>::iterator fIt = fields.begin();
269 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
271 TPoint & p = myPoints[ iPoint ];
272 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
274 double coord = getDouble( *fIt );
275 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
276 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
278 return setErrorCode( ERR_READ_3D_COORD );
280 p.myInitXYZ.SetCoord( iCoord, coord );
282 p.myInitUV.SetCoord( iCoord, coord );
286 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
289 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
290 MESSAGE("Error: missing key-points");
292 return setErrorCode( ERR_READ_NO_KEYPOINT );
295 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
297 int pointIndex = getInt( *fIt );
298 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
299 MESSAGE("Error: invalid point index " << pointIndex );
301 return setErrorCode( ERR_READ_BAD_INDEX );
303 if ( idSet.insert( pointIndex ).second ) // unique?
304 myKeyPointIDs.push_back( pointIndex );
308 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
310 while ( readLine( fields, lineBeg, clearFields ))
312 myElemPointIDs.push_back( TElemDef() );
313 TElemDef& elemPoints = myElemPointIDs.back();
314 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
316 int pointIndex = getInt( *fIt );
317 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
318 MESSAGE("Error: invalid point index " << pointIndex );
320 return setErrorCode( ERR_READ_BAD_INDEX );
322 elemPoints.push_back( pointIndex );
324 // check the nb of nodes in element
326 switch ( elemPoints.size() ) {
327 case 3: if ( !myIs2D ) Ok = false; break;
331 case 8: if ( myIs2D ) Ok = false; break;
335 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
337 return setErrorCode( ERR_READ_ELEM_POINTS );
340 if ( myElemPointIDs.empty() ) {
341 MESSAGE("Error: no elements");
343 return setErrorCode( ERR_READ_NO_ELEMS );
346 findBoundaryPoints(); // sort key-points
348 return setErrorCode( ERR_OK );
351 //=======================================================================
353 //purpose : Save the loaded pattern into the file <theFileName>
354 //=======================================================================
356 bool SMESH_Pattern::Save (ostream& theFile)
358 MESSAGE(" ::Save(file) " );
360 Kernel_Utils::Localizer loc;
363 MESSAGE(" Pattern not loaded ");
364 return setErrorCode( ERR_SAVE_NOT_LOADED );
367 theFile << "!!! SALOME Mesh Pattern file" << endl;
368 theFile << "!!!" << endl;
369 theFile << "!!! Nb of points:" << endl;
370 theFile << myPoints.size() << endl;
374 // theFile.width( 8 );
375 // theFile.setf(ios::fixed);// use 123.45 floating notation
376 // theFile.setf(ios::right);
377 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
378 // theFile.setf(ios::showpoint); // do not show trailing zeros
379 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
380 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
381 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
382 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
383 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
384 theFile << " !- " << i << endl; // point id to ease reading by a human being
388 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
389 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
390 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
391 theFile << " " << *kpIt;
392 if ( !myKeyPointIDs.empty() )
396 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
397 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
398 for ( ; epIt != myElemPointIDs.end(); epIt++ )
400 const TElemDef & elemPoints = *epIt;
401 TElemDef::const_iterator iIt = elemPoints.begin();
402 for ( ; iIt != elemPoints.end(); iIt++ )
403 theFile << " " << *iIt;
409 return setErrorCode( ERR_OK );
412 //=======================================================================
413 //function : sortBySize
414 //purpose : sort theListOfList by size
415 //=======================================================================
417 template<typename T> struct TSizeCmp {
418 bool operator ()( const list < T > & l1, const list < T > & l2 )
419 const { return l1.size() < l2.size(); }
422 template<typename T> void sortBySize( list< list < T > > & theListOfList )
424 if ( theListOfList.size() > 2 ) {
425 TSizeCmp< T > SizeCmp;
426 theListOfList.sort( SizeCmp );
430 //=======================================================================
433 //=======================================================================
435 static gp_XY project (const SMDS_MeshNode* theNode,
436 Extrema_GenExtPS & theProjectorPS)
438 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
439 theProjectorPS.Perform( P );
440 if ( !theProjectorPS.IsDone() ) {
441 MESSAGE( "SMESH_Pattern: point projection FAILED");
444 double u, v, minVal = DBL_MAX;
445 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
446 if ( theProjectorPS.Value( i ) < minVal ) {
447 minVal = theProjectorPS.Value( i );
448 theProjectorPS.Point( i ).Parameter( u, v );
450 return gp_XY( u, v );
453 //=======================================================================
454 //function : areNodesBound
455 //purpose : true if all nodes of faces are bound to shapes
456 //=======================================================================
458 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
460 while ( faceItr->more() )
462 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
463 while ( nIt->more() )
465 const SMDS_MeshNode* node = smdsNode( nIt->next() );
466 SMDS_PositionPtr pos = node->GetPosition();
467 if ( !pos || !pos->GetShapeId() ) {
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 SMESH_MesherHelper helper( *theMesh );
519 helper.SetSubShape( theFace );
521 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
522 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
523 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
525 MESSAGE( "No elements bound to the face");
526 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
529 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
531 // check if face is closed
532 bool isClosed = helper.HasSeam();
534 list<TopoDS_Edge> eList;
535 list<TopoDS_Edge>::iterator elIt;
536 SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
538 // check that requested or needed projection is possible
539 bool isMainShape = theMesh->IsMainShape( face );
540 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
541 bool canProject = ( nbElems ? true : isMainShape );
543 canProject = false; // so far
545 if ( ( theProject || needProject ) && !canProject )
546 return setErrorCode( ERR_LOADF_CANT_PROJECT );
548 Extrema_GenExtPS projector;
549 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
550 if ( theProject || needProject )
551 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
554 TNodePointIDMap nodePointIDMap;
555 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
559 MESSAGE("Project the submesh");
560 // ---------------------------------------------------------------
561 // The case where the submesh is projected to theFace
562 // ---------------------------------------------------------------
565 list< const SMDS_MeshElement* > faces;
567 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
568 while ( fIt->more() ) {
569 const SMDS_MeshElement* f = fIt->next();
570 if ( f && f->GetType() == SMDSAbs_Face )
571 faces.push_back( f );
575 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
576 while ( fIt->more() )
577 faces.push_back( fIt->next() );
580 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
581 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
582 for ( ; fIt != faces.end(); ++fIt )
584 myElemPointIDs.push_back( TElemDef() );
585 TElemDef& elemPoints = myElemPointIDs.back();
586 SMDS_ElemIteratorPtr nIt = (*fIt)->nodesIterator();
587 while ( nIt->more() )
589 const SMDS_MeshElement* node = nIt->next();
590 TNodePointIDMap::iterator nIdIt = nodePointIDMap.find( node );
591 if ( nIdIt == nodePointIDMap.end() )
593 elemPoints.push_back( iPoint );
594 nodePointIDMap.insert( make_pair( node, iPoint++ ));
597 elemPoints.push_back( (*nIdIt).second );
600 myPoints.resize( iPoint );
602 // project all nodes of 2d elements to theFace
603 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
604 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
606 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
607 TPoint * p = & myPoints[ (*nIdIt).second ];
608 p->myInitUV = project( node, projector );
609 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
611 // find key-points: the points most close to UV of vertices
612 TopExp_Explorer vExp( face, TopAbs_VERTEX );
613 set<int> foundIndices;
614 for ( ; vExp.More(); vExp.Next() ) {
615 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
616 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
617 double minDist = DBL_MAX;
619 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
620 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
621 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
622 if ( dist < minDist ) {
627 if ( foundIndices.insert( index ).second ) // unique?
628 myKeyPointIDs.push_back( index );
630 myIsBoundaryPointsFound = false;
635 // ---------------------------------------------------------------------
636 // The case where a pattern is being made from the mesh built by mesher
637 // ---------------------------------------------------------------------
639 // Load shapes in the consequent order and count nb of points
642 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
643 int nbV = myShapeIDMap.Extent();
644 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
645 bool added = ( nbV < myShapeIDMap.Extent() );
646 if ( !added ) { // vertex encountered twice
647 // a seam vertex have two corresponding key points
648 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
651 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
652 nbNodes += eSubMesh->NbNodes() + 1;
655 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
656 myShapeIDMap.Add( *elIt );
658 myShapeIDMap.Add( face );
660 myPoints.resize( nbNodes );
662 // Load U of points on edges
664 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
666 TopoDS_Edge & edge = *elIt;
667 list< TPoint* > & ePoints = getShapePoints( edge );
669 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
670 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
672 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
673 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
674 // to make adjacent edges share key-point, we make v2 FORWARD too
675 // (as we have different points for same shape with different orienation)
678 // on closed face we must have REVERSED some of seam vertices
680 if ( helper.IsSeamShape( edge ) ) {
681 if ( helper.IsRealSeam( edge ) && !isForward ) {
682 // reverse on reversed SEAM edge
687 else { // on CLOSED edge (i.e. having one vertex with different orienations)
688 for ( int is2 = 0; is2 < 2; ++is2 ) {
689 TopoDS_Shape & v = is2 ? v2 : v1;
690 if ( helper.IsRealSeam( v ) ) {
691 // reverse or not depending on orientation of adjacent seam
693 list<TopoDS_Edge>::iterator eIt2 = elIt;
695 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
697 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
698 if ( seam.Orientation() == TopAbs_REVERSED )
705 // the forward key-point
706 list< TPoint* > * vPoint = & getShapePoints( v1 );
707 if ( vPoint->empty() )
709 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
710 if ( vSubMesh && vSubMesh->NbNodes() ) {
711 myKeyPointIDs.push_back( iPoint );
712 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
713 const SMDS_MeshNode* node = nIt->next();
714 if ( v1.Orientation() == TopAbs_REVERSED )
715 closeNodePointIDMap.insert( make_pair( node, iPoint ));
717 nodePointIDMap.insert( make_pair( node, iPoint ));
719 TPoint* keyPoint = &myPoints[ iPoint++ ];
720 vPoint->push_back( keyPoint );
722 keyPoint->myInitUV = project( node, projector );
724 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
725 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
728 if ( !vPoint->empty() )
729 ePoints.push_back( vPoint->front() );
732 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
733 if ( eSubMesh && eSubMesh->NbNodes() )
735 // loop on nodes of an edge: sort them by param on edge
736 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
737 TParamNodeMap paramNodeMap;
738 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
739 while ( nIt->more() )
741 const SMDS_MeshNode* node = smdsNode( nIt->next() );
742 const SMDS_EdgePosition* epos =
743 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
744 double u = epos->GetUParameter();
745 paramNodeMap.insert( make_pair( u, node ));
747 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
748 // wrong U on edge, project
750 BRepAdaptor_Curve aCurve( edge );
751 proj.Initialize( aCurve, f, l );
752 paramNodeMap.clear();
753 nIt = eSubMesh->GetNodes();
754 for ( int iNode = 0; nIt->more(); ++iNode ) {
755 const SMDS_MeshNode* node = smdsNode( nIt->next() );
756 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
758 if ( proj.IsDone() ) {
759 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
760 if ( proj.IsMin( i )) {
761 u = proj.Point( i ).Parameter();
765 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
767 paramNodeMap.insert( make_pair( u, node ));
770 // put U in [0,1] so that the first key-point has U==0
771 bool isSeam = helper.IsRealSeam( edge );
773 TParamNodeMap::iterator unIt = paramNodeMap.begin();
774 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
775 while ( unIt != paramNodeMap.end() )
777 TPoint* p = & myPoints[ iPoint ];
778 ePoints.push_back( p );
779 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
780 if ( isSeam && !isForward )
781 closeNodePointIDMap.insert( make_pair( node, iPoint ));
783 nodePointIDMap.insert ( make_pair( node, iPoint ));
786 p->myInitUV = project( node, projector );
788 double u = isForward ? (*unIt).first : (*unRIt).first;
789 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
790 p->myInitUV = C2d->Value( u ).XY();
792 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
797 // the reverse key-point
798 vPoint = & getShapePoints( v2 );
799 if ( vPoint->empty() )
801 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
802 if ( vSubMesh && vSubMesh->NbNodes() ) {
803 myKeyPointIDs.push_back( iPoint );
804 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
805 const SMDS_MeshNode* node = nIt->next();
806 if ( v2.Orientation() == TopAbs_REVERSED )
807 closeNodePointIDMap.insert( make_pair( node, iPoint ));
809 nodePointIDMap.insert( make_pair( node, iPoint ));
811 TPoint* keyPoint = &myPoints[ iPoint++ ];
812 vPoint->push_back( keyPoint );
814 keyPoint->myInitUV = project( node, projector );
816 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
817 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
820 if ( !vPoint->empty() )
821 ePoints.push_back( vPoint->front() );
823 // compute U of edge-points
826 double totalDist = 0;
827 list< TPoint* >::iterator pIt = ePoints.begin();
828 TPoint* prevP = *pIt;
829 prevP->myInitU = totalDist;
830 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
832 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
833 p->myInitU = totalDist;
836 if ( totalDist > DBL_MIN)
837 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
839 p->myInitU /= totalDist;
842 } // loop on edges of a wire
844 // Load in-face points and elements
846 if ( fSubMesh && fSubMesh->NbElements() )
848 list< TPoint* > & fPoints = getShapePoints( face );
849 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
850 while ( nIt->more() )
852 const SMDS_MeshNode* node = smdsNode( nIt->next() );
853 nodePointIDMap.insert( make_pair( node, iPoint ));
854 TPoint* p = &myPoints[ iPoint++ ];
855 fPoints.push_back( p );
857 p->myInitUV = project( node, projector );
859 const SMDS_FacePosition* pos =
860 static_cast<const SMDS_FacePosition*>(node->GetPosition().get());
861 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
863 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
866 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
867 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
868 while ( elemIt->more() )
870 const SMDS_MeshElement* elem = elemIt->next();
871 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
872 myElemPointIDs.push_back( TElemDef() );
873 TElemDef& elemPoints = myElemPointIDs.back();
874 // find point indices corresponding to element nodes
875 while ( nIt->more() )
877 const SMDS_MeshNode* node = smdsNode( nIt->next() );
878 iPoint = nodePointIDMap[ node ]; // point index of interest
879 // for a node on a seam edge there are two points
880 if ( helper.IsRealSeam( node->GetPosition()->GetShapeId() ) &&
881 ( n_id = closeNodePointIDMap.find( node )) != not_found )
883 TPoint & p1 = myPoints[ iPoint ];
884 TPoint & p2 = myPoints[ n_id->second ];
885 // Select point closest to the rest nodes of element in UV space
886 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
887 const SMDS_MeshNode* notSeamNode = 0;
888 // find node not on a seam edge
889 while ( nIt2->more() && !notSeamNode ) {
890 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
891 if ( !helper.IsSeamShape( n->GetPosition()->GetShapeId() ))
894 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
895 double dist1 = uv.SquareDistance( p1.myInitUV );
896 double dist2 = uv.SquareDistance( p2.myInitUV );
898 iPoint = n_id->second;
900 elemPoints.push_back( iPoint );
905 myIsBoundaryPointsFound = true;
908 // Assure that U range is proportional to V range
911 vector< TPoint >::iterator pVecIt = myPoints.begin();
912 for ( ; pVecIt != myPoints.end(); pVecIt++ )
913 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
914 double minU, minV, maxU, maxV;
915 bndBox.Get( minU, minV, maxU, maxV );
916 double dU = maxU - minU, dV = maxV - minV;
917 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
920 // define where is the problem, in the face or in the mesh
921 TopExp_Explorer vExp( face, TopAbs_VERTEX );
922 for ( ; vExp.More(); vExp.Next() ) {
923 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
926 bndBox.Get( minU, minV, maxU, maxV );
927 dU = maxU - minU, dV = maxV - minV;
928 if ( dU <= DBL_MIN || dV <= DBL_MIN )
930 return setErrorCode( ERR_LOADF_NARROW_FACE );
932 // mesh is projected onto a line, e.g.
933 return setErrorCode( ERR_LOADF_CANT_PROJECT );
935 double ratio = dU / dV, maxratio = 3, scale;
937 if ( ratio > maxratio ) {
938 scale = ratio / maxratio;
941 else if ( ratio < 1./maxratio ) {
942 scale = maxratio / ratio;
947 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
948 TPoint & p = *pVecIt;
949 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
950 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
953 if ( myElemPointIDs.empty() ) {
954 MESSAGE( "No elements bound to the face");
955 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
958 return setErrorCode( ERR_OK );
961 //=======================================================================
962 //function : computeUVOnEdge
963 //purpose : compute coordinates of points on theEdge
964 //=======================================================================
966 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
967 const list< TPoint* > & ePoints )
969 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
971 Handle(Geom2d_Curve) C2d =
972 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
974 ePoints.back()->myInitU = 1.0;
975 list< TPoint* >::const_iterator pIt = ePoints.begin();
976 for ( pIt++; pIt != ePoints.end(); pIt++ )
978 TPoint* point = *pIt;
980 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
981 point->myU = ( f * ( 1 - du ) + l * du );
983 point->myUV = C2d->Value( point->myU ).XY();
987 //=======================================================================
988 //function : intersectIsolines
990 //=======================================================================
992 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
993 const gp_XY& uv21, const gp_XY& uv22, const double r2,
997 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
998 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
999 resUV = 0.5 * ( loc1 + loc2 );
1000 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1001 // SKL 26.07.2007 for NPAL16567
1002 double d1 = (uv11-uv12).Modulus();
1003 double d2 = (uv21-uv22).Modulus();
1004 // double delta = d1*d2*1e-6; PAL17233
1005 double delta = min( d1, d2 ) / 10.;
1006 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1008 // double len1 = ( uv11 - uv12 ).Modulus();
1009 // double len2 = ( uv21 - uv22 ).Modulus();
1010 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1014 // gp_Lin2d line1( uv11, uv12 - uv11 );
1015 // gp_Lin2d line2( uv21, uv22 - uv21 );
1016 // double angle = Abs( line1.Angle( line2 ) );
1018 // IntAna2d_AnaIntersection inter;
1019 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1020 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1022 // gp_Pnt2d interUV = inter.Point(1).Value();
1023 // resUV += interUV.XY();
1024 // inter.Perform( line1, line2 );
1025 // interUV = inter.Point(1).Value();
1026 // resUV += interUV.XY();
1031 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1032 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1037 //=======================================================================
1038 //function : compUVByIsoIntersection
1040 //=======================================================================
1042 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1043 const gp_XY& theInitUV,
1045 bool & theIsDeformed )
1047 // compute UV by intersection of 2 iso lines
1048 //gp_Lin2d isoLine[2];
1049 gp_XY uv1[2], uv2[2];
1051 const double zero = DBL_MIN;
1052 for ( int iIso = 0; iIso < 2; iIso++ )
1054 // to build an iso line:
1055 // find 2 pairs of consequent edge-points such that the range of their
1056 // initial parameters encloses the in-face point initial parameter
1057 gp_XY UV[2], initUV[2];
1058 int nbUV = 0, iCoord = iIso + 1;
1059 double initParam = theInitUV.Coord( iCoord );
1061 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1062 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1064 const list< TPoint* > & bndPoints = * bndIt;
1065 TPoint* prevP = bndPoints.back(); // this is the first point
1066 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1067 bool coincPrev = false;
1068 // loop on the edge-points
1069 for ( ; pIt != bndPoints.end(); pIt++ )
1071 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1072 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1073 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1074 if (!coincPrev && // ignore if initParam coincides with prev point param
1075 sumOfDiff > zero && // ignore if both points coincide with initParam
1076 prevParamDiff * paramDiff <= zero )
1078 // find UV in parametric space of theFace
1079 double r = Abs(prevParamDiff) / sumOfDiff;
1080 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1083 // throw away uv most distant from <theInitUV>
1084 gp_XY vec0 = initUV[0] - theInitUV;
1085 gp_XY vec1 = initUV[1] - theInitUV;
1086 gp_XY vec = uvInit - theInitUV;
1087 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1088 double dist0 = vec0.SquareModulus();
1089 double dist1 = vec1.SquareModulus();
1090 double dist = vec .SquareModulus();
1091 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1092 i = ( dist0 < dist1 ? 1 : 0 );
1093 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1094 i = 3; // theInitUV must remain between
1098 initUV[ i ] = uvInit;
1099 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1101 coincPrev = ( Abs(paramDiff) <= zero );
1108 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1109 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1110 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1111 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1113 // an iso line should be normal to UV[0] - UV[1] direction
1114 // and be located at the same relative distance as from initial ends
1115 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1117 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1118 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1119 //isoLine[ iIso ] = iso.Normal( isoLoc );
1120 uv1[ iIso ] = UV[0];
1121 uv2[ iIso ] = UV[1];
1124 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1125 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1126 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1127 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1134 // ==========================================================
1135 // structure representing a node of a grid of iso-poly-lines
1136 // ==========================================================
1143 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1144 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1145 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1146 TIsoNode(double initU, double initV):
1147 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1148 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1149 bool IsUVComputed() const
1150 { return myUV.X() != 1e100; }
1151 bool IsMovable() const
1152 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1153 void SetNotMovable()
1154 { myIsMovable = false; }
1155 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1156 { myBndNodes[ iDir + i * 2 ] = node; }
1157 TIsoNode* GetBoundaryNode(int iDir, int i)
1158 { return myBndNodes[ iDir + i * 2 ]; }
1159 void SetNext(TIsoNode* node, int iDir, int isForward)
1160 { myNext[ iDir + isForward * 2 ] = node; }
1161 TIsoNode* GetNext(int iDir, int isForward)
1162 { return myNext[ iDir + isForward * 2 ]; }
1165 //=======================================================================
1166 //function : getNextNode
1168 //=======================================================================
1170 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1172 TIsoNode* n = node->myNext[ dir ];
1173 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1174 n = 0;//node->myBndNodes[ dir ];
1175 // MESSAGE("getNextNode: use bnd for node "<<
1176 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1180 //=======================================================================
1181 //function : checkQuads
1182 //purpose : check if newUV destortes quadrangles around node,
1183 // and if ( crit == FIX_OLD ) fix newUV in this case
1184 //=======================================================================
1186 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1188 static bool checkQuads (const TIsoNode* node,
1190 const bool reversed,
1191 const int crit = FIX_OLD,
1192 double fixSize = 0.)
1194 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1195 int nbOldFix = 0, nbOldImpr = 0;
1196 double newBadRate = 0, oldBadRate = 0;
1197 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1198 int i, dir1 = 0, dir2 = 3;
1199 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1201 if ( dir2 > 3 ) dir2 = 0;
1203 // walking counterclockwise around a quad,
1204 // nodes are in the order: node, n[0], n[1], n[2]
1205 n[0] = getNextNode( node, dir1 );
1206 n[2] = getNextNode( node, dir2 );
1207 if ( !n[0] || !n[2] ) continue;
1208 n[1] = getNextNode( n[0], dir2 );
1209 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1210 bool isTriangle = ( !n[1] );
1212 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1214 // if ( fixSize != 0 ) {
1215 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1216 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1217 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1218 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1220 // check if a quadrangle is degenerated
1222 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1223 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1226 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1229 // find min size of the diagonal node-n[1]
1230 double minDiag = fixSize;
1231 if ( minDiag == 0. ) {
1232 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1233 if ( !isTriangle ) {
1234 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1235 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1237 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1238 minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1241 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1242 // ( behind means "to the right of")
1244 // 1. newUV is not behind 01 and 12 dirs
1245 // 2. or newUV is not behind 02 dir and n[2] is convex
1246 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1247 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1248 gp_Vec2d moveVec[3], outVec[3];
1249 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1251 bool isDiag = ( i == 2 );
1252 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1256 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1258 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1260 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1262 gp_Vec2d newDir( n[i]->myUV, newUV );
1263 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1265 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1266 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1267 if ( crit == FIX_OLD ) {
1268 wasIn[i] = ( outDir * oldDir < 0 );
1269 wasOk[i] = ( outDir * oldDir < -minDiag );
1271 newBadRate += outDir * newDir;
1273 oldBadRate += outDir * oldDir;
1276 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1277 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1278 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1279 moveVec[i] = ( oldDist - minDiag ) * outDir;
1284 // check if n[2] is convex
1287 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1289 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1290 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1291 newIsOk = ( newIsOk && isNewOk );
1292 newIsIn = ( newIsIn && isNewIn );
1294 if ( crit != FIX_OLD ) {
1295 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1296 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1300 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1301 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1302 oldIsIn = ( oldIsIn && isOldIn );
1303 oldIsOk = ( oldIsOk && isOldIn );
1306 if ( !isOldIn ) { // node is outside a quadrangle
1307 // move newUV inside a quadrangle
1308 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1309 // node and newUV are outside: push newUV inside
1311 if ( convex || isTriangle ) {
1312 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1315 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1316 double outSize = out.Magnitude();
1317 if ( outSize > DBL_MIN )
1320 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1321 uv = n[1]->myUV - minDiag * out.XY();
1323 oldUVFixed[ nbOldFix++ ] = uv;
1324 //node->myUV = newUV;
1326 else if ( !isOldOk ) {
1327 // try to fix old UV: move node inside as less as possible
1328 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1329 gp_XY uv1, uv2 = node->myUV;
1330 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1332 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1333 while ( !isOldOk ) {
1334 // find the least moveVec
1336 double minMove2 = 1e100;
1337 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1339 if ( moveVec[i].Coord(1) < 1e100 ) {
1340 double move2 = moveVec[i].SquareMagnitude();
1341 if ( move2 < minMove2 ) {
1350 // move node to newUV
1351 uv1 = node->myUV + moveVec[ iMin ].XY();
1352 uv2 += moveVec[ iMin ].XY();
1353 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1354 // check if uv1 is ok
1355 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1356 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1357 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1359 oldUVImpr[ nbOldImpr++ ] = uv1;
1361 // check if uv2 is ok
1362 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1363 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1364 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1366 oldUVImpr[ nbOldImpr++ ] = uv2;
1371 } // loop on 4 quadrangles around <node>
1373 if ( crit == CHECK_NEW_OK )
1375 if ( crit == CHECK_NEW_IN )
1384 if ( oldIsIn && nbOldImpr ) {
1385 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1386 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1387 gp_XY uv = oldUVImpr[ 0 ];
1388 for ( int i = 1; i < nbOldImpr; i++ )
1389 uv += oldUVImpr[ i ];
1391 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1396 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1399 if ( !oldIsIn && nbOldFix ) {
1400 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1401 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1402 gp_XY uv = oldUVFixed[ 0 ];
1403 for ( int i = 1; i < nbOldFix; i++ )
1404 uv += oldUVFixed[ i ];
1406 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1411 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1414 if ( newIsIn && oldIsIn )
1415 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1416 else if ( !newIsIn )
1423 //=======================================================================
1424 //function : compUVByElasticIsolines
1425 //purpose : compute UV as nodes of iso-poly-lines consisting of
1426 // segments keeping relative size as in the pattern
1427 //=======================================================================
1428 //#define DEB_COMPUVBYELASTICISOLINES
1429 bool SMESH_Pattern::
1430 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1431 const list< TPoint* >& thePntToCompute)
1433 return false; // PAL17233
1434 //cout << "============================== KEY POINTS =============================="<<endl;
1435 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1436 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1437 // TPoint& p = myPoints[ *kpIt ];
1438 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1439 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1441 //cout << "=============================="<<endl;
1443 // Define parameters of iso-grid nodes in U and V dir
1445 set< double > paramSet[ 2 ];
1446 list< list< TPoint* > >::const_iterator pListIt;
1447 list< TPoint* >::const_iterator pIt;
1448 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1449 const list< TPoint* > & pList = * pListIt;
1450 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1451 paramSet[0].insert( (*pIt)->myInitUV.X() );
1452 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1455 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1456 paramSet[0].insert( (*pIt)->myInitUV.X() );
1457 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1459 // unite close parameters and split too long segments
1462 for ( iDir = 0; iDir < 2; iDir++ )
1464 set< double > & params = paramSet[ iDir ];
1465 double range = ( *params.rbegin() - *params.begin() );
1466 double toler = range / 1e6;
1467 tol[ iDir ] = toler;
1468 // double maxSegment = range / params.size() / 2.;
1470 // set< double >::iterator parIt = params.begin();
1471 // double prevPar = *parIt;
1472 // for ( parIt++; parIt != params.end(); parIt++ )
1474 // double segLen = (*parIt) - prevPar;
1475 // if ( segLen < toler )
1476 // ;//params.erase( prevPar ); // unite
1477 // else if ( segLen > maxSegment )
1478 // params.insert( prevPar + 0.5 * segLen ); // split
1479 // prevPar = (*parIt);
1483 // Make nodes of a grid of iso-poly-lines
1485 list < TIsoNode > nodes;
1486 typedef list < TIsoNode *> TIsoLine;
1487 map < double, TIsoLine > isoMap[ 2 ];
1489 set< double > & params0 = paramSet[ 0 ];
1490 set< double >::iterator par0It = params0.begin();
1491 for ( ; par0It != params0.end(); par0It++ )
1493 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1494 set< double > & params1 = paramSet[ 1 ];
1495 set< double >::iterator par1It = params1.begin();
1496 for ( ; par1It != params1.end(); par1It++ )
1498 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1499 isoLine0.push_back( & nodes.back() );
1500 isoMap[1][ *par1It ].push_back( & nodes.back() );
1504 // Compute intersections of boundaries with iso-lines:
1505 // only boundary nodes will have computed UV so far
1508 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1509 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1510 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1512 const list< TPoint* > & bndPoints = * bndIt;
1513 TPoint* prevP = bndPoints.back(); // this is the first point
1514 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1515 // loop on the edge-points
1516 for ( ; pIt != bndPoints.end(); pIt++ )
1518 TPoint* point = *pIt;
1519 for ( iDir = 0; iDir < 2; iDir++ )
1521 const int iCoord = iDir + 1;
1522 const int iOtherCoord = 2 - iDir;
1523 double par1 = prevP->myInitUV.Coord( iCoord );
1524 double par2 = point->myInitUV.Coord( iCoord );
1525 double parDif = par2 - par1;
1526 if ( Abs( parDif ) <= DBL_MIN )
1528 // find iso-lines intersecting a bounadry
1529 double toler = tol[ 1 - iDir ];
1530 double minPar = Min ( par1, par2 );
1531 double maxPar = Max ( par1, par2 );
1532 map < double, TIsoLine >& isos = isoMap[ iDir ];
1533 map < double, TIsoLine >::iterator isoIt = isos.begin();
1534 for ( ; isoIt != isos.end(); isoIt++ )
1536 double isoParam = (*isoIt).first;
1537 if ( isoParam < minPar || isoParam > maxPar )
1539 double r = ( isoParam - par1 ) / parDif;
1540 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1541 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1542 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1543 // find existing node with otherPar or insert a new one
1544 TIsoLine & isoLine = (*isoIt).second;
1546 TIsoLine::iterator nIt = isoLine.begin();
1547 for ( ; nIt != isoLine.end(); nIt++ ) {
1548 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1549 if ( nodePar >= otherPar )
1553 if ( Abs( nodePar - otherPar ) <= toler )
1554 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1556 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1557 node = & nodes.back();
1558 isoLine.insert( nIt, node );
1560 node->SetNotMovable();
1562 uvBnd.Add( gp_Pnt2d( uv ));
1563 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1565 gp_XY tgt( point->myUV - prevP->myUV );
1566 if ( ::IsEqual( r, 1. ))
1567 node->myDir[ 0 ] = tgt;
1568 else if ( ::IsEqual( r, 0. ))
1569 node->myDir[ 1 ] = tgt;
1571 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1572 // keep boundary nodes corresponding to boundary points
1573 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1574 if ( bndNodes.empty() || bndNodes.back() != node )
1575 bndNodes.push_back( node );
1576 } // loop on isolines
1577 } // loop on 2 directions
1579 } // loop on boundary points
1580 } // loop on boundaries
1582 // Define orientation
1584 // find the point with the least X
1585 double leastX = DBL_MAX;
1586 TIsoNode * leftNode;
1587 list < TIsoNode >::iterator nodeIt = nodes.begin();
1588 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1589 TIsoNode & node = *nodeIt;
1590 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1591 leastX = node.myUV.X();
1594 // if ( node.IsUVComputed() ) {
1595 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1596 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1597 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1598 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1601 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1602 //SCRUTE( reversed );
1604 // Prepare internal nodes:
1606 // 2. compute ratios
1607 // 3. find boundary nodes for each node
1608 // 4. remove nodes out of the boundary
1609 for ( iDir = 0; iDir < 2; iDir++ )
1611 const int iCoord = 2 - iDir; // coord changing along an isoline
1612 map < double, TIsoLine >& isos = isoMap[ iDir ];
1613 map < double, TIsoLine >::iterator isoIt = isos.begin();
1614 for ( ; isoIt != isos.end(); isoIt++ )
1616 TIsoLine & isoLine = (*isoIt).second;
1617 bool firstCompNodeFound = false;
1618 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1619 nPrevIt = nIt = nNextIt = isoLine.begin();
1621 nNextIt++; nNextIt++;
1622 while ( nIt != isoLine.end() )
1624 // 1. connect prev - cur
1625 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1626 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1627 firstCompNodeFound = true;
1628 lastCompNodePos = nPrevIt;
1630 if ( firstCompNodeFound ) {
1631 node->SetNext( prevNode, iDir, 0 );
1632 prevNode->SetNext( node, iDir, 1 );
1635 if ( nNextIt != isoLine.end() ) {
1636 double par1 = prevNode->myInitUV.Coord( iCoord );
1637 double par2 = node->myInitUV.Coord( iCoord );
1638 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1639 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1641 // 3. find boundary nodes
1642 if ( node->IsUVComputed() )
1643 lastCompNodePos = nIt;
1644 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1645 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1646 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1647 if ( (*nIt2)->IsUVComputed() )
1649 if ( nIt2 != isoLine.end() ) {
1651 node->SetBoundaryNode( bndNode1, iDir, 0 );
1652 node->SetBoundaryNode( bndNode2, iDir, 1 );
1653 // cout << "--------------------------------------------------"<<endl;
1654 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1655 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1656 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1657 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1658 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1659 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1662 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1663 node->SetBoundaryNode( 0, iDir, 0 );
1664 node->SetBoundaryNode( 0, iDir, 1 );
1668 if ( nNextIt != isoLine.end() ) nNextIt++;
1669 // 4. remove nodes out of the boundary
1670 if ( !firstCompNodeFound )
1671 isoLine.pop_front();
1672 } // loop on isoLine nodes
1674 // remove nodes after the boundary
1675 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1676 // (*nIt)->SetNotMovable();
1677 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1678 } // loop on isolines
1679 } // loop on 2 directions
1681 // Compute local isoline direction for internal nodes
1684 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1685 map < double, TIsoLine >::iterator isoIt = isos.begin();
1686 for ( ; isoIt != isos.end(); isoIt++ )
1688 TIsoLine & isoLine = (*isoIt).second;
1689 TIsoLine::iterator nIt = isoLine.begin();
1690 for ( ; nIt != isoLine.end(); nIt++ )
1692 TIsoNode* node = *nIt;
1693 if ( node->IsUVComputed() || !node->IsMovable() )
1695 gp_Vec2d aTgt[2], aNorm[2];
1698 for ( iDir = 0; iDir < 2; iDir++ )
1700 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1701 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1702 if ( !bndNode1 || !bndNode2 ) {
1706 const int iCoord = 2 - iDir; // coord changing along an isoline
1707 double par1 = bndNode1->myInitUV.Coord( iCoord );
1708 double par2 = node->myInitUV.Coord( iCoord );
1709 double par3 = bndNode2->myInitUV.Coord( iCoord );
1710 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1712 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1713 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1714 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1715 else tgt1.Reverse();
1716 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1718 if ( ratio[ iDir ] < 0.5 )
1719 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1721 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1723 aNorm[ iDir ].Reverse(); // along iDir isoline
1725 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1726 // maybe angle is more than |PI|
1727 if ( Abs( angle ) > PI / 2. ) {
1728 // check direction of the last but one perpendicular isoline
1729 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1730 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1731 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1732 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1733 if ( isoDir * tgt2 < 0 )
1735 double angle2 = tgt1.Angle( isoDir );
1736 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1737 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1738 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1739 //MESSAGE("REVERSE ANGLE");
1742 if ( Abs( angle2 ) > Abs( angle ) ||
1743 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1744 //MESSAGE("Add PI");
1745 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1746 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1747 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1748 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1749 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1750 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1753 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1757 for ( iDir = 0; iDir < 2; iDir++ )
1759 aTgt[iDir].Normalize();
1760 aNorm[1-iDir].Normalize();
1761 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1764 node->myDir[iDir] = //aTgt[iDir];
1765 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1767 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1768 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1769 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1770 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1772 } // loop on iso nodes
1773 } // loop on isolines
1775 // Find nodes to start computing UV from
1777 list< TIsoNode* > startNodes;
1778 list< TIsoNode* >::iterator nIt = bndNodes.end();
1779 TIsoNode* node = *(--nIt);
1780 TIsoNode* prevNode = *(--nIt);
1781 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1783 TIsoNode* nextNode = *nIt;
1784 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1785 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1786 double initAngle = initTgt1.Angle( initTgt2 );
1787 double angle = node->myDir[0].Angle( node->myDir[1] );
1788 if ( reversed ) angle = -angle;
1789 if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1790 // find a close internal node
1791 TIsoNode* nClose = 0;
1792 list< TIsoNode* > testNodes;
1793 testNodes.push_back( node );
1794 list< TIsoNode* >::iterator it = testNodes.begin();
1795 for ( ; !nClose && it != testNodes.end(); it++ )
1797 for (int i = 0; i < 4; i++ )
1799 nClose = (*it)->myNext[ i ];
1801 if ( !nClose->IsUVComputed() )
1804 testNodes.push_back( nClose );
1810 startNodes.push_back( nClose );
1811 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1812 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1813 // "initAngle: " << initAngle << " angle: " << angle << endl;
1814 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1815 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1816 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1817 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1823 // Compute starting UV of internal nodes
1825 list < TIsoNode* > internNodes;
1826 bool needIteration = true;
1827 if ( startNodes.empty() ) {
1828 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1829 needIteration = false;
1830 map < double, TIsoLine >& isos = isoMap[ 0 ];
1831 map < double, TIsoLine >::iterator isoIt = isos.begin();
1832 for ( ; isoIt != isos.end(); isoIt++ )
1834 TIsoLine & isoLine = (*isoIt).second;
1835 TIsoLine::iterator nIt = isoLine.begin();
1836 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1838 TIsoNode* node = *nIt;
1839 if ( !node->IsUVComputed() && node->IsMovable() ) {
1840 internNodes.push_back( node );
1842 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1843 node->myUV, needIteration ))
1844 node->myUV = node->myInitUV;
1848 if ( needIteration )
1849 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1851 TIsoNode* node = *nIt, *nClose = 0;
1852 list< TIsoNode* > testNodes;
1853 testNodes.push_back( node );
1854 list< TIsoNode* >::iterator it = testNodes.begin();
1855 for ( ; !nClose && it != testNodes.end(); it++ )
1857 for (int i = 0; i < 4; i++ )
1859 nClose = (*it)->myNext[ i ];
1861 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1864 testNodes.push_back( nClose );
1870 startNodes.push_back( nClose );
1874 double aMin[2], aMax[2], step[2];
1875 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1876 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1877 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1878 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1879 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1881 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1883 TIsoNode* prevN[2], *node = *nIt;
1884 if ( node->IsUVComputed() || !node->IsMovable() )
1886 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1887 int nbComp = 0, nbPrev = 0;
1888 for ( iDir = 0; iDir < 2; iDir++ )
1890 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1891 TIsoNode* n = node->GetNext( iDir, 0 );
1892 if ( n->IsUVComputed() )
1895 startNodes.push_back( n );
1896 n = node->GetNext( iDir, 1 );
1897 if ( n->IsUVComputed() )
1900 startNodes.push_back( n );
1902 prevNode1 = prevNode2;
1905 if ( prevNode1 ) nbPrev++;
1906 if ( prevNode2 ) nbPrev++;
1909 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1910 double par = node->myInitUV.Coord( 2 - iDir );
1911 bool isEnd = ( prevPar > par );
1912 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1913 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1914 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1916 MESSAGE("Why we are here?");
1919 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1920 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1921 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1922 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1923 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1924 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1925 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1926 //" par: " << prevPar << endl;
1927 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1928 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1930 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1931 gp_XY & uv1 = prevNode1->myUV;
1932 gp_XY & uv2 = prevNode2->myUV;
1933 // dir = ( uv2 - uv1 );
1934 // double len = dir.Modulus();
1935 // if ( len > DBL_MIN )
1936 // dir /= len * 0.5;
1937 double r = node->myRatio[ iDir ];
1938 newUV += uv1 * ( 1 - r ) + uv2 * r;
1941 newUV += prevNode1->myUV + dir * step[ iDir ];
1944 prevN[ iDir ] = prevNode1;
1948 if ( !nbComp ) continue;
1951 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1953 // check if a quadrangle is not distorted
1955 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1956 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1957 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1958 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1962 internNodes.push_back( node );
1967 static int maxNbIter = 100;
1968 #ifdef DEB_COMPUVBYELASTICISOLINES
1970 bool useNbMoveNode = 0;
1971 static int maxNbNodeMove = 100;
1974 if ( !useNbMoveNode )
1975 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1980 if ( !needIteration) break;
1981 #ifdef DEB_COMPUVBYELASTICISOLINES
1982 if ( nbIter >= maxNbIter ) break;
1985 list < TIsoNode* >::iterator nIt = internNodes.begin();
1986 for ( ; nIt != internNodes.end(); nIt++ ) {
1987 #ifdef DEB_COMPUVBYELASTICISOLINES
1989 cout << nbNodeMove <<" =================================================="<<endl;
1991 TIsoNode * node = *nIt;
1995 for ( iDir = 0; iDir < 2; iDir++ )
1997 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
1998 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
1999 double r = node->myRatio[ iDir ];
2000 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2001 // line[ iDir ].SetLocation( loc[ iDir ] );
2002 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2005 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2006 double locR[2] = { 0, 0 };
2007 for ( iDir = 0; iDir < 2; iDir++ )
2009 const int iCoord = 2 - iDir; // coord changing along an isoline
2010 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2011 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2012 if ( !bndNode1 || !bndNode2 ) {
2015 double par1 = bndNode1->myInitUV.Coord( iCoord );
2016 double par2 = node->myInitUV.Coord( iCoord );
2017 double par3 = bndNode2->myInitUV.Coord( iCoord );
2018 double r = ( par2 - par1 ) / ( par3 - par1 );
2019 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2020 locR[ iDir ] = ( 1 - r * r ) * 0.25;
2022 //locR[0] = locR[1] = 0.25;
2023 // intersect the 2 lines and move a node
2024 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2025 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2027 // double intR = 1 - locR[0] - locR[1];
2028 // gp_XY newUV = inter.Point(1).Value().XY();
2029 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2030 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2032 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2033 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2034 // avoid parallel isolines intersection
2035 checkQuads( node, newUV, reversed );
2037 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2039 } // intersection found
2040 #ifdef DEB_COMPUVBYELASTICISOLINES
2041 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2043 } // loop on internal nodes
2044 #ifdef DEB_COMPUVBYELASTICISOLINES
2045 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2047 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2049 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2051 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2052 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2053 #ifndef DEB_COMPUVBYELASTICISOLINES
2058 // Set computed UV to points
2060 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2061 TPoint* point = *pIt;
2062 //gp_XY oldUV = point->myUV;
2063 double minDist = DBL_MAX;
2064 list < TIsoNode >::iterator nIt = nodes.begin();
2065 for ( ; nIt != nodes.end(); nIt++ ) {
2066 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2067 if ( dist < minDist ) {
2069 point->myUV = (*nIt).myUV;
2078 //=======================================================================
2079 //function : setFirstEdge
2080 //purpose : choose the best first edge of theWire; return the summary distance
2081 // between point UV computed by isolines intersection and
2082 // eventual UV got from edge p-curves
2083 //=======================================================================
2085 //#define DBG_SETFIRSTEDGE
2086 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2088 int iE, nbEdges = theWire.size();
2092 // Transform UVs computed by iso to fit bnd box of a wire
2094 // max nb of points on an edge
2096 int eID = theFirstEdgeID;
2097 for ( iE = 0; iE < nbEdges; iE++ )
2098 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2100 // compute bnd boxes
2101 TopoDS_Face face = TopoDS::Face( myShape );
2102 Bnd_Box2d bndBox, eBndBox;
2103 eID = theFirstEdgeID;
2104 list< TopoDS_Edge >::iterator eIt;
2105 list< TPoint* >::iterator pIt;
2106 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2108 // UV by isos stored in TPoint.myXYZ
2109 list< TPoint* > & ePoints = getShapePoints( eID++ );
2110 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2112 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2114 // UV by an edge p-curve
2116 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2117 double dU = ( l - f ) / ( maxNbPnt - 1 );
2118 for ( int i = 0; i < maxNbPnt; i++ )
2119 eBndBox.Add( C2d->Value( f + i * dU ));
2122 // transform UVs by isos
2123 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2124 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2125 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2126 #ifdef DBG_SETFIRSTEDGE
2127 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2128 << eMinPar[1] << " - " << eMaxPar[1] );
2130 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2132 double dMin = eMinPar[i] - minPar[i];
2133 double dMax = eMaxPar[i] - maxPar[i];
2134 double dPar = maxPar[i] - minPar[i];
2135 eID = theFirstEdgeID;
2136 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2138 list< TPoint* > & ePoints = getShapePoints( eID++ );
2139 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2141 double par = (*pIt)->myXYZ.Coord( iC );
2142 double r = ( par - minPar[i] ) / dPar;
2143 par += ( 1 - r ) * dMin + r * dMax;
2144 (*pIt)->myXYZ.SetCoord( iC, par );
2150 double minDist = DBL_MAX;
2151 for ( iE = 0 ; iE < nbEdges; iE++ )
2153 #ifdef DBG_SETFIRSTEDGE
2154 MESSAGE ( " VARIANT " << iE );
2156 // evaluate the distance between UV computed by the 2 methods:
2157 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2159 int eID = theFirstEdgeID;
2160 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2162 list< TPoint* > & ePoints = getShapePoints( eID++ );
2163 computeUVOnEdge( *eIt, ePoints );
2164 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2166 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2167 #ifdef DBG_SETFIRSTEDGE
2168 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2169 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2173 #ifdef DBG_SETFIRSTEDGE
2174 MESSAGE ( "dist -- " << dist );
2176 if ( dist < minDist ) {
2178 eBest = theWire.front();
2180 // check variant with another first edge
2181 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2183 // put the best first edge to the theWire front
2184 if ( eBest != theWire.front() ) {
2185 eIt = find ( theWire.begin(), theWire.end(), eBest );
2186 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2192 //=======================================================================
2193 //function : sortSameSizeWires
2194 //purpose : sort wires in theWireList from theFromWire until theToWire,
2195 // the wires are set in the order to correspond to the order
2196 // of boundaries; after sorting, edges in the wires are put
2197 // in a good order, point UVs on edges are computed and points
2198 // are appended to theEdgesPointsList
2199 //=======================================================================
2201 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2202 const TListOfEdgesList::iterator& theFromWire,
2203 const TListOfEdgesList::iterator& theToWire,
2204 const int theFirstEdgeID,
2205 list< list< TPoint* > >& theEdgesPointsList )
2207 TopoDS_Face F = TopoDS::Face( myShape );
2208 int iW, nbWires = 0;
2209 TListOfEdgesList::iterator wlIt = theFromWire;
2210 while ( wlIt++ != theToWire )
2213 // Recompute key-point UVs by isolines intersection,
2214 // compute CG of key-points for each wire and bnd boxes of GCs
2217 gp_XY orig( gp::Origin2d().XY() );
2218 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2219 Bnd_Box2d bndBox, vBndBox;
2220 int eID = theFirstEdgeID;
2221 list< TopoDS_Edge >::iterator eIt;
2222 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2224 list< TopoDS_Edge > & wire = *wlIt;
2225 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2227 list< TPoint* > & ePoints = getShapePoints( eID++ );
2228 TPoint* p = ePoints.front();
2229 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2230 MESSAGE("cant sortSameSizeWires()");
2233 gcVec[iW] += p->myUV;
2234 bndBox.Add( gp_Pnt2d( p->myUV ));
2235 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2236 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2237 vGcVec[iW] += vXY.XY();
2239 // keep the computed UV to compare against by setFirstEdge()
2240 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2242 gcVec[iW] /= nbWires;
2243 vGcVec[iW] /= nbWires;
2244 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2245 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2248 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2250 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2251 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2252 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2253 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2255 double dMin = vMinPar[i] - minPar[i];
2256 double dMax = vMaxPar[i] - maxPar[i];
2257 double dPar = maxPar[i] - minPar[i];
2258 if ( Abs( dPar ) <= DBL_MIN )
2260 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2261 double par = gcVec[iW].Coord( iC );
2262 double r = ( par - minPar[i] ) / dPar;
2263 par += ( 1 - r ) * dMin + r * dMax;
2264 gcVec[iW].SetCoord( iC, par );
2268 // Define boundary - wire correspondence by GC closeness
2270 TListOfEdgesList tmpWList;
2271 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2272 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2273 TIntWirePosMap bndIndWirePosMap;
2274 vector< bool > bndFound( nbWires, false );
2275 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2277 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2278 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2279 double minDist = DBL_MAX;
2280 gp_XY & wGc = vGcVec[ iW ];
2282 for ( int iB = 0; iB < nbWires; iB++ ) {
2283 if ( bndFound[ iB ] ) continue;
2284 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2285 if ( dist < minDist ) {
2290 bndFound[ bIndex ] = true;
2291 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2296 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2297 eID = theFirstEdgeID;
2298 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2300 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2301 list < TopoDS_Edge > & wire = ( *wirePos );
2303 // choose the best first edge of a wire
2304 setFirstEdge( wire, eID );
2306 // compute eventual UV and fill theEdgesPointsList
2307 theEdgesPointsList.push_back( list< TPoint* >() );
2308 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2309 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2311 list< TPoint* > & ePoints = getShapePoints( eID++ );
2312 computeUVOnEdge( *eIt, ePoints );
2313 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2315 // put wire back to theWireList
2317 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2323 //=======================================================================
2325 //purpose : Compute nodes coordinates applying
2326 // the loaded pattern to <theFace>. The first key-point
2327 // will be mapped into <theVertexOnKeyPoint1>
2328 //=======================================================================
2330 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2331 const TopoDS_Vertex& theVertexOnKeyPoint1,
2332 const bool theReverse)
2334 MESSAGE(" ::Apply(face) " );
2335 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2336 if ( !setShapeToMesh( face ))
2339 // find points on edges, it fills myNbKeyPntInBoundary
2340 if ( !findBoundaryPoints() )
2343 // Define the edges order so that the first edge starts at
2344 // theVertexOnKeyPoint1
2346 list< TopoDS_Edge > eList;
2347 list< int > nbVertexInWires;
2348 int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2349 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2351 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2352 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2354 // check nb wires and edges
2355 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2356 l1.sort(); l2.sort();
2359 MESSAGE( "Wrong nb vertices in wires" );
2360 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2363 // here shapes get IDs, for the outer wire IDs are OK
2364 list<TopoDS_Edge>::iterator elIt = eList.begin();
2365 for ( ; elIt != eList.end(); elIt++ ) {
2366 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2367 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2368 // BEGIN: jfa for bug 0019943
2371 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2372 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2374 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2375 if (we.Current().IsSame(*elIt)) {
2377 if (nbe == 2) isClosed1 = true;
2382 // END: jfa for bug 0019943
2384 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2386 int nbVertices = myShapeIDMap.Extent();
2388 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2389 myShapeIDMap.Add( *elIt );
2391 myShapeIDMap.Add( face );
2393 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2394 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2395 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2398 // points on edges to be used for UV computation of in-face points
2399 list< list< TPoint* > > edgesPointsList;
2400 edgesPointsList.push_back( list< TPoint* >() );
2401 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2402 list< TPoint* >::iterator pIt;
2404 // compute UV of points on the outer wire
2405 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2406 for (iE = 0, elIt = eList.begin();
2407 iE < nbEdgesInOuterWire && elIt != eList.end();
2410 list< TPoint* > & ePoints = getShapePoints( *elIt );
2412 computeUVOnEdge( *elIt, ePoints );
2413 // collect on-edge points (excluding the last one)
2414 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2417 // If there are several wires, define the order of edges of inner wires:
2418 // compute UV of inner edge-points using 2 methods: the one for in-face points
2419 // and the one for on-edge points and then choose the best edge order
2420 // by the best correspondance of the 2 results
2423 // compute UV of inner edge-points using the method for in-face points
2424 // and devide eList into a list of separate wires
2426 list< list< TopoDS_Edge > > wireList;
2427 list<TopoDS_Edge>::iterator eIt = elIt;
2428 list<int>::iterator nbEIt = nbVertexInWires.begin();
2429 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2431 int nbEdges = *nbEIt;
2432 wireList.push_back( list< TopoDS_Edge >() );
2433 list< TopoDS_Edge > & wire = wireList.back();
2434 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2436 list< TPoint* > & ePoints = getShapePoints( *eIt );
2437 pIt = ePoints.begin();
2438 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2440 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2441 MESSAGE("cant Apply(face)");
2444 // keep the computed UV to compare against by setFirstEdge()
2445 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2447 wire.push_back( *eIt );
2450 // remove inner edges from eList
2451 eList.erase( elIt, eList.end() );
2453 // sort wireList by nb edges in a wire
2454 sortBySize< TopoDS_Edge > ( wireList );
2456 // an ID of the first edge of a boundary
2457 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2458 // if ( nbSeamShapes > 0 )
2459 // id1 += 2; // 2 vertices more
2461 // find points - edge correspondence for wires of unique size,
2462 // edge order within a wire should be defined only
2464 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2465 while ( wlIt != wireList.end() )
2467 list< TopoDS_Edge >& wire = (*wlIt);
2468 int nbEdges = wire.size();
2470 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2472 // choose the best first edge of a wire
2473 setFirstEdge( wire, id1 );
2475 // compute eventual UV and collect on-edge points
2476 edgesPointsList.push_back( list< TPoint* >() );
2477 edgesPoints = & edgesPointsList.back();
2479 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2481 list< TPoint* > & ePoints = getShapePoints( eID++ );
2482 computeUVOnEdge( *eIt, ePoints );
2483 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2489 // find boundary - wire correspondence for several wires of same size
2491 id1 = nbVertices + nbEdgesInOuterWire + 1;
2492 wlIt = wireList.begin();
2493 while ( wlIt != wireList.end() )
2495 int nbSameSize = 0, nbEdges = (*wlIt).size();
2496 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2498 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2502 if ( nbSameSize > 0 )
2503 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2506 id1 += nbEdges * ( nbSameSize + 1 );
2509 // add well-ordered edges to eList
2511 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2513 list< TopoDS_Edge >& wire = (*wlIt);
2514 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2517 // re-fill myShapeIDMap - all shapes get good IDs
2519 myShapeIDMap.Clear();
2520 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2521 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2522 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2523 myShapeIDMap.Add( *elIt );
2524 myShapeIDMap.Add( face );
2526 } // there are inner wires
2528 // Compute XYZ of on-edge points
2530 TopLoc_Location loc;
2531 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2533 BRepAdaptor_Curve C3d( *elIt );
2534 list< TPoint* > & ePoints = getShapePoints( iE++ );
2535 pIt = ePoints.begin();
2536 for ( pIt++; pIt != ePoints.end(); pIt++ )
2538 TPoint* point = *pIt;
2539 point->myXYZ = C3d.Value( point->myU );
2543 // Compute UV and XYZ of in-face points
2545 // try to use a simple algo
2546 list< TPoint* > & fPoints = getShapePoints( face );
2547 bool isDeformed = false;
2548 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2549 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2550 (*pIt)->myUV, isDeformed )) {
2551 MESSAGE("cant Apply(face)");
2554 // try to use a complex algo if it is a difficult case
2555 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2557 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2558 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2559 (*pIt)->myUV, isDeformed )) {
2560 MESSAGE("cant Apply(face)");
2565 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2566 const gp_Trsf & aTrsf = loc.Transformation();
2567 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2569 TPoint * point = *pIt;
2570 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2571 if ( !loc.IsIdentity() )
2572 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2575 myIsComputed = true;
2577 return setErrorCode( ERR_OK );
2580 //=======================================================================
2582 //purpose : Compute nodes coordinates applying
2583 // the loaded pattern to <theFace>. The first key-point
2584 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2585 //=======================================================================
2587 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2588 const int theNodeIndexOnKeyPoint1,
2589 const bool theReverse)
2591 // MESSAGE(" ::Apply(MeshFace) " );
2593 if ( !IsLoaded() ) {
2594 MESSAGE( "Pattern not loaded" );
2595 return setErrorCode( ERR_APPL_NOT_LOADED );
2598 // check nb of nodes
2599 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2600 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2601 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2604 // find points on edges, it fills myNbKeyPntInBoundary
2605 if ( !findBoundaryPoints() )
2608 // check that there are no holes in a pattern
2609 if (myNbKeyPntInBoundary.size() > 1 ) {
2610 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2613 // Define the nodes order
2615 list< const SMDS_MeshNode* > nodes;
2616 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2617 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2619 while ( noIt->more() ) {
2620 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2621 nodes.push_back( node );
2622 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2625 if ( n != nodes.end() ) {
2627 if ( n != --nodes.end() )
2628 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2631 else if ( n != nodes.begin() )
2632 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2634 list< gp_XYZ > xyzList;
2635 myOrderedNodes.resize( theFace->NbNodes() );
2636 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2637 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2638 myOrderedNodes[ iSub++] = *n;
2641 // Define a face plane
2643 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2644 gp_Pnt P ( *xyzIt++ );
2645 gp_Vec Vx( P, *xyzIt++ ), N;
2647 N = Vx ^ gp_Vec( P, *xyzIt++ );
2648 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2649 if ( N.SquareMagnitude() <= DBL_MIN )
2650 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2651 gp_Ax2 pos( P, N, Vx );
2653 // Compute UV of key-points on a plane
2654 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2656 gp_Vec vec ( pos.Location(), *xyzIt );
2657 TPoint* p = getShapePoints( iSub ).front();
2658 p->myUV.SetX( vec * pos.XDirection() );
2659 p->myUV.SetY( vec * pos.YDirection() );
2663 // points on edges to be used for UV computation of in-face points
2664 list< list< TPoint* > > edgesPointsList;
2665 edgesPointsList.push_back( list< TPoint* >() );
2666 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2667 list< TPoint* >::iterator pIt;
2669 // compute UV and XYZ of points on edges
2671 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2673 gp_XYZ& xyz1 = *xyzIt++;
2674 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2676 list< TPoint* > & ePoints = getShapePoints( iSub );
2677 ePoints.back()->myInitU = 1.0;
2678 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2679 while ( *pIt != ePoints.back() )
2682 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2683 gp_Vec vec ( pos.Location(), p->myXYZ );
2684 p->myUV.SetX( vec * pos.XDirection() );
2685 p->myUV.SetY( vec * pos.YDirection() );
2687 // collect on-edge points (excluding the last one)
2688 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2691 // Compute UV and XYZ of in-face points
2693 // try to use a simple algo to compute UV
2694 list< TPoint* > & fPoints = getShapePoints( iSub );
2695 bool isDeformed = false;
2696 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2697 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2698 (*pIt)->myUV, isDeformed )) {
2699 MESSAGE("cant Apply(face)");
2702 // try to use a complex algo if it is a difficult case
2703 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2705 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2706 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2707 (*pIt)->myUV, isDeformed )) {
2708 MESSAGE("cant Apply(face)");
2713 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2715 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2718 myIsComputed = true;
2720 return setErrorCode( ERR_OK );
2723 //=======================================================================
2725 //purpose : Compute nodes coordinates applying
2726 // the loaded pattern to <theFace>. The first key-point
2727 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2728 //=======================================================================
2730 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2731 const SMDS_MeshFace* theFace,
2732 const TopoDS_Shape& theSurface,
2733 const int theNodeIndexOnKeyPoint1,
2734 const bool theReverse)
2736 // MESSAGE(" ::Apply(MeshFace) " );
2737 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2738 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2740 const TopoDS_Face& face = TopoDS::Face( theSurface );
2741 TopLoc_Location loc;
2742 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2743 const gp_Trsf & aTrsf = loc.Transformation();
2745 if ( !IsLoaded() ) {
2746 MESSAGE( "Pattern not loaded" );
2747 return setErrorCode( ERR_APPL_NOT_LOADED );
2750 // check nb of nodes
2751 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2752 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2753 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2756 // find points on edges, it fills myNbKeyPntInBoundary
2757 if ( !findBoundaryPoints() )
2760 // check that there are no holes in a pattern
2761 if (myNbKeyPntInBoundary.size() > 1 ) {
2762 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2765 // Define the nodes order
2767 list< const SMDS_MeshNode* > nodes;
2768 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2769 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2771 while ( noIt->more() ) {
2772 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2773 nodes.push_back( node );
2774 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2777 if ( n != nodes.end() ) {
2779 if ( n != --nodes.end() )
2780 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2783 else if ( n != nodes.begin() )
2784 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2787 // find a node not on a seam edge, if necessary
2788 SMESH_MesherHelper helper( *theMesh );
2789 helper.SetSubShape( theSurface );
2790 const SMDS_MeshNode* inFaceNode = 0;
2791 if ( helper.GetNodeUVneedInFaceNode() )
2793 SMESH_MeshEditor editor( theMesh );
2794 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2795 int shapeID = editor.FindShape( *n );
2797 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2798 if ( !helper.IsSeamShape( shapeID ))
2803 // Set UV of key-points (i.e. of nodes of theFace )
2804 vector< gp_XY > keyUV( theFace->NbNodes() );
2805 myOrderedNodes.resize( theFace->NbNodes() );
2806 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2808 TPoint* p = getShapePoints( iSub ).front();
2809 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2810 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2812 keyUV[ iSub-1 ] = p->myUV;
2813 myOrderedNodes[ iSub-1 ] = *n;
2816 // points on edges to be used for UV computation of in-face points
2817 list< list< TPoint* > > edgesPointsList;
2818 edgesPointsList.push_back( list< TPoint* >() );
2819 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2820 list< TPoint* >::iterator pIt;
2822 // compute UV and XYZ of points on edges
2824 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2826 gp_XY& uv1 = keyUV[ i ];
2827 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2829 list< TPoint* > & ePoints = getShapePoints( iSub );
2830 ePoints.back()->myInitU = 1.0;
2831 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2832 while ( *pIt != ePoints.back() )
2835 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2836 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2837 if ( !loc.IsIdentity() )
2838 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2840 // collect on-edge points (excluding the last one)
2841 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2844 // Compute UV and XYZ of in-face points
2846 // try to use a simple algo to compute UV
2847 list< TPoint* > & fPoints = getShapePoints( iSub );
2848 bool isDeformed = false;
2849 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2850 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2851 (*pIt)->myUV, isDeformed )) {
2852 MESSAGE("cant Apply(face)");
2855 // try to use a complex algo if it is a difficult case
2856 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2858 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2859 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2860 (*pIt)->myUV, isDeformed )) {
2861 MESSAGE("cant Apply(face)");
2866 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2868 TPoint * point = *pIt;
2869 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2870 if ( !loc.IsIdentity() )
2871 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2874 myIsComputed = true;
2876 return setErrorCode( ERR_OK );
2879 //=======================================================================
2880 //function : undefinedXYZ
2882 //=======================================================================
2884 static const gp_XYZ& undefinedXYZ()
2886 static gp_XYZ xyz( 1.e100, 0., 0. );
2890 //=======================================================================
2891 //function : isDefined
2893 //=======================================================================
2895 inline static bool isDefined(const gp_XYZ& theXYZ)
2897 return theXYZ.X() < 1.e100;
2900 //=======================================================================
2902 //purpose : Compute nodes coordinates applying
2903 // the loaded pattern to <theFaces>. The first key-point
2904 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2905 //=======================================================================
2907 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2908 std::set<const SMDS_MeshFace*>& theFaces,
2909 const int theNodeIndexOnKeyPoint1,
2910 const bool theReverse)
2912 MESSAGE(" ::Apply(set<MeshFace>) " );
2914 if ( !IsLoaded() ) {
2915 MESSAGE( "Pattern not loaded" );
2916 return setErrorCode( ERR_APPL_NOT_LOADED );
2919 // find points on edges, it fills myNbKeyPntInBoundary
2920 if ( !findBoundaryPoints() )
2923 // check that there are no holes in a pattern
2924 if (myNbKeyPntInBoundary.size() > 1 ) {
2925 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2930 myElemXYZIDs.clear();
2931 myXYZIdToNodeMap.clear();
2933 myIdsOnBoundary.clear();
2934 myReverseConnectivity.clear();
2936 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2937 myElements.reserve( theFaces.size() );
2939 // to find point index
2940 map< TPoint*, int > pointIndex;
2941 for ( int i = 0; i < myPoints.size(); i++ )
2942 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2944 int ind1 = 0; // lowest point index for a face
2949 // SMESH_MeshEditor editor( theMesh );
2951 // apply to each face in theFaces set
2952 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2953 for ( ; face != theFaces.end(); ++face )
2955 // int curShapeId = editor.FindShape( *face );
2956 // if ( curShapeId != shapeID ) {
2957 // if ( curShapeId )
2958 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2961 // shapeID = curShapeId;
2964 if ( shape.IsNull() )
2965 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2967 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2969 MESSAGE( "Failed on " << *face );
2972 myElements.push_back( *face );
2974 // store computed points belonging to elements
2975 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2976 for ( ; ll != myElemPointIDs.end(); ++ll )
2978 myElemXYZIDs.push_back(TElemDef());
2979 TElemDef& xyzIds = myElemXYZIDs.back();
2980 TElemDef& pIds = *ll;
2981 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
2982 int pIndex = *id + ind1;
2983 xyzIds.push_back( pIndex );
2984 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
2985 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
2988 // put points on links to myIdsOnBoundary,
2989 // they will be used to sew new elements on adjacent refined elements
2990 int nbNodes = (*face)->NbNodes(), eID = nbNodes + 1;
2991 for ( int i = 0; i < nbNodes; i++ )
2993 list< TPoint* > & linkPoints = getShapePoints( eID++ );
2994 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
2995 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
2996 // make a link and a node set
2997 TNodeSet linkSet, node1Set;
2998 linkSet.insert( n1 );
2999 linkSet.insert( n2 );
3000 node1Set.insert( n1 );
3001 list< TPoint* >::iterator p = linkPoints.begin();
3003 // map the first link point to n1
3004 int nId = pointIndex[ *p ] + ind1;
3005 myXYZIdToNodeMap[ nId ] = n1;
3006 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3007 groups.push_back(list< int > ());
3008 groups.back().push_back( nId );
3010 // add the linkSet to the map
3011 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3012 groups.push_back(list< int > ());
3013 list< int >& indList = groups.back();
3014 // add points to the map excluding the end points
3015 for ( p++; *p != linkPoints.back(); p++ )
3016 indList.push_back( pointIndex[ *p ] + ind1 );
3018 ind1 += myPoints.size();
3021 return !myElemXYZIDs.empty();
3024 //=======================================================================
3026 //purpose : Compute nodes coordinates applying
3027 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3028 // will be mapped into <theNode000Index>-th node. The
3029 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3031 //=======================================================================
3033 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3034 const int theNode000Index,
3035 const int theNode001Index)
3037 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3039 if ( !IsLoaded() ) {
3040 MESSAGE( "Pattern not loaded" );
3041 return setErrorCode( ERR_APPL_NOT_LOADED );
3044 // bind ID to points
3045 if ( !findBoundaryPoints() )
3048 // check that there are no holes in a pattern
3049 if (myNbKeyPntInBoundary.size() > 1 ) {
3050 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3055 myElemXYZIDs.clear();
3056 myXYZIdToNodeMap.clear();
3058 myIdsOnBoundary.clear();
3059 myReverseConnectivity.clear();
3061 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3062 myElements.reserve( theVolumes.size() );
3064 // to find point index
3065 map< TPoint*, int > pointIndex;
3066 for ( int i = 0; i < myPoints.size(); i++ )
3067 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3069 int ind1 = 0; // lowest point index for an element
3071 // apply to each element in theVolumes set
3072 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3073 for ( ; vol != theVolumes.end(); ++vol )
3075 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3076 MESSAGE( "Failed on " << *vol );
3079 myElements.push_back( *vol );
3081 // store computed points belonging to elements
3082 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3083 for ( ; ll != myElemPointIDs.end(); ++ll )
3085 myElemXYZIDs.push_back(TElemDef());
3086 TElemDef& xyzIds = myElemXYZIDs.back();
3087 TElemDef& pIds = *ll;
3088 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3089 int pIndex = *id + ind1;
3090 xyzIds.push_back( pIndex );
3091 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3092 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3095 // put points on edges and faces to myIdsOnBoundary,
3096 // they will be used to sew new elements on adjacent refined elements
3097 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3099 // make a set of sub-points
3101 vector< int > subIDs;
3102 if ( SMESH_Block::IsVertexID( Id )) {
3103 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3105 else if ( SMESH_Block::IsEdgeID( Id )) {
3106 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3107 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3108 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3111 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3112 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3113 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3114 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3115 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3116 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3117 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3118 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3121 list< TPoint* > & points = getShapePoints( Id );
3122 list< TPoint* >::iterator p = points.begin();
3123 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3124 groups.push_back(list< int > ());
3125 list< int >& indList = groups.back();
3126 for ( ; p != points.end(); p++ )
3127 indList.push_back( pointIndex[ *p ] + ind1 );
3128 if ( subNodes.size() == 1 ) // vertex case
3129 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3131 ind1 += myPoints.size();
3134 return !myElemXYZIDs.empty();
3137 //=======================================================================
3139 //purpose : Create a pattern from the mesh built on <theBlock>
3140 //=======================================================================
3142 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3143 const TopoDS_Shell& theBlock)
3145 MESSAGE(" ::Load(volume) " );
3148 SMESHDS_SubMesh * aSubMesh;
3150 // load shapes in myShapeIDMap
3152 TopoDS_Vertex v1, v2;
3153 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3154 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3157 int nbNodes = 0, shapeID;
3158 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3160 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3161 aSubMesh = getSubmeshWithElements( theMesh, S );
3163 nbNodes += aSubMesh->NbNodes();
3165 myPoints.resize( nbNodes );
3167 // load U of points on edges
3168 TNodePointIDMap nodePointIDMap;
3170 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3172 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3173 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3174 aSubMesh = getSubmeshWithElements( theMesh, S );
3175 if ( ! aSubMesh ) continue;
3176 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3177 if ( !nIt->more() ) continue;
3179 // store a node and a point
3180 while ( nIt->more() ) {
3181 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3182 nodePointIDMap.insert( make_pair( node, iPoint ));
3183 if ( block.IsVertexID( shapeID ))
3184 myKeyPointIDs.push_back( iPoint );
3185 TPoint* p = & myPoints[ iPoint++ ];
3186 shapePoints.push_back( p );
3187 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3188 p->myInitXYZ.SetCoord( 0,0,0 );
3190 list< TPoint* >::iterator pIt = shapePoints.begin();
3193 switch ( S.ShapeType() )
3198 for ( ; pIt != shapePoints.end(); pIt++ ) {
3199 double * coef = block.GetShapeCoef( shapeID );
3200 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3201 if ( coef[ iCoord - 1] > 0 )
3202 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3204 if ( S.ShapeType() == TopAbs_VERTEX )
3207 const TopoDS_Edge& edge = TopoDS::Edge( S );
3209 BRep_Tool::Range( edge, f, l );
3210 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3211 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3212 pIt = shapePoints.begin();
3213 nIt = aSubMesh->GetNodes();
3214 for ( ; nIt->more(); pIt++ )
3216 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3217 const SMDS_EdgePosition* epos =
3218 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
3219 double u = ( epos->GetUParameter() - f ) / ( l - f );
3220 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3225 for ( ; pIt != shapePoints.end(); pIt++ )
3227 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3228 MESSAGE( "!block.ComputeParameters()" );
3229 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3233 } // loop on block sub-shapes
3237 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3240 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3241 while ( elemIt->more() ) {
3242 SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
3243 myElemPointIDs.push_back( TElemDef() );
3244 TElemDef& elemPoints = myElemPointIDs.back();
3245 while ( nIt->more() )
3246 elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
3250 myIsBoundaryPointsFound = true;
3252 return setErrorCode( ERR_OK );
3255 //=======================================================================
3256 //function : getSubmeshWithElements
3257 //purpose : return submesh containing elements bound to theBlock in theMesh
3258 //=======================================================================
3260 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3261 const TopoDS_Shape& theShape)
3263 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3264 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3267 if ( theShape.ShapeType() == TopAbs_SHELL )
3269 // look for submesh of VOLUME
3270 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3271 for (; it.More(); it.Next()) {
3272 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3273 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3281 //=======================================================================
3283 //purpose : Compute nodes coordinates applying
3284 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3285 // will be mapped into <theVertex000>. The (0,0,1)
3286 // fifth key-point will be mapped into <theVertex001>.
3287 //=======================================================================
3289 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3290 const TopoDS_Vertex& theVertex000,
3291 const TopoDS_Vertex& theVertex001)
3293 MESSAGE(" ::Apply(volume) " );
3295 if (!findBoundaryPoints() || // bind ID to points
3296 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3299 SMESH_Block block; // bind ID to shape
3300 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3301 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3303 // compute XYZ of points on shapes
3305 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3307 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3308 list< TPoint* >::iterator pIt = shapePoints.begin();
3309 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3310 switch ( S.ShapeType() )
3312 case TopAbs_VERTEX: {
3314 for ( ; pIt != shapePoints.end(); pIt++ )
3315 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3320 for ( ; pIt != shapePoints.end(); pIt++ )
3321 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3326 for ( ; pIt != shapePoints.end(); pIt++ )
3327 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3331 for ( ; pIt != shapePoints.end(); pIt++ )
3332 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3334 } // loop on block sub-shapes
3336 myIsComputed = true;
3338 return setErrorCode( ERR_OK );
3341 //=======================================================================
3343 //purpose : Compute nodes coordinates applying
3344 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3345 // will be mapped into <theNode000Index>-th node. The
3346 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3348 //=======================================================================
3350 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3351 const int theNode000Index,
3352 const int theNode001Index)
3354 //MESSAGE(" ::Apply(MeshVolume) " );
3356 if (!findBoundaryPoints()) // bind ID to points
3359 SMESH_Block block; // bind ID to shape
3360 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3361 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3362 // compute XYZ of points on shapes
3364 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3366 list< TPoint* > & shapePoints = getShapePoints( ID );
3367 list< TPoint* >::iterator pIt = shapePoints.begin();
3369 if ( block.IsVertexID( ID ))
3370 for ( ; pIt != shapePoints.end(); pIt++ ) {
3371 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3373 else if ( block.IsEdgeID( ID ))
3374 for ( ; pIt != shapePoints.end(); pIt++ ) {
3375 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3377 else if ( block.IsFaceID( ID ))
3378 for ( ; pIt != shapePoints.end(); pIt++ ) {
3379 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3382 for ( ; pIt != shapePoints.end(); pIt++ )
3383 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3384 } // loop on block sub-shapes
3386 myIsComputed = true;
3388 return setErrorCode( ERR_OK );
3391 //=======================================================================
3392 //function : mergePoints
3393 //purpose : Merge XYZ on edges and/or faces.
3394 //=======================================================================
3396 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3398 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3399 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3401 list<list< int > >& groups = idListIt->second;
3402 if ( groups.size() < 2 )
3406 const TNodeSet& nodes = idListIt->first;
3407 double tol2 = 1.e-10;
3408 if ( nodes.size() > 1 ) {
3410 TNodeSet::const_iterator n = nodes.begin();
3411 for ( ; n != nodes.end(); ++n )
3412 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3413 double x, y, z, X, Y, Z;
3414 box.Get( x, y, z, X, Y, Z );
3415 gp_Pnt p( x, y, z ), P( X, Y, Z );
3416 tol2 = 1.e-4 * p.SquareDistance( P );
3419 // to unite groups on link
3420 bool unite = ( uniteGroups && nodes.size() == 2 );
3421 map< double, int > distIndMap;
3422 const SMDS_MeshNode* node = *nodes.begin();
3423 gp_Pnt P( node->X(), node->Y(), node->Z() );
3425 // compare points, replace indices
3427 list< int >::iterator ind1, ind2;
3428 list< list< int > >::iterator grpIt1, grpIt2;
3429 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3431 list< int >& indices1 = *grpIt1;
3433 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3435 list< int >& indices2 = *grpIt2;
3436 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3438 gp_XYZ& p1 = myXYZ[ *ind1 ];
3439 ind2 = indices2.begin();
3440 while ( ind2 != indices2.end() )
3442 gp_XYZ& p2 = myXYZ[ *ind2 ];
3443 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3444 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3446 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3447 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3448 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3449 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3451 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3452 myXYZ[ *ind2 ] = undefinedXYZ();
3453 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3455 ind2 = indices2.erase( ind2 );
3462 if ( unite ) { // sort indices using distIndMap
3463 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3465 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3466 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3467 distIndMap.insert( make_pair( dist, *ind1 ));
3471 if ( unite ) { // put all sorted indices into the first group
3472 list< int >& g = groups.front();
3474 map< double, int >::iterator dist_ind = distIndMap.begin();
3475 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3476 g.push_back( dist_ind->second );
3478 } // loop on myIdsOnBoundary
3481 //=======================================================================
3482 //function : makePolyElements
3483 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3484 //=======================================================================
3486 void SMESH_Pattern::
3487 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3488 const bool toCreatePolygons,
3489 const bool toCreatePolyedrs)
3491 myPolyElemXYZIDs.clear();
3492 myPolyElems.clear();
3493 myPolyElems.reserve( myIdsOnBoundary.size() );
3495 // make a set of refined elements
3496 TIDSortedElemSet avoidSet, elemSet;
3497 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3498 for(; itv!=myElements.end(); itv++) {
3499 const SMDS_MeshElement* el = (*itv);
3500 avoidSet.insert( el );
3502 //avoidSet.insert( myElements.begin(), myElements.end() );
3504 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3506 if ( toCreatePolygons )
3508 int lastFreeId = myXYZ.size();
3510 // loop on links of refined elements
3511 indListIt = myIdsOnBoundary.begin();
3512 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3514 const TNodeSet & linkNodes = indListIt->first;
3515 if ( linkNodes.size() != 2 )
3516 continue; // skip face
3517 const SMDS_MeshNode* n1 = * linkNodes.begin();
3518 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3520 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3521 if ( idGroups.empty() || idGroups.front().empty() )
3524 // find not refined face having n1-n2 link
3528 const SMDS_MeshElement* face =
3529 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3532 avoidSet.insert ( face );
3533 myPolyElems.push_back( face );
3535 // some links of <face> are split;
3536 // make list of xyz for <face>
3537 myPolyElemXYZIDs.push_back(TElemDef());
3538 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3539 // loop on links of a <face>
3540 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3541 int i = 0, nbNodes = face->NbNodes();
3542 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3543 while ( nIt->more() )
3544 nodes[ i++ ] = smdsNode( nIt->next() );
3545 nodes[ i ] = nodes[ 0 ];
3546 for ( i = 0; i < nbNodes; ++i )
3548 // look for point mapped on a link
3549 TNodeSet faceLinkNodes;
3550 faceLinkNodes.insert( nodes[ i ] );
3551 faceLinkNodes.insert( nodes[ i + 1 ] );
3552 if ( faceLinkNodes == linkNodes )
3553 nn_IdList = indListIt;
3555 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3556 // add face point ids
3557 faceNodeIds.push_back( ++lastFreeId );
3558 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3559 if ( nn_IdList != myIdsOnBoundary.end() )
3561 // there are points mapped on a link
3562 list< int >& mappedIds = nn_IdList->second.front();
3563 if ( isReversed( nodes[ i ], mappedIds ))
3564 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3566 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3568 } // loop on links of a <face>
3574 if ( myIs2D && idGroups.size() > 1 ) {
3576 // sew new elements on 2 refined elements sharing n1-n2 link
3578 list< int >& idsOnLink = idGroups.front();
3579 // temporarily add ids of link nodes to idsOnLink
3580 bool rev = isReversed( n1, idsOnLink );
3581 for ( int i = 0; i < 2; ++i )
3584 nodeSet.insert( i ? n2 : n1 );
3585 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3586 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3587 int nodeId = groups.front().front();
3589 if ( rev ) append = !append;
3591 idsOnLink.push_back( nodeId );
3593 idsOnLink.push_front( nodeId );
3595 list< int >::iterator id = idsOnLink.begin();
3596 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3598 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3599 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3600 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3602 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3603 // look for <id> in element definition
3604 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3605 ASSERT ( idDef != pIdList->end() );
3606 // look for 2 neighbour ids of <id> in element definition
3607 for ( int prev = 0; prev < 2; ++prev ) {
3608 TElemDef::iterator idDef2 = idDef;
3610 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3612 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3613 // look for idDef2 on a link starting from id
3614 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3615 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3616 // insert ids located on link between <id> and <id2>
3617 // into the element definition between idDef and idDef2
3619 for ( ; id2 != id; --id2 )
3620 pIdList->insert( idDef, *id2 );
3622 list< int >::iterator id1 = id;
3623 for ( ++id1, ++id2; id1 != id2; ++id1 )
3624 pIdList->insert( idDef2, *id1 );
3630 // remove ids of link nodes
3631 idsOnLink.pop_front();
3632 idsOnLink.pop_back();
3634 } // loop on myIdsOnBoundary
3635 } // if ( toCreatePolygons )
3637 if ( toCreatePolyedrs )
3639 // check volumes adjacent to the refined elements
3640 SMDS_VolumeTool volTool;
3641 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3642 for ( ; refinedElem != myElements.end(); ++refinedElem )
3644 // loop on nodes of refinedElem
3645 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3646 while ( nIt->more() ) {
3647 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3648 // loop on inverse elements of node
3649 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3650 while ( eIt->more() )
3652 const SMDS_MeshElement* elem = eIt->next();
3653 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3654 continue; // skip faces or refined elements
3655 // add polyhedron definition
3656 myPolyhedronQuantities.push_back(vector<int> ());
3657 myPolyElemXYZIDs.push_back(TElemDef());
3658 vector<int>& quantity = myPolyhedronQuantities.back();
3659 TElemDef & elemDef = myPolyElemXYZIDs.back();
3660 // get definitions of new elements on volume faces
3661 bool makePoly = false;
3662 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3664 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3665 volTool.NbFaceNodes( iF ),
3666 theNodes, elemDef, quantity))
3670 myPolyElems.push_back( elem );
3672 myPolyhedronQuantities.pop_back();
3673 myPolyElemXYZIDs.pop_back();
3681 //=======================================================================
3682 //function : getFacesDefinition
3683 //purpose : return faces definition for a volume face defined by theBndNodes
3684 //=======================================================================
3686 bool SMESH_Pattern::
3687 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3688 const int theNbBndNodes,
3689 const vector< const SMDS_MeshNode* >& theNodes,
3690 list< int >& theFaceDefs,
3691 vector<int>& theQuantity)
3693 bool makePoly = false;
3694 // cout << "FROM FACE NODES: " <<endl;
3695 // for ( int i = 0; i < theNbBndNodes; ++i )
3696 // cout << theBndNodes[ i ];
3698 set< const SMDS_MeshNode* > bndNodeSet;
3699 for ( int i = 0; i < theNbBndNodes; ++i )
3700 bndNodeSet.insert( theBndNodes[ i ]);
3702 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3704 // make a set of all nodes on a face
3706 if ( !myIs2D ) { // for 2D, merge only edges
3707 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3708 if ( nn_IdList != myIdsOnBoundary.end() ) {
3710 list< int > & faceIds = nn_IdList->second.front();
3711 ids.insert( faceIds.begin(), faceIds.end() );
3714 //bool hasIdsInFace = !ids.empty();
3716 // add ids on links and bnd nodes
3717 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3718 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3719 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3721 // add id of iN-th bnd node
3723 nSet.insert( theBndNodes[ iN ] );
3724 nn_IdList = myIdsOnBoundary.find( nSet );
3725 int bndId = ++lastFreeId;
3726 if ( nn_IdList != myIdsOnBoundary.end() ) {
3727 bndId = nn_IdList->second.front().front();
3728 ids.insert( bndId );
3731 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3732 faceDef.push_back( bndId );
3733 // add ids on a link
3735 linkNodes.insert( theBndNodes[ iN ]);
3736 linkNodes.insert( theBndNodes[ iN + 1 == theNbBndNodes ? 0 : iN + 1 ]);
3737 nn_IdList = myIdsOnBoundary.find( linkNodes );
3738 if ( nn_IdList != myIdsOnBoundary.end() ) {
3740 list< int > & linkIds = nn_IdList->second.front();
3741 ids.insert( linkIds.begin(), linkIds.end() );
3742 if ( isReversed( theBndNodes[ iN ], linkIds ))
3743 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3745 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3749 // find faces definition of new volumes
3751 bool defsAdded = false;
3752 if ( !myIs2D ) { // for 2D, merge only edges
3753 SMDS_VolumeTool vol;
3754 set< TElemDef* > checkedVolDefs;
3755 set< int >::iterator id = ids.begin();
3756 for ( ; id != ids.end(); ++id )
3758 // definitions of volumes sharing id
3759 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3760 ASSERT( !defList.empty() );
3761 // loop on volume definitions
3762 list< TElemDef* >::iterator pIdList = defList.begin();
3763 for ( ; pIdList != defList.end(); ++pIdList)
3765 if ( !checkedVolDefs.insert( *pIdList ).second )
3766 continue; // skip already checked volume definition
3767 vector< int > idVec;
3768 idVec.reserve( (*pIdList)->size() );
3769 idVec.insert( idVec.begin(), (*pIdList)->begin(), (*pIdList)->end() );
3770 // loop on face defs of a volume
3771 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3772 if ( volType == SMDS_VolumeTool::UNKNOWN )
3774 int nbFaces = vol.NbFaces( volType );
3775 for ( int iF = 0; iF < nbFaces; ++iF )
3777 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3778 int iN, nbN = vol.NbFaceNodes( volType, iF );
3779 // check if all nodes of a faces are in <ids>
3781 for ( iN = 0; iN < nbN && all; ++iN ) {
3782 int nodeId = idVec[ nodeInds[ iN ]];
3783 all = ( ids.find( nodeId ) != ids.end() );
3786 // store a face definition
3787 for ( iN = 0; iN < nbN; ++iN ) {
3788 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3790 theQuantity.push_back( nbN );
3798 theQuantity.push_back( faceDef.size() );
3799 theFaceDefs.splice( theFaceDefs.end(), faceDef, faceDef.begin(), faceDef.end() );
3805 //=======================================================================
3806 //function : clearSubMesh
3808 //=======================================================================
3810 static bool clearSubMesh( SMESH_Mesh* theMesh,
3811 const TopoDS_Shape& theShape)
3813 bool removed = false;
3814 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3816 removed = !aSubMesh->IsEmpty();
3818 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3821 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3822 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3824 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3825 removed = eIt->more();
3826 while ( eIt->more() )
3827 aMeshDS->RemoveElement( eIt->next() );
3828 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3829 removed = removed || nIt->more();
3830 while ( nIt->more() )
3831 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3837 //=======================================================================
3838 //function : clearMesh
3839 //purpose : clear mesh elements existing on myShape in theMesh
3840 //=======================================================================
3842 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3845 if ( !myShape.IsNull() )
3847 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3848 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3849 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3851 clearSubMesh( theMesh, it.Value() );
3857 //=======================================================================
3858 //function : MakeMesh
3859 //purpose : Create nodes and elements in <theMesh> using nodes
3860 // coordinates computed by either of Apply...() methods
3861 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3862 // it does not care of nodes and elements already existing on
3863 // subshapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3864 //=======================================================================
3866 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3867 const bool toCreatePolygons,
3868 const bool toCreatePolyedrs)
3870 MESSAGE(" ::MakeMesh() " );
3871 if ( !myIsComputed )
3872 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3874 mergePoints( toCreatePolygons );
3876 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3878 // clear elements and nodes existing on myShape
3881 bool onMeshElements = ( !myElements.empty() );
3883 // Create missing nodes
3885 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3886 if ( onMeshElements )
3888 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3889 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3890 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3891 nodesVector[ i_node->first ] = i_node->second;
3893 for ( int i = 0; i < myXYZ.size(); ++i ) {
3894 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3895 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3902 nodesVector.resize( myPoints.size(), 0 );
3904 // to find point index
3905 map< TPoint*, int > pointIndex;
3906 for ( int i = 0; i < myPoints.size(); i++ )
3907 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3909 // loop on sub-shapes of myShape: create nodes
3910 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3911 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3914 //SMESHDS_SubMesh * subMeshDS = 0;
3915 if ( !myShapeIDMap.IsEmpty() ) {
3916 S = myShapeIDMap( idPointIt->first );
3917 //subMeshDS = aMeshDS->MeshElements( S );
3919 list< TPoint* > & points = idPointIt->second;
3920 list< TPoint* >::iterator pIt = points.begin();
3921 for ( ; pIt != points.end(); pIt++ )
3923 TPoint* point = *pIt;
3924 int pIndex = pointIndex[ point ];
3925 if ( nodesVector [ pIndex ] )
3927 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3930 nodesVector [ pIndex ] = node;
3932 if ( !S.IsNull() /*subMeshDS*/ ) {
3933 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3934 switch ( S.ShapeType() ) {
3935 case TopAbs_VERTEX: {
3936 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3939 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3942 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3943 point->myUV.X(), point->myUV.Y() ); break;
3946 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3955 if ( onMeshElements )
3957 // prepare data to create poly elements
3958 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3961 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3962 // sew old and new elements
3963 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3967 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3970 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3971 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3972 // for ( ; i_sm != sm.end(); i_sm++ )
3974 // cout << " SM " << i_sm->first << " ";
3975 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
3976 // //SMDS_ElemIteratorPtr GetElements();
3977 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
3978 // while ( nit->more() )
3979 // cout << nit->next()->GetID() << " ";
3982 return setErrorCode( ERR_OK );
3985 //=======================================================================
3986 //function : createElements
3987 //purpose : add elements to the mesh
3988 //=======================================================================
3990 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
3991 const vector<const SMDS_MeshNode* >& theNodesVector,
3992 const list< TElemDef > & theElemNodeIDs,
3993 const vector<const SMDS_MeshElement*>& theElements)
3995 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3996 SMESH_MeshEditor editor( theMesh );
3998 bool onMeshElements = !theElements.empty();
4000 // shapes and groups theElements are on
4001 vector< int > shapeIDs;
4002 vector< list< SMESHDS_Group* > > groups;
4003 set< const SMDS_MeshNode* > shellNodes;
4004 if ( onMeshElements )
4006 shapeIDs.resize( theElements.size() );
4007 groups.resize( theElements.size() );
4008 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4009 set<SMESHDS_GroupBase*>::const_iterator grIt;
4010 for ( int i = 0; i < theElements.size(); i++ )
4012 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4013 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4014 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4015 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4016 groups[ i ].push_back( group );
4019 // get all nodes bound to shells because their SpacePosition is not set
4020 // by SMESHDS_Mesh::SetNodeInVolume()
4021 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4022 if ( !aMainShape.IsNull() ) {
4023 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4024 for ( ; shellExp.More(); shellExp.Next() )
4026 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4028 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4029 while ( nIt->more() )
4030 shellNodes.insert( nIt->next() );
4035 // nb new elements per a refined element
4036 int nbNewElemsPerOld = 1;
4037 if ( onMeshElements )
4038 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4042 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4043 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4044 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4046 const TElemDef & elemNodeInd = *enIt;
4048 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4049 TElemDef::const_iterator id = elemNodeInd.begin();
4051 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4052 if ( *id < theNodesVector.size() )
4053 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4055 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4057 // dim of refined elem
4058 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4059 if ( onMeshElements ) {
4060 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4063 const SMDS_MeshElement* elem = 0;
4065 switch ( nbNodes ) {
4067 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4069 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4071 if ( !onMeshElements ) {// create a quadratic face
4072 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4073 nodes[4], nodes[5] ); break;
4074 } // else do not break but create a polygon
4076 if ( !onMeshElements ) {// create a quadratic face
4077 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4078 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4079 } // else do not break but create a polygon
4081 elem = aMeshDS->AddPolygonalFace( nodes );
4085 switch ( nbNodes ) {
4087 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4089 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4092 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4093 nodes[4], nodes[5] ); break;
4095 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4096 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4098 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4101 // set element on a shape
4102 if ( elem && onMeshElements ) // applied to mesh elements
4104 int shapeID = shapeIDs[ elemIndex ];
4105 if ( shapeID > 0 ) {
4106 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4107 // set nodes on a shape
4108 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4109 if ( S.ShapeType() == TopAbs_SOLID ) {
4110 TopoDS_Iterator shellIt( S );
4111 if ( shellIt.More() )
4112 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4114 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4115 while ( noIt->more() ) {
4116 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4117 if (!node->GetPosition()->GetShapeId() &&
4118 shellNodes.find( node ) == shellNodes.end() ) {
4119 if ( S.ShapeType() == TopAbs_FACE )
4120 aMeshDS->SetNodeOnFace( node, shapeID );
4122 aMeshDS->SetNodeInVolume( node, shapeID );
4123 shellNodes.insert( node );
4128 // add elem in groups
4129 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4130 for ( ; g != groups[ elemIndex ].end(); ++g )
4131 (*g)->SMDSGroup().Add( elem );
4133 if ( elem && !myShape.IsNull() ) // applied to shape
4134 aMeshDS->SetMeshElementOnShape( elem, myShape );
4137 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4138 // so that operations with hypotheses will erase the mesh being built
4140 SMESH_subMesh * subMesh;
4141 if ( !myShape.IsNull() ) {
4142 subMesh = theMesh->GetSubMesh( myShape );
4144 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4146 if ( onMeshElements ) {
4147 list< int > elemIDs;
4148 for ( int i = 0; i < theElements.size(); i++ )
4150 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4152 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4154 elemIDs.push_back( theElements[ i ]->GetID() );
4156 // remove refined elements
4157 editor.Remove( elemIDs, false );
4161 //=======================================================================
4162 //function : isReversed
4163 //purpose : check xyz ids order in theIdsList taking into account
4164 // theFirstNode on a link
4165 //=======================================================================
4167 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4168 const list< int >& theIdsList) const
4170 if ( theIdsList.size() < 2 )
4173 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4175 list<int>::const_iterator id = theIdsList.begin();
4176 for ( int i = 0; i < 2; ++i, ++id ) {
4177 if ( *id < myXYZ.size() )
4178 P[ i ] = myXYZ[ *id ];
4180 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4181 i_n = myXYZIdToNodeMap.find( *id );
4182 ASSERT( i_n != myXYZIdToNodeMap.end() );
4183 const SMDS_MeshNode* n = i_n->second;
4184 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4187 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4191 //=======================================================================
4192 //function : arrangeBoundaries
4193 //purpose : if there are several wires, arrange boundaryPoints so that
4194 // the outer wire goes first and fix inner wires orientation
4195 // update myKeyPointIDs to correspond to the order of key-points
4196 // in boundaries; sort internal boundaries by the nb of key-points
4197 //=======================================================================
4199 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4201 typedef list< list< TPoint* > >::iterator TListOfListIt;
4202 TListOfListIt bndIt;
4203 list< TPoint* >::iterator pIt;
4205 int nbBoundaries = boundaryList.size();
4206 if ( nbBoundaries > 1 )
4208 // sort boundaries by nb of key-points
4209 if ( nbBoundaries > 2 )
4211 // move boundaries in tmp list
4212 list< list< TPoint* > > tmpList;
4213 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4214 // make a map nb-key-points to boundary-position-in-tmpList,
4215 // boundary-positions get ordered in it
4216 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4217 TNbKpBndPosMap nbKpBndPosMap;
4218 bndIt = tmpList.begin();
4219 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4220 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4221 int nb = *nbKpIt * nbBoundaries;
4222 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4224 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4226 // move boundaries back to boundaryList
4227 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4228 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4229 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4230 TListOfListIt bndPos1 = bndPos2++;
4231 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4235 // Look for the outer boundary: the one with the point with the least X
4236 double leastX = DBL_MAX;
4237 TListOfListIt outerBndPos;
4238 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4240 list< TPoint* >& boundary = (*bndIt);
4241 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4243 TPoint* point = *pIt;
4244 if ( point->myInitXYZ.X() < leastX ) {
4245 leastX = point->myInitXYZ.X();
4246 outerBndPos = bndIt;
4251 if ( outerBndPos != boundaryList.begin() )
4252 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4254 } // if nbBoundaries > 1
4256 // Check boundaries orientation and re-fill myKeyPointIDs
4258 set< TPoint* > keyPointSet;
4259 list< int >::iterator kpIt = myKeyPointIDs.begin();
4260 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4261 keyPointSet.insert( & myPoints[ *kpIt ]);
4262 myKeyPointIDs.clear();
4264 // update myNbKeyPntInBoundary also
4265 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4267 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4269 // find the point with the least X
4270 double leastX = DBL_MAX;
4271 list< TPoint* >::iterator xpIt;
4272 list< TPoint* >& boundary = (*bndIt);
4273 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4275 TPoint* point = *pIt;
4276 if ( point->myInitXYZ.X() < leastX ) {
4277 leastX = point->myInitXYZ.X();
4281 // find points next to the point with the least X
4282 TPoint* p = *xpIt, *pPrev, *pNext;
4283 if ( p == boundary.front() )
4284 pPrev = *(++boundary.rbegin());
4290 if ( p == boundary.back() )
4291 pNext = *(++boundary.begin());
4296 // vectors of boundary direction near <p>
4297 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4298 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4299 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4300 double yPrev = v1.Y() / sqrt( sqMag1 );
4301 double yNext = v2.Y() / sqrt( sqMag2 );
4302 double sumY = yPrev + yNext;
4304 if ( bndIt == boundaryList.begin() ) // outer boundary
4312 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4313 (*nbKpIt) = 0; // count nb of key-points again
4314 pIt = boundary.begin();
4315 for ( ; pIt != boundary.end(); pIt++)
4317 TPoint* point = *pIt;
4318 if ( keyPointSet.find( point ) == keyPointSet.end() )
4320 // find an index of a keypoint
4322 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4323 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4324 if ( &(*pVecIt) == point )
4326 myKeyPointIDs.push_back( index );
4329 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4332 } // loop on a list of boundaries
4334 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4337 //=======================================================================
4338 //function : findBoundaryPoints
4339 //purpose : if loaded from file, find points to map on edges and faces and
4340 // compute their parameters
4341 //=======================================================================
4343 bool SMESH_Pattern::findBoundaryPoints()
4345 if ( myIsBoundaryPointsFound ) return true;
4347 MESSAGE(" findBoundaryPoints() ");
4349 myNbKeyPntInBoundary.clear();
4353 set< TPoint* > pointsInElems;
4355 // Find free links of elements:
4356 // put links of all elements in a set and remove links encountered twice
4358 typedef pair< TPoint*, TPoint*> TLink;
4359 set< TLink > linkSet;
4360 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4361 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4363 TElemDef & elemPoints = *epIt;
4364 TElemDef::iterator pIt = elemPoints.begin();
4365 int prevP = elemPoints.back();
4366 for ( ; pIt != elemPoints.end(); pIt++ ) {
4367 TPoint* p1 = & myPoints[ prevP ];
4368 TPoint* p2 = & myPoints[ *pIt ];
4369 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4370 ASSERT( link.first != link.second );
4371 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4372 if ( !itUniq.second )
4373 linkSet.erase( itUniq.first );
4376 pointsInElems.insert( p1 );
4379 // Now linkSet contains only free links,
4380 // find the points order that they have in boundaries
4382 // 1. make a map of key-points
4383 set< TPoint* > keyPointSet;
4384 list< int >::iterator kpIt = myKeyPointIDs.begin();
4385 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4386 keyPointSet.insert( & myPoints[ *kpIt ]);
4388 // 2. chain up boundary points
4389 list< list< TPoint* > > boundaryList;
4390 boundaryList.push_back( list< TPoint* >() );
4391 list< TPoint* > * boundary = & boundaryList.back();
4393 TPoint *point1, *point2, *keypoint1;
4394 kpIt = myKeyPointIDs.begin();
4395 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4396 // loop on free links: look for the next point
4398 set< TLink >::iterator lIt = linkSet.begin();
4399 while ( lIt != linkSet.end() )
4401 if ( (*lIt).first == point1 )
4402 point2 = (*lIt).second;
4403 else if ( (*lIt).second == point1 )
4404 point2 = (*lIt).first;
4409 linkSet.erase( lIt );
4410 lIt = linkSet.begin();
4412 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4414 boundary->push_back( point2 );
4416 else // a key-point found
4418 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4420 if ( point2 != keypoint1 ) // its not the boundary end
4422 boundary->push_back( point2 );
4424 else // the boundary end reached
4426 boundary->push_front( keypoint1 );
4427 boundary->push_back( keypoint1 );
4428 myNbKeyPntInBoundary.push_back( iKeyPoint );
4429 if ( keyPointSet.empty() )
4430 break; // all boundaries containing key-points are found
4432 // prepare to search for the next boundary
4433 boundaryList.push_back( list< TPoint* >() );
4434 boundary = & boundaryList.back();
4435 point2 = keypoint1 = (*keyPointSet.begin());
4439 } // loop on the free links set
4441 if ( boundary->empty() ) {
4442 MESSAGE(" a separate key-point");
4443 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4446 // if there are several wires, arrange boundaryPoints so that
4447 // the outer wire goes first and fix inner wires orientation;
4448 // sort myKeyPointIDs to correspond to the order of key-points
4450 arrangeBoundaries( boundaryList );
4452 // Find correspondence shape ID - points,
4453 // compute points parameter on edge
4455 keyPointSet.clear();
4456 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4457 keyPointSet.insert( & myPoints[ *kpIt ]);
4459 set< TPoint* > edgePointSet; // to find in-face points
4460 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4461 int edgeID = myKeyPointIDs.size() + 1;
4463 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4464 for ( ; bndIt != boundaryList.end(); bndIt++ )
4466 boundary = & (*bndIt);
4467 double edgeLength = 0;
4468 list< TPoint* >::iterator pIt = boundary->begin();
4469 getShapePoints( edgeID ).push_back( *pIt );
4470 getShapePoints( vertexID++ ).push_back( *pIt );
4471 for ( pIt++; pIt != boundary->end(); pIt++)
4473 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4474 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4475 TPoint* point = *pIt;
4476 edgePointSet.insert( point );
4477 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4479 edgePoints.push_back( point );
4480 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4481 point->myInitU = edgeLength;
4485 // treat points on the edge which ends up: compute U [0,1]
4486 edgePoints.push_back( point );
4487 if ( edgePoints.size() > 2 ) {
4488 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4489 list< TPoint* >::iterator epIt = edgePoints.begin();
4490 for ( ; epIt != edgePoints.end(); epIt++ )
4491 (*epIt)->myInitU /= edgeLength;
4493 // begin the next edge treatment
4496 if ( point != boundary->front() ) { // not the first key-point again
4497 getShapePoints( edgeID ).push_back( point );
4498 getShapePoints( vertexID++ ).push_back( point );
4504 // find in-face points
4505 list< TPoint* > & facePoints = getShapePoints( edgeID );
4506 vector< TPoint >::iterator pVecIt = myPoints.begin();
4507 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4508 TPoint* point = &(*pVecIt);
4509 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4510 pointsInElems.find( point ) != pointsInElems.end())
4511 facePoints.push_back( point );
4518 // bind points to shapes according to point parameters
4519 vector< TPoint >::iterator pVecIt = myPoints.begin();
4520 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4521 TPoint* point = &(*pVecIt);
4522 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4523 getShapePoints( shapeID ).push_back( point );
4524 // detect key-points
4525 if ( SMESH_Block::IsVertexID( shapeID ))
4526 myKeyPointIDs.push_back( i );
4530 myIsBoundaryPointsFound = true;
4531 return myIsBoundaryPointsFound;
4534 //=======================================================================
4536 //purpose : clear fields
4537 //=======================================================================
4539 void SMESH_Pattern::Clear()
4541 myIsComputed = myIsBoundaryPointsFound = false;
4544 myKeyPointIDs.clear();
4545 myElemPointIDs.clear();
4546 myShapeIDToPointsMap.clear();
4547 myShapeIDMap.Clear();
4549 myNbKeyPntInBoundary.clear();
4552 //=======================================================================
4553 //function : setShapeToMesh
4554 //purpose : set a shape to be meshed. Return True if meshing is possible
4555 //=======================================================================
4557 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4559 if ( !IsLoaded() ) {
4560 MESSAGE( "Pattern not loaded" );
4561 return setErrorCode( ERR_APPL_NOT_LOADED );
4564 TopAbs_ShapeEnum aType = theShape.ShapeType();
4565 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4567 MESSAGE( "Pattern dimention mismatch" );
4568 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4571 // check if a face is closed
4572 int nbNodeOnSeamEdge = 0;
4574 TopTools_MapOfShape seamVertices;
4575 TopoDS_Face face = TopoDS::Face( theShape );
4576 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4577 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4578 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4579 if ( BRep_Tool::IsClosed(ee, face) ) {
4580 // seam edge and vertices encounter twice in theFace
4581 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4582 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4587 // check nb of vertices
4588 TopTools_IndexedMapOfShape vMap;
4589 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4590 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4591 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4592 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4595 myElements.clear(); // not refine elements
4596 myElemXYZIDs.clear();
4598 myShapeIDMap.Clear();
4603 //=======================================================================
4604 //function : GetMappedPoints
4605 //purpose : Return nodes coordinates computed by Apply() method
4606 //=======================================================================
4608 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4611 if ( !myIsComputed )
4614 if ( myElements.empty() ) { // applied to shape
4615 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4616 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4617 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4619 else { // applied to mesh elements
4620 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4621 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4622 for ( ; xyz != myXYZ.end(); ++xyz )
4623 if ( !isDefined( *xyz ))
4624 thePoints.push_back( definedXYZ );
4626 thePoints.push_back( & (*xyz) );
4628 return !thePoints.empty();
4632 //=======================================================================
4633 //function : GetPoints
4634 //purpose : Return nodes coordinates of the pattern
4635 //=======================================================================
4637 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4644 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4645 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4646 thePoints.push_back( & (*pVecIt).myInitXYZ );
4648 return ( thePoints.size() > 0 );
4651 //=======================================================================
4652 //function : getShapePoints
4653 //purpose : return list of points located on theShape
4654 //=======================================================================
4656 list< SMESH_Pattern::TPoint* > &
4657 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4660 if ( !myShapeIDMap.Contains( theShape ))
4661 aShapeID = myShapeIDMap.Add( theShape );
4663 aShapeID = myShapeIDMap.FindIndex( theShape );
4665 return myShapeIDToPointsMap[ aShapeID ];
4668 //=======================================================================
4669 //function : getShapePoints
4670 //purpose : return list of points located on the shape
4671 //=======================================================================
4673 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4675 return myShapeIDToPointsMap[ theShapeID ];
4678 //=======================================================================
4679 //function : DumpPoints
4681 //=======================================================================
4683 void SMESH_Pattern::DumpPoints() const
4686 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4687 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4688 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4692 //=======================================================================
4693 //function : TPoint()
4695 //=======================================================================
4697 SMESH_Pattern::TPoint::TPoint()
4700 myInitXYZ.SetCoord(0,0,0);
4701 myInitUV.SetCoord(0.,0.);
4703 myXYZ.SetCoord(0,0,0);
4704 myUV.SetCoord(0.,0.);
4709 //=======================================================================
4710 //function : operator <<
4712 //=======================================================================
4714 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4716 gp_XYZ xyz = p.myInitXYZ;
4717 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4718 gp_XY xy = p.myInitUV;
4719 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4720 double u = p.myInitU;
4721 OS << " u( " << u << " )) " << &p << endl;
4722 xyz = p.myXYZ.XYZ();
4723 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4725 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4727 OS << " u( " << u << " ))" << endl;