1 // Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_Pattern.hxx
24 // Created : Mon Aug 2 10:30:00 2004
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_Pattern.hxx"
29 #include <BRepAdaptor_Curve.hxx>
30 #include <BRepTools.hxx>
31 #include <BRepTools_WireExplorer.hxx>
32 #include <BRep_Tool.hxx>
33 #include <Bnd_Box.hxx>
34 #include <Bnd_Box2d.hxx>
36 #include <Extrema_ExtPC.hxx>
37 #include <Extrema_GenExtPS.hxx>
38 #include <Extrema_POnSurf.hxx>
39 #include <Geom2d_Curve.hxx>
40 #include <GeomAdaptor_Surface.hxx>
41 #include <Geom_Curve.hxx>
42 #include <Geom_Surface.hxx>
43 #include <Precision.hxx>
44 #include <TopAbs_ShapeEnum.hxx>
46 #include <TopExp_Explorer.hxx>
47 #include <TopLoc_Location.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
50 #include <TopoDS_Edge.hxx>
51 #include <TopoDS_Face.hxx>
52 #include <TopoDS_Iterator.hxx>
53 #include <TopoDS_Shell.hxx>
54 #include <TopoDS_Vertex.hxx>
55 #include <TopoDS_Wire.hxx>
57 #include <gp_Lin2d.hxx>
58 #include <gp_Pnt2d.hxx>
59 #include <gp_Trsf.hxx>
63 #include "SMDS_EdgePosition.hxx"
64 #include "SMDS_FacePosition.hxx"
65 #include "SMDS_MeshElement.hxx"
66 #include "SMDS_MeshFace.hxx"
67 #include "SMDS_MeshNode.hxx"
68 #include "SMDS_VolumeTool.hxx"
69 #include "SMESHDS_Group.hxx"
70 #include "SMESHDS_Mesh.hxx"
71 #include "SMESHDS_SubMesh.hxx"
72 #include "SMESH_Block.hxx"
73 #include "SMESH_Mesh.hxx"
74 #include "SMESH_MesherHelper.hxx"
75 #include "SMESH_subMesh.hxx"
77 #include <Basics_OCCTVersion.hxx>
79 #include <Basics_Utils.hxx>
80 #include "utilities.h"
84 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
86 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
88 //=======================================================================
89 //function : SMESH_Pattern
91 //=======================================================================
93 SMESH_Pattern::SMESH_Pattern ()
96 //=======================================================================
99 //=======================================================================
101 static inline int getInt( const char * theSring )
103 if ( *theSring < '0' || *theSring > '9' )
107 int val = strtol( theSring, &ptr, 10 );
108 if ( ptr == theSring ||
109 // there must not be neither '.' nor ',' nor 'E' ...
110 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
116 //=======================================================================
117 //function : getDouble
119 //=======================================================================
121 static inline double getDouble( const char * theSring )
124 return strtod( theSring, &ptr );
127 //=======================================================================
128 //function : readLine
129 //purpose : Put token starting positions in theFields until '\n' or '\0'
130 // Return the number of the found tokens
131 //=======================================================================
133 static int readLine (list <const char*> & theFields,
134 const char* & theLineBeg,
135 const bool theClearFields )
137 if ( theClearFields )
142 /* switch ( symbol ) { */
143 /* case white-space: */
144 /* look for a non-space symbol; */
145 /* case string-end: */
148 /* case comment beginning: */
149 /* skip all till a line-end; */
151 /* put its position in theFields, skip till a white-space;*/
157 bool stopReading = false;
160 bool isNumber = false;
161 switch ( *theLineBeg )
163 case ' ': // white space
168 case '\n': // a line ends
169 stopReading = ( nbRead > 0 );
174 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
178 case '\0': // file ends
181 case '-': // real number
186 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
188 theFields.push_back( theLineBeg );
191 while (*theLineBeg != ' ' &&
192 *theLineBeg != '\n' &&
193 *theLineBeg != '\0');
197 return 0; // incorrect file format
203 } while ( !stopReading );
208 //=======================================================================
210 //purpose : Load a pattern from <theFile>
211 //=======================================================================
213 bool SMESH_Pattern::Load (const char* theFileContents)
215 MESSAGE("Load( file ) ");
217 Kernel_Utils::Localizer loc;
221 // ! This is a comment
222 // NB_POINTS ! 1 integer - the number of points in the pattern.
223 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
224 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
226 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
227 // ! elements description goes after all
228 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
233 const char* lineBeg = theFileContents;
234 list <const char*> fields;
235 const bool clearFields = true;
237 // NB_POINTS ! 1 integer - the number of points in the pattern.
239 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
240 MESSAGE("Error reading NB_POINTS");
241 return setErrorCode( ERR_READ_NB_POINTS );
243 int nbPoints = getInt( fields.front() );
245 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
247 // read the first point coordinates to define pattern dimention
248 int dim = readLine( fields, lineBeg, clearFields );
254 MESSAGE("Error reading points: wrong nb of coordinates");
255 return setErrorCode( ERR_READ_POINT_COORDS );
257 if ( nbPoints <= dim ) {
258 MESSAGE(" Too few points ");
259 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
262 // read the rest points
264 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
265 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
266 MESSAGE("Error reading points : wrong nb of coordinates ");
267 return setErrorCode( ERR_READ_POINT_COORDS );
269 // store point coordinates
270 myPoints.resize( nbPoints );
271 list <const char*>::iterator fIt = fields.begin();
272 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
274 TPoint & p = myPoints[ iPoint ];
275 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
277 double coord = getDouble( *fIt );
278 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
279 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
281 return setErrorCode( ERR_READ_3D_COORD );
283 p.myInitXYZ.SetCoord( iCoord, coord );
285 p.myInitUV.SetCoord( iCoord, coord );
289 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
292 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
293 MESSAGE("Error: missing key-points");
295 return setErrorCode( ERR_READ_NO_KEYPOINT );
298 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
300 int pointIndex = getInt( *fIt );
301 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
302 MESSAGE("Error: invalid point index " << pointIndex );
304 return setErrorCode( ERR_READ_BAD_INDEX );
306 if ( idSet.insert( pointIndex ).second ) // unique?
307 myKeyPointIDs.push_back( pointIndex );
311 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
313 while ( readLine( fields, lineBeg, clearFields ))
315 myElemPointIDs.push_back( TElemDef() );
316 TElemDef& elemPoints = myElemPointIDs.back();
317 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
319 int pointIndex = getInt( *fIt );
320 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
321 MESSAGE("Error: invalid point index " << pointIndex );
323 return setErrorCode( ERR_READ_BAD_INDEX );
325 elemPoints.push_back( pointIndex );
327 // check the nb of nodes in element
329 switch ( elemPoints.size() ) {
330 case 3: if ( !myIs2D ) Ok = false; break;
334 case 8: if ( myIs2D ) Ok = false; break;
338 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
340 return setErrorCode( ERR_READ_ELEM_POINTS );
343 if ( myElemPointIDs.empty() ) {
344 MESSAGE("Error: no elements");
346 return setErrorCode( ERR_READ_NO_ELEMS );
349 findBoundaryPoints(); // sort key-points
351 return setErrorCode( ERR_OK );
354 //=======================================================================
356 //purpose : Save the loaded pattern into the file <theFileName>
357 //=======================================================================
359 bool SMESH_Pattern::Save (ostream& theFile)
361 MESSAGE(" ::Save(file) " );
363 Kernel_Utils::Localizer loc;
366 MESSAGE(" Pattern not loaded ");
367 return setErrorCode( ERR_SAVE_NOT_LOADED );
370 theFile << "!!! SALOME Mesh Pattern file" << endl;
371 theFile << "!!!" << endl;
372 theFile << "!!! Nb of points:" << endl;
373 theFile << myPoints.size() << endl;
377 // theFile.width( 8 );
378 // theFile.setf(ios::fixed);// use 123.45 floating notation
379 // theFile.setf(ios::right);
380 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
381 // theFile.setf(ios::showpoint); // do not show trailing zeros
382 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
383 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
384 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
385 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
386 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
387 theFile << " !- " << i << endl; // point id to ease reading by a human being
391 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
392 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
393 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
394 theFile << " " << *kpIt;
395 if ( !myKeyPointIDs.empty() )
399 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
400 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
401 for ( ; epIt != myElemPointIDs.end(); epIt++ )
403 const TElemDef & elemPoints = *epIt;
404 TElemDef::const_iterator iIt = elemPoints.begin();
405 for ( ; iIt != elemPoints.end(); iIt++ )
406 theFile << " " << *iIt;
412 return setErrorCode( ERR_OK );
415 //=======================================================================
416 //function : sortBySize
417 //purpose : sort theListOfList by size
418 //=======================================================================
420 template<typename T> struct TSizeCmp {
421 bool operator ()( const list < T > & l1, const list < T > & l2 )
422 const { return l1.size() < l2.size(); }
425 template<typename T> void sortBySize( list< list < T > > & theListOfList )
427 if ( theListOfList.size() > 2 ) {
428 TSizeCmp< T > SizeCmp;
429 theListOfList.sort( SizeCmp );
433 //=======================================================================
436 //=======================================================================
438 static gp_XY project (const SMDS_MeshNode* theNode,
439 Extrema_GenExtPS & theProjectorPS)
441 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
442 theProjectorPS.Perform( P );
443 if ( !theProjectorPS.IsDone() ) {
444 MESSAGE( "SMESH_Pattern: point projection FAILED");
447 double u, v, minVal = DBL_MAX;
448 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
449 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
450 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
451 minVal = theProjectorPS.SquareDistance( i );
453 if ( theProjectorPS.Value( i ) < minVal ) {
454 minVal = theProjectorPS.Value( i );
456 theProjectorPS.Point( i ).Parameter( u, v );
458 return gp_XY( u, v );
461 //=======================================================================
462 //function : areNodesBound
463 //purpose : true if all nodes of faces are bound to shapes
464 //=======================================================================
466 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
468 while ( faceItr->more() )
470 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
471 while ( nIt->more() )
473 const SMDS_MeshNode* node = smdsNode( nIt->next() );
474 if (node->getshapeId() <1) {
482 //=======================================================================
483 //function : isMeshBoundToShape
484 //purpose : return true if all 2d elements are bound to shape
485 // if aFaceSubmesh != NULL, then check faces bound to it
486 // else check all faces in aMeshDS
487 //=======================================================================
489 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
490 SMESHDS_SubMesh * aFaceSubmesh,
491 const bool isMainShape)
494 // check that all faces are bound to aFaceSubmesh
495 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
499 // check face nodes binding
500 if ( aFaceSubmesh ) {
501 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
502 return areNodesBound( fIt );
504 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
505 return areNodesBound( fIt );
508 //=======================================================================
510 //purpose : Create a pattern from the mesh built on <theFace>.
511 // <theProject>==true makes override nodes positions
512 // on <theFace> computed by mesher
513 //=======================================================================
515 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
516 const TopoDS_Face& theFace,
519 MESSAGE(" ::Load(face) " );
523 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
524 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
525 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
526 SMESH_MesherHelper helper( *theMesh );
527 helper.SetSubShape( theFace );
529 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
530 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
531 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
533 MESSAGE( "No elements bound to the face");
534 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
537 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
539 // check if face is closed
540 bool isClosed = helper.HasSeam();
542 list<TopoDS_Edge> eList;
543 list<TopoDS_Edge>::iterator elIt;
544 SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
546 // check that requested or needed projection is possible
547 bool isMainShape = theMesh->IsMainShape( face );
548 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
549 bool canProject = ( nbElems ? true : isMainShape );
551 canProject = false; // so far
553 if ( ( theProject || needProject ) && !canProject )
554 return setErrorCode( ERR_LOADF_CANT_PROJECT );
556 Extrema_GenExtPS projector;
557 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
558 if ( theProject || needProject )
559 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
562 TNodePointIDMap nodePointIDMap;
563 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
567 MESSAGE("Project the submesh");
568 // ---------------------------------------------------------------
569 // The case where the submesh is projected to theFace
570 // ---------------------------------------------------------------
573 list< const SMDS_MeshElement* > faces;
575 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
576 while ( fIt->more() ) {
577 const SMDS_MeshElement* f = fIt->next();
578 if ( f && f->GetType() == SMDSAbs_Face )
579 faces.push_back( f );
583 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
584 while ( fIt->more() )
585 faces.push_back( fIt->next() );
588 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
589 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
590 for ( ; fIt != faces.end(); ++fIt )
592 myElemPointIDs.push_back( TElemDef() );
593 TElemDef& elemPoints = myElemPointIDs.back();
594 int nbNodes = (*fIt)->NbCornerNodes();
595 for ( int i = 0;i < nbNodes; ++i )
597 const SMDS_MeshElement* node = (*fIt)->GetNode( i );
598 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
599 if ( nIdIt->second == -1 )
601 elemPoints.push_back( iPoint );
602 nIdIt->second = iPoint++;
605 elemPoints.push_back( (*nIdIt).second );
608 myPoints.resize( iPoint );
610 // project all nodes of 2d elements to theFace
611 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
612 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
614 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
615 TPoint * p = & myPoints[ (*nIdIt).second ];
616 p->myInitUV = project( node, projector );
617 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
619 // find key-points: the points most close to UV of vertices
620 TopExp_Explorer vExp( face, TopAbs_VERTEX );
621 set<int> foundIndices;
622 for ( ; vExp.More(); vExp.Next() ) {
623 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
624 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
625 double minDist = DBL_MAX;
627 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
628 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
629 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
630 if ( dist < minDist ) {
635 if ( foundIndices.insert( index ).second ) // unique?
636 myKeyPointIDs.push_back( index );
638 myIsBoundaryPointsFound = false;
643 // ---------------------------------------------------------------------
644 // The case where a pattern is being made from the mesh built by mesher
645 // ---------------------------------------------------------------------
647 // Load shapes in the consequent order and count nb of points
650 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
651 int nbV = myShapeIDMap.Extent();
652 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
653 bool added = ( nbV < myShapeIDMap.Extent() );
654 if ( !added ) { // vertex encountered twice
655 // a seam vertex have two corresponding key points
656 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
659 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
660 nbNodes += eSubMesh->NbNodes() + 1;
663 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
664 myShapeIDMap.Add( *elIt );
666 myShapeIDMap.Add( face );
668 myPoints.resize( nbNodes );
670 // Load U of points on edges
672 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
674 TopoDS_Edge & edge = *elIt;
675 list< TPoint* > & ePoints = getShapePoints( edge );
677 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
678 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
680 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
681 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
682 // to make adjacent edges share key-point, we make v2 FORWARD too
683 // (as we have different points for same shape with different orienation)
686 // on closed face we must have REVERSED some of seam vertices
688 if ( helper.IsSeamShape( edge ) ) {
689 if ( helper.IsRealSeam( edge ) && !isForward ) {
690 // reverse on reversed SEAM edge
695 else { // on CLOSED edge (i.e. having one vertex with different orienations)
696 for ( int is2 = 0; is2 < 2; ++is2 ) {
697 TopoDS_Shape & v = is2 ? v2 : v1;
698 if ( helper.IsRealSeam( v ) ) {
699 // reverse or not depending on orientation of adjacent seam
701 list<TopoDS_Edge>::iterator eIt2 = elIt;
703 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
705 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
706 if ( seam.Orientation() == TopAbs_REVERSED )
713 // the forward key-point
714 list< TPoint* > * vPoint = & getShapePoints( v1 );
715 if ( vPoint->empty() )
717 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
718 if ( vSubMesh && vSubMesh->NbNodes() ) {
719 myKeyPointIDs.push_back( iPoint );
720 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
721 const SMDS_MeshNode* node = nIt->next();
722 if ( v1.Orientation() == TopAbs_REVERSED )
723 closeNodePointIDMap.insert( make_pair( node, iPoint ));
725 nodePointIDMap.insert( make_pair( node, iPoint ));
727 TPoint* keyPoint = &myPoints[ iPoint++ ];
728 vPoint->push_back( keyPoint );
730 keyPoint->myInitUV = project( node, projector );
732 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
733 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
736 if ( !vPoint->empty() )
737 ePoints.push_back( vPoint->front() );
740 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
741 if ( eSubMesh && eSubMesh->NbNodes() )
743 // loop on nodes of an edge: sort them by param on edge
744 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
745 TParamNodeMap paramNodeMap;
746 int nbMeduimNodes = 0;
747 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
748 while ( nIt->more() )
750 const SMDS_MeshNode* node = nIt->next();
751 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
755 const SMDS_EdgePosition* epos =
756 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
757 double u = epos->GetUParameter();
758 paramNodeMap.insert( make_pair( u, node ));
760 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
761 // wrong U on edge, project
763 BRepAdaptor_Curve aCurve( edge );
764 proj.Initialize( aCurve, f, l );
765 paramNodeMap.clear();
766 nIt = eSubMesh->GetNodes();
767 for ( int iNode = 0; nIt->more(); ++iNode ) {
768 const SMDS_MeshNode* node = nIt->next();
769 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
771 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
773 if ( proj.IsDone() ) {
774 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
775 if ( proj.IsMin( i )) {
776 u = proj.Point( i ).Parameter();
780 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
782 paramNodeMap.insert( make_pair( u, node ));
785 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
786 if ( paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
787 return setErrorCode(ERR_UNEXPECTED);
790 // put U in [0,1] so that the first key-point has U==0
791 bool isSeam = helper.IsRealSeam( edge );
793 TParamNodeMap::iterator unIt = paramNodeMap.begin();
794 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
795 while ( unIt != paramNodeMap.end() )
797 TPoint* p = & myPoints[ iPoint ];
798 ePoints.push_back( p );
799 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
800 if ( isSeam && !isForward )
801 closeNodePointIDMap.insert( make_pair( node, iPoint ));
803 nodePointIDMap.insert ( make_pair( node, iPoint ));
806 p->myInitUV = project( node, projector );
808 double u = isForward ? (*unIt).first : (*unRIt).first;
809 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
810 p->myInitUV = C2d->Value( u ).XY();
812 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
817 // the reverse key-point
818 vPoint = & getShapePoints( v2 );
819 if ( vPoint->empty() )
821 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
822 if ( vSubMesh && vSubMesh->NbNodes() ) {
823 myKeyPointIDs.push_back( iPoint );
824 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
825 const SMDS_MeshNode* node = nIt->next();
826 if ( v2.Orientation() == TopAbs_REVERSED )
827 closeNodePointIDMap.insert( make_pair( node, iPoint ));
829 nodePointIDMap.insert( make_pair( node, iPoint ));
831 TPoint* keyPoint = &myPoints[ iPoint++ ];
832 vPoint->push_back( keyPoint );
834 keyPoint->myInitUV = project( node, projector );
836 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
837 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
840 if ( !vPoint->empty() )
841 ePoints.push_back( vPoint->front() );
843 // compute U of edge-points
846 double totalDist = 0;
847 list< TPoint* >::iterator pIt = ePoints.begin();
848 TPoint* prevP = *pIt;
849 prevP->myInitU = totalDist;
850 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
852 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
853 p->myInitU = totalDist;
856 if ( totalDist > DBL_MIN)
857 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
859 p->myInitU /= totalDist;
862 } // loop on edges of a wire
864 // Load in-face points and elements
866 if ( fSubMesh && fSubMesh->NbElements() )
868 list< TPoint* > & fPoints = getShapePoints( face );
869 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
870 while ( nIt->more() )
872 const SMDS_MeshNode* node = nIt->next();
873 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
875 nodePointIDMap.insert( make_pair( node, iPoint ));
876 TPoint* p = &myPoints[ iPoint++ ];
877 fPoints.push_back( p );
879 p->myInitUV = project( node, projector );
881 const SMDS_FacePosition* pos =
882 static_cast<const SMDS_FacePosition*>(node->GetPosition());
883 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
885 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
888 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
889 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
890 while ( elemIt->more() )
892 const SMDS_MeshElement* elem = elemIt->next();
893 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
894 myElemPointIDs.push_back( TElemDef() );
895 TElemDef& elemPoints = myElemPointIDs.back();
896 // find point indices corresponding to element nodes
897 while ( nIt->more() )
899 const SMDS_MeshNode* node = smdsNode( nIt->next() );
900 n_id = nodePointIDMap.find( node );
901 if ( n_id == nodePointIDMap.end() )
902 continue; // medium node
903 iPoint = n_id->second; // point index of interest
904 // for a node on a seam edge there are two points
905 if ( helper.IsRealSeam( node->getshapeId() ) &&
906 ( n_id = closeNodePointIDMap.find( node )) != not_found )
908 TPoint & p1 = myPoints[ iPoint ];
909 TPoint & p2 = myPoints[ n_id->second ];
910 // Select point closest to the rest nodes of element in UV space
911 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
912 const SMDS_MeshNode* notSeamNode = 0;
913 // find node not on a seam edge
914 while ( nIt2->more() && !notSeamNode ) {
915 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
916 if ( !helper.IsSeamShape( n->getshapeId() ))
919 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
920 double dist1 = uv.SquareDistance( p1.myInitUV );
921 double dist2 = uv.SquareDistance( p2.myInitUV );
923 iPoint = n_id->second;
925 elemPoints.push_back( iPoint );
929 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
931 myIsBoundaryPointsFound = true;
934 // Assure that U range is proportional to V range
937 vector< TPoint >::iterator pVecIt = myPoints.begin();
938 for ( ; pVecIt != myPoints.end(); pVecIt++ )
939 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
940 double minU, minV, maxU, maxV;
941 bndBox.Get( minU, minV, maxU, maxV );
942 double dU = maxU - minU, dV = maxV - minV;
943 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
946 // define where is the problem, in the face or in the mesh
947 TopExp_Explorer vExp( face, TopAbs_VERTEX );
948 for ( ; vExp.More(); vExp.Next() ) {
949 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
952 bndBox.Get( minU, minV, maxU, maxV );
953 dU = maxU - minU, dV = maxV - minV;
954 if ( dU <= DBL_MIN || dV <= DBL_MIN )
956 return setErrorCode( ERR_LOADF_NARROW_FACE );
958 // mesh is projected onto a line, e.g.
959 return setErrorCode( ERR_LOADF_CANT_PROJECT );
961 double ratio = dU / dV, maxratio = 3, scale;
963 if ( ratio > maxratio ) {
964 scale = ratio / maxratio;
967 else if ( ratio < 1./maxratio ) {
968 scale = maxratio / ratio;
973 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
974 TPoint & p = *pVecIt;
975 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
976 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
979 if ( myElemPointIDs.empty() ) {
980 MESSAGE( "No elements bound to the face");
981 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
984 return setErrorCode( ERR_OK );
987 //=======================================================================
988 //function : computeUVOnEdge
989 //purpose : compute coordinates of points on theEdge
990 //=======================================================================
992 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
993 const list< TPoint* > & ePoints )
995 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
997 Handle(Geom2d_Curve) C2d =
998 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1000 ePoints.back()->myInitU = 1.0;
1001 list< TPoint* >::const_iterator pIt = ePoints.begin();
1002 for ( pIt++; pIt != ePoints.end(); pIt++ )
1004 TPoint* point = *pIt;
1006 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1007 point->myU = ( f * ( 1 - du ) + l * du );
1009 point->myUV = C2d->Value( point->myU ).XY();
1013 //=======================================================================
1014 //function : intersectIsolines
1016 //=======================================================================
1018 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1019 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1023 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1024 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1025 resUV = 0.5 * ( loc1 + loc2 );
1026 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1027 // SKL 26.07.2007 for NPAL16567
1028 double d1 = (uv11-uv12).Modulus();
1029 double d2 = (uv21-uv22).Modulus();
1030 // double delta = d1*d2*1e-6; PAL17233
1031 double delta = min( d1, d2 ) / 10.;
1032 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1034 // double len1 = ( uv11 - uv12 ).Modulus();
1035 // double len2 = ( uv21 - uv22 ).Modulus();
1036 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1040 // gp_Lin2d line1( uv11, uv12 - uv11 );
1041 // gp_Lin2d line2( uv21, uv22 - uv21 );
1042 // double angle = Abs( line1.Angle( line2 ) );
1044 // IntAna2d_AnaIntersection inter;
1045 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1046 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1048 // gp_Pnt2d interUV = inter.Point(1).Value();
1049 // resUV += interUV.XY();
1050 // inter.Perform( line1, line2 );
1051 // interUV = inter.Point(1).Value();
1052 // resUV += interUV.XY();
1057 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1058 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1063 //=======================================================================
1064 //function : compUVByIsoIntersection
1066 //=======================================================================
1068 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1069 const gp_XY& theInitUV,
1071 bool & theIsDeformed )
1073 // compute UV by intersection of 2 iso lines
1074 //gp_Lin2d isoLine[2];
1075 gp_XY uv1[2], uv2[2];
1077 const double zero = DBL_MIN;
1078 for ( int iIso = 0; iIso < 2; iIso++ )
1080 // to build an iso line:
1081 // find 2 pairs of consequent edge-points such that the range of their
1082 // initial parameters encloses the in-face point initial parameter
1083 gp_XY UV[2], initUV[2];
1084 int nbUV = 0, iCoord = iIso + 1;
1085 double initParam = theInitUV.Coord( iCoord );
1087 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1088 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1090 const list< TPoint* > & bndPoints = * bndIt;
1091 TPoint* prevP = bndPoints.back(); // this is the first point
1092 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1093 bool coincPrev = false;
1094 // loop on the edge-points
1095 for ( ; pIt != bndPoints.end(); pIt++ )
1097 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1098 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1099 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1100 if (!coincPrev && // ignore if initParam coincides with prev point param
1101 sumOfDiff > zero && // ignore if both points coincide with initParam
1102 prevParamDiff * paramDiff <= zero )
1104 // find UV in parametric space of theFace
1105 double r = Abs(prevParamDiff) / sumOfDiff;
1106 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1109 // throw away uv most distant from <theInitUV>
1110 gp_XY vec0 = initUV[0] - theInitUV;
1111 gp_XY vec1 = initUV[1] - theInitUV;
1112 gp_XY vec = uvInit - theInitUV;
1113 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1114 double dist0 = vec0.SquareModulus();
1115 double dist1 = vec1.SquareModulus();
1116 double dist = vec .SquareModulus();
1117 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1118 i = ( dist0 < dist1 ? 1 : 0 );
1119 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1120 i = 3; // theInitUV must remain between
1124 initUV[ i ] = uvInit;
1125 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1127 coincPrev = ( Abs(paramDiff) <= zero );
1134 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1135 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1136 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1137 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1139 // an iso line should be normal to UV[0] - UV[1] direction
1140 // and be located at the same relative distance as from initial ends
1141 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1143 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1144 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1145 //isoLine[ iIso ] = iso.Normal( isoLoc );
1146 uv1[ iIso ] = UV[0];
1147 uv2[ iIso ] = UV[1];
1150 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1151 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1152 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1153 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1160 // ==========================================================
1161 // structure representing a node of a grid of iso-poly-lines
1162 // ==========================================================
1169 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1170 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1171 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1172 TIsoNode(double initU, double initV):
1173 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1174 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1175 bool IsUVComputed() const
1176 { return myUV.X() != 1e100; }
1177 bool IsMovable() const
1178 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1179 void SetNotMovable()
1180 { myIsMovable = false; }
1181 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1182 { myBndNodes[ iDir + i * 2 ] = node; }
1183 TIsoNode* GetBoundaryNode(int iDir, int i)
1184 { return myBndNodes[ iDir + i * 2 ]; }
1185 void SetNext(TIsoNode* node, int iDir, int isForward)
1186 { myNext[ iDir + isForward * 2 ] = node; }
1187 TIsoNode* GetNext(int iDir, int isForward)
1188 { return myNext[ iDir + isForward * 2 ]; }
1191 //=======================================================================
1192 //function : getNextNode
1194 //=======================================================================
1196 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1198 TIsoNode* n = node->myNext[ dir ];
1199 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1200 n = 0;//node->myBndNodes[ dir ];
1201 // MESSAGE("getNextNode: use bnd for node "<<
1202 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1206 //=======================================================================
1207 //function : checkQuads
1208 //purpose : check if newUV destortes quadrangles around node,
1209 // and if ( crit == FIX_OLD ) fix newUV in this case
1210 //=======================================================================
1212 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1214 static bool checkQuads (const TIsoNode* node,
1216 const bool reversed,
1217 const int crit = FIX_OLD,
1218 double fixSize = 0.)
1220 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1221 int nbOldFix = 0, nbOldImpr = 0;
1222 double newBadRate = 0, oldBadRate = 0;
1223 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1224 int i, dir1 = 0, dir2 = 3;
1225 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1227 if ( dir2 > 3 ) dir2 = 0;
1229 // walking counterclockwise around a quad,
1230 // nodes are in the order: node, n[0], n[1], n[2]
1231 n[0] = getNextNode( node, dir1 );
1232 n[2] = getNextNode( node, dir2 );
1233 if ( !n[0] || !n[2] ) continue;
1234 n[1] = getNextNode( n[0], dir2 );
1235 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1236 bool isTriangle = ( !n[1] );
1238 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1240 // if ( fixSize != 0 ) {
1241 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1242 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1243 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1244 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1246 // check if a quadrangle is degenerated
1248 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1249 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1252 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1255 // find min size of the diagonal node-n[1]
1256 double minDiag = fixSize;
1257 if ( minDiag == 0. ) {
1258 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1259 if ( !isTriangle ) {
1260 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1261 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1263 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1264 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1267 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1268 // ( behind means "to the right of")
1270 // 1. newUV is not behind 01 and 12 dirs
1271 // 2. or newUV is not behind 02 dir and n[2] is convex
1272 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1273 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1274 gp_Vec2d moveVec[3], outVec[3];
1275 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1277 bool isDiag = ( i == 2 );
1278 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1282 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1284 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1286 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1288 gp_Vec2d newDir( n[i]->myUV, newUV );
1289 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1291 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1292 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1293 if ( crit == FIX_OLD ) {
1294 wasIn[i] = ( outDir * oldDir < 0 );
1295 wasOk[i] = ( outDir * oldDir < -minDiag );
1297 newBadRate += outDir * newDir;
1299 oldBadRate += outDir * oldDir;
1302 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1303 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1304 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1305 moveVec[i] = ( oldDist - minDiag ) * outDir;
1310 // check if n[2] is convex
1313 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1315 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1316 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1317 newIsOk = ( newIsOk && isNewOk );
1318 newIsIn = ( newIsIn && isNewIn );
1320 if ( crit != FIX_OLD ) {
1321 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1322 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1326 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1327 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1328 oldIsIn = ( oldIsIn && isOldIn );
1329 oldIsOk = ( oldIsOk && isOldIn );
1332 if ( !isOldIn ) { // node is outside a quadrangle
1333 // move newUV inside a quadrangle
1334 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1335 // node and newUV are outside: push newUV inside
1337 if ( convex || isTriangle ) {
1338 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1341 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1342 double outSize = out.Magnitude();
1343 if ( outSize > DBL_MIN )
1346 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1347 uv = n[1]->myUV - minDiag * out.XY();
1349 oldUVFixed[ nbOldFix++ ] = uv;
1350 //node->myUV = newUV;
1352 else if ( !isOldOk ) {
1353 // try to fix old UV: move node inside as less as possible
1354 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1355 gp_XY uv1, uv2 = node->myUV;
1356 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1358 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1359 while ( !isOldOk ) {
1360 // find the least moveVec
1362 double minMove2 = 1e100;
1363 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1365 if ( moveVec[i].Coord(1) < 1e100 ) {
1366 double move2 = moveVec[i].SquareMagnitude();
1367 if ( move2 < minMove2 ) {
1376 // move node to newUV
1377 uv1 = node->myUV + moveVec[ iMin ].XY();
1378 uv2 += moveVec[ iMin ].XY();
1379 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1380 // check if uv1 is ok
1381 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1382 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1383 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1385 oldUVImpr[ nbOldImpr++ ] = uv1;
1387 // check if uv2 is ok
1388 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1389 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1390 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1392 oldUVImpr[ nbOldImpr++ ] = uv2;
1397 } // loop on 4 quadrangles around <node>
1399 if ( crit == CHECK_NEW_OK )
1401 if ( crit == CHECK_NEW_IN )
1410 if ( oldIsIn && nbOldImpr ) {
1411 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1412 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1413 gp_XY uv = oldUVImpr[ 0 ];
1414 for ( int i = 1; i < nbOldImpr; i++ )
1415 uv += oldUVImpr[ i ];
1417 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1422 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1425 if ( !oldIsIn && nbOldFix ) {
1426 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1427 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1428 gp_XY uv = oldUVFixed[ 0 ];
1429 for ( int i = 1; i < nbOldFix; i++ )
1430 uv += oldUVFixed[ i ];
1432 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1437 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1440 if ( newIsIn && oldIsIn )
1441 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1442 else if ( !newIsIn )
1449 //=======================================================================
1450 //function : compUVByElasticIsolines
1451 //purpose : compute UV as nodes of iso-poly-lines consisting of
1452 // segments keeping relative size as in the pattern
1453 //=======================================================================
1454 //#define DEB_COMPUVBYELASTICISOLINES
1455 bool SMESH_Pattern::
1456 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1457 const list< TPoint* >& thePntToCompute)
1459 return false; // PAL17233
1460 //cout << "============================== KEY POINTS =============================="<<endl;
1461 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1462 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1463 // TPoint& p = myPoints[ *kpIt ];
1464 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1465 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1467 //cout << "=============================="<<endl;
1469 // Define parameters of iso-grid nodes in U and V dir
1471 set< double > paramSet[ 2 ];
1472 list< list< TPoint* > >::const_iterator pListIt;
1473 list< TPoint* >::const_iterator pIt;
1474 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1475 const list< TPoint* > & pList = * pListIt;
1476 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1477 paramSet[0].insert( (*pIt)->myInitUV.X() );
1478 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1481 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1482 paramSet[0].insert( (*pIt)->myInitUV.X() );
1483 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1485 // unite close parameters and split too long segments
1488 for ( iDir = 0; iDir < 2; iDir++ )
1490 set< double > & params = paramSet[ iDir ];
1491 double range = ( *params.rbegin() - *params.begin() );
1492 double toler = range / 1e6;
1493 tol[ iDir ] = toler;
1494 // double maxSegment = range / params.size() / 2.;
1496 // set< double >::iterator parIt = params.begin();
1497 // double prevPar = *parIt;
1498 // for ( parIt++; parIt != params.end(); parIt++ )
1500 // double segLen = (*parIt) - prevPar;
1501 // if ( segLen < toler )
1502 // ;//params.erase( prevPar ); // unite
1503 // else if ( segLen > maxSegment )
1504 // params.insert( prevPar + 0.5 * segLen ); // split
1505 // prevPar = (*parIt);
1509 // Make nodes of a grid of iso-poly-lines
1511 list < TIsoNode > nodes;
1512 typedef list < TIsoNode *> TIsoLine;
1513 map < double, TIsoLine > isoMap[ 2 ];
1515 set< double > & params0 = paramSet[ 0 ];
1516 set< double >::iterator par0It = params0.begin();
1517 for ( ; par0It != params0.end(); par0It++ )
1519 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1520 set< double > & params1 = paramSet[ 1 ];
1521 set< double >::iterator par1It = params1.begin();
1522 for ( ; par1It != params1.end(); par1It++ )
1524 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1525 isoLine0.push_back( & nodes.back() );
1526 isoMap[1][ *par1It ].push_back( & nodes.back() );
1530 // Compute intersections of boundaries with iso-lines:
1531 // only boundary nodes will have computed UV so far
1534 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1535 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1536 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1538 const list< TPoint* > & bndPoints = * bndIt;
1539 TPoint* prevP = bndPoints.back(); // this is the first point
1540 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1541 // loop on the edge-points
1542 for ( ; pIt != bndPoints.end(); pIt++ )
1544 TPoint* point = *pIt;
1545 for ( iDir = 0; iDir < 2; iDir++ )
1547 const int iCoord = iDir + 1;
1548 const int iOtherCoord = 2 - iDir;
1549 double par1 = prevP->myInitUV.Coord( iCoord );
1550 double par2 = point->myInitUV.Coord( iCoord );
1551 double parDif = par2 - par1;
1552 if ( Abs( parDif ) <= DBL_MIN )
1554 // find iso-lines intersecting a bounadry
1555 double toler = tol[ 1 - iDir ];
1556 double minPar = Min ( par1, par2 );
1557 double maxPar = Max ( par1, par2 );
1558 map < double, TIsoLine >& isos = isoMap[ iDir ];
1559 map < double, TIsoLine >::iterator isoIt = isos.begin();
1560 for ( ; isoIt != isos.end(); isoIt++ )
1562 double isoParam = (*isoIt).first;
1563 if ( isoParam < minPar || isoParam > maxPar )
1565 double r = ( isoParam - par1 ) / parDif;
1566 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1567 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1568 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1569 // find existing node with otherPar or insert a new one
1570 TIsoLine & isoLine = (*isoIt).second;
1572 TIsoLine::iterator nIt = isoLine.begin();
1573 for ( ; nIt != isoLine.end(); nIt++ ) {
1574 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1575 if ( nodePar >= otherPar )
1579 if ( Abs( nodePar - otherPar ) <= toler )
1580 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1582 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1583 node = & nodes.back();
1584 isoLine.insert( nIt, node );
1586 node->SetNotMovable();
1588 uvBnd.Add( gp_Pnt2d( uv ));
1589 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1591 gp_XY tgt( point->myUV - prevP->myUV );
1592 if ( ::IsEqual( r, 1. ))
1593 node->myDir[ 0 ] = tgt;
1594 else if ( ::IsEqual( r, 0. ))
1595 node->myDir[ 1 ] = tgt;
1597 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1598 // keep boundary nodes corresponding to boundary points
1599 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1600 if ( bndNodes.empty() || bndNodes.back() != node )
1601 bndNodes.push_back( node );
1602 } // loop on isolines
1603 } // loop on 2 directions
1605 } // loop on boundary points
1606 } // loop on boundaries
1608 // Define orientation
1610 // find the point with the least X
1611 double leastX = DBL_MAX;
1612 TIsoNode * leftNode;
1613 list < TIsoNode >::iterator nodeIt = nodes.begin();
1614 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1615 TIsoNode & node = *nodeIt;
1616 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1617 leastX = node.myUV.X();
1620 // if ( node.IsUVComputed() ) {
1621 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1622 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1623 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1624 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1627 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1628 //SCRUTE( reversed );
1630 // Prepare internal nodes:
1632 // 2. compute ratios
1633 // 3. find boundary nodes for each node
1634 // 4. remove nodes out of the boundary
1635 for ( iDir = 0; iDir < 2; iDir++ )
1637 const int iCoord = 2 - iDir; // coord changing along an isoline
1638 map < double, TIsoLine >& isos = isoMap[ iDir ];
1639 map < double, TIsoLine >::iterator isoIt = isos.begin();
1640 for ( ; isoIt != isos.end(); isoIt++ )
1642 TIsoLine & isoLine = (*isoIt).second;
1643 bool firstCompNodeFound = false;
1644 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1645 nPrevIt = nIt = nNextIt = isoLine.begin();
1647 nNextIt++; nNextIt++;
1648 while ( nIt != isoLine.end() )
1650 // 1. connect prev - cur
1651 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1652 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1653 firstCompNodeFound = true;
1654 lastCompNodePos = nPrevIt;
1656 if ( firstCompNodeFound ) {
1657 node->SetNext( prevNode, iDir, 0 );
1658 prevNode->SetNext( node, iDir, 1 );
1661 if ( nNextIt != isoLine.end() ) {
1662 double par1 = prevNode->myInitUV.Coord( iCoord );
1663 double par2 = node->myInitUV.Coord( iCoord );
1664 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1665 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1667 // 3. find boundary nodes
1668 if ( node->IsUVComputed() )
1669 lastCompNodePos = nIt;
1670 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1671 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1672 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1673 if ( (*nIt2)->IsUVComputed() )
1675 if ( nIt2 != isoLine.end() ) {
1677 node->SetBoundaryNode( bndNode1, iDir, 0 );
1678 node->SetBoundaryNode( bndNode2, iDir, 1 );
1679 // cout << "--------------------------------------------------"<<endl;
1680 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1681 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1682 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1683 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1684 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1685 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1688 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1689 node->SetBoundaryNode( 0, iDir, 0 );
1690 node->SetBoundaryNode( 0, iDir, 1 );
1694 if ( nNextIt != isoLine.end() ) nNextIt++;
1695 // 4. remove nodes out of the boundary
1696 if ( !firstCompNodeFound )
1697 isoLine.pop_front();
1698 } // loop on isoLine nodes
1700 // remove nodes after the boundary
1701 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1702 // (*nIt)->SetNotMovable();
1703 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1704 } // loop on isolines
1705 } // loop on 2 directions
1707 // Compute local isoline direction for internal nodes
1710 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1711 map < double, TIsoLine >::iterator isoIt = isos.begin();
1712 for ( ; isoIt != isos.end(); isoIt++ )
1714 TIsoLine & isoLine = (*isoIt).second;
1715 TIsoLine::iterator nIt = isoLine.begin();
1716 for ( ; nIt != isoLine.end(); nIt++ )
1718 TIsoNode* node = *nIt;
1719 if ( node->IsUVComputed() || !node->IsMovable() )
1721 gp_Vec2d aTgt[2], aNorm[2];
1724 for ( iDir = 0; iDir < 2; iDir++ )
1726 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1727 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1728 if ( !bndNode1 || !bndNode2 ) {
1732 const int iCoord = 2 - iDir; // coord changing along an isoline
1733 double par1 = bndNode1->myInitUV.Coord( iCoord );
1734 double par2 = node->myInitUV.Coord( iCoord );
1735 double par3 = bndNode2->myInitUV.Coord( iCoord );
1736 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1738 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1739 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1740 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1741 else tgt1.Reverse();
1742 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1744 if ( ratio[ iDir ] < 0.5 )
1745 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1747 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1749 aNorm[ iDir ].Reverse(); // along iDir isoline
1751 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1752 // maybe angle is more than |PI|
1753 if ( Abs( angle ) > PI / 2. ) {
1754 // check direction of the last but one perpendicular isoline
1755 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1756 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1757 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1758 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1759 if ( isoDir * tgt2 < 0 )
1761 double angle2 = tgt1.Angle( isoDir );
1762 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1763 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1764 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1765 //MESSAGE("REVERSE ANGLE");
1768 if ( Abs( angle2 ) > Abs( angle ) ||
1769 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1770 //MESSAGE("Add PI");
1771 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1772 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1773 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1774 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1775 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1776 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1779 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1783 for ( iDir = 0; iDir < 2; iDir++ )
1785 aTgt[iDir].Normalize();
1786 aNorm[1-iDir].Normalize();
1787 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1790 node->myDir[iDir] = //aTgt[iDir];
1791 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1793 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1794 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1795 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1796 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1798 } // loop on iso nodes
1799 } // loop on isolines
1801 // Find nodes to start computing UV from
1803 list< TIsoNode* > startNodes;
1804 list< TIsoNode* >::iterator nIt = bndNodes.end();
1805 TIsoNode* node = *(--nIt);
1806 TIsoNode* prevNode = *(--nIt);
1807 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1809 TIsoNode* nextNode = *nIt;
1810 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1811 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1812 double initAngle = initTgt1.Angle( initTgt2 );
1813 double angle = node->myDir[0].Angle( node->myDir[1] );
1814 if ( reversed ) angle = -angle;
1815 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1816 // find a close internal node
1817 TIsoNode* nClose = 0;
1818 list< TIsoNode* > testNodes;
1819 testNodes.push_back( node );
1820 list< TIsoNode* >::iterator it = testNodes.begin();
1821 for ( ; !nClose && it != testNodes.end(); it++ )
1823 for (int i = 0; i < 4; i++ )
1825 nClose = (*it)->myNext[ i ];
1827 if ( !nClose->IsUVComputed() )
1830 testNodes.push_back( nClose );
1836 startNodes.push_back( nClose );
1837 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1838 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1839 // "initAngle: " << initAngle << " angle: " << angle << endl;
1840 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1841 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1842 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1843 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1849 // Compute starting UV of internal nodes
1851 list < TIsoNode* > internNodes;
1852 bool needIteration = true;
1853 if ( startNodes.empty() ) {
1854 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1855 needIteration = false;
1856 map < double, TIsoLine >& isos = isoMap[ 0 ];
1857 map < double, TIsoLine >::iterator isoIt = isos.begin();
1858 for ( ; isoIt != isos.end(); isoIt++ )
1860 TIsoLine & isoLine = (*isoIt).second;
1861 TIsoLine::iterator nIt = isoLine.begin();
1862 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1864 TIsoNode* node = *nIt;
1865 if ( !node->IsUVComputed() && node->IsMovable() ) {
1866 internNodes.push_back( node );
1868 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1869 node->myUV, needIteration ))
1870 node->myUV = node->myInitUV;
1874 if ( needIteration )
1875 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1877 TIsoNode* node = *nIt, *nClose = 0;
1878 list< TIsoNode* > testNodes;
1879 testNodes.push_back( node );
1880 list< TIsoNode* >::iterator it = testNodes.begin();
1881 for ( ; !nClose && it != testNodes.end(); it++ )
1883 for (int i = 0; i < 4; i++ )
1885 nClose = (*it)->myNext[ i ];
1887 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1890 testNodes.push_back( nClose );
1896 startNodes.push_back( nClose );
1900 double aMin[2], aMax[2], step[2];
1901 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1902 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1903 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1904 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1905 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1907 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1909 TIsoNode *node = *nIt;
1910 if ( node->IsUVComputed() || !node->IsMovable() )
1912 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1913 int nbComp = 0, nbPrev = 0;
1914 for ( iDir = 0; iDir < 2; iDir++ )
1916 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1917 TIsoNode* n = node->GetNext( iDir, 0 );
1918 if ( n->IsUVComputed() )
1921 startNodes.push_back( n );
1922 n = node->GetNext( iDir, 1 );
1923 if ( n->IsUVComputed() )
1926 startNodes.push_back( n );
1928 prevNode1 = prevNode2;
1931 if ( prevNode1 ) nbPrev++;
1932 if ( prevNode2 ) nbPrev++;
1935 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1936 double par = node->myInitUV.Coord( 2 - iDir );
1937 bool isEnd = ( prevPar > par );
1938 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1939 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1940 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1942 MESSAGE("Why we are here?");
1945 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1946 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1947 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1948 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1949 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1950 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1951 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1952 //" par: " << prevPar << endl;
1953 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1954 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1956 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1957 gp_XY & uv1 = prevNode1->myUV;
1958 gp_XY & uv2 = prevNode2->myUV;
1959 // dir = ( uv2 - uv1 );
1960 // double len = dir.Modulus();
1961 // if ( len > DBL_MIN )
1962 // dir /= len * 0.5;
1963 double r = node->myRatio[ iDir ];
1964 newUV += uv1 * ( 1 - r ) + uv2 * r;
1967 newUV += prevNode1->myUV + dir * step[ iDir ];
1973 if ( !nbComp ) continue;
1976 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1978 // check if a quadrangle is not distorted
1980 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1981 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1982 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1983 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1987 internNodes.push_back( node );
1992 static int maxNbIter = 100;
1993 #ifdef DEB_COMPUVBYELASTICISOLINES
1995 bool useNbMoveNode = 0;
1996 static int maxNbNodeMove = 100;
1999 if ( !useNbMoveNode )
2000 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2005 if ( !needIteration) break;
2006 #ifdef DEB_COMPUVBYELASTICISOLINES
2007 if ( nbIter >= maxNbIter ) break;
2010 list < TIsoNode* >::iterator nIt = internNodes.begin();
2011 for ( ; nIt != internNodes.end(); nIt++ ) {
2012 #ifdef DEB_COMPUVBYELASTICISOLINES
2014 cout << nbNodeMove <<" =================================================="<<endl;
2016 TIsoNode * node = *nIt;
2020 for ( iDir = 0; iDir < 2; iDir++ )
2022 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2023 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2024 double r = node->myRatio[ iDir ];
2025 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2026 // line[ iDir ].SetLocation( loc[ iDir ] );
2027 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2030 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2031 // double locR[2] = { 0, 0 };
2032 for ( iDir = 0; iDir < 2; iDir++ )
2034 const int iCoord = 2 - iDir; // coord changing along an isoline
2035 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2036 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2037 if ( !bndNode1 || !bndNode2 ) {
2040 double par1 = bndNode1->myInitUV.Coord( iCoord );
2041 double par2 = node->myInitUV.Coord( iCoord );
2042 double par3 = bndNode2->myInitUV.Coord( iCoord );
2043 double r = ( par2 - par1 ) / ( par3 - par1 );
2044 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2045 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2047 //locR[0] = locR[1] = 0.25;
2048 // intersect the 2 lines and move a node
2049 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2050 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2052 // double intR = 1 - locR[0] - locR[1];
2053 // gp_XY newUV = inter.Point(1).Value().XY();
2054 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2055 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2057 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2058 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2059 // avoid parallel isolines intersection
2060 checkQuads( node, newUV, reversed );
2062 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2064 } // intersection found
2065 #ifdef DEB_COMPUVBYELASTICISOLINES
2066 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2068 } // loop on internal nodes
2069 #ifdef DEB_COMPUVBYELASTICISOLINES
2070 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2072 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2074 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2076 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2077 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2078 #ifndef DEB_COMPUVBYELASTICISOLINES
2083 // Set computed UV to points
2085 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2086 TPoint* point = *pIt;
2087 //gp_XY oldUV = point->myUV;
2088 double minDist = DBL_MAX;
2089 list < TIsoNode >::iterator nIt = nodes.begin();
2090 for ( ; nIt != nodes.end(); nIt++ ) {
2091 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2092 if ( dist < minDist ) {
2094 point->myUV = (*nIt).myUV;
2103 //=======================================================================
2104 //function : setFirstEdge
2105 //purpose : choose the best first edge of theWire; return the summary distance
2106 // between point UV computed by isolines intersection and
2107 // eventual UV got from edge p-curves
2108 //=======================================================================
2110 //#define DBG_SETFIRSTEDGE
2111 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2113 int iE, nbEdges = theWire.size();
2117 // Transform UVs computed by iso to fit bnd box of a wire
2119 // max nb of points on an edge
2121 int eID = theFirstEdgeID;
2122 for ( iE = 0; iE < nbEdges; iE++ )
2123 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2125 // compute bnd boxes
2126 TopoDS_Face face = TopoDS::Face( myShape );
2127 Bnd_Box2d bndBox, eBndBox;
2128 eID = theFirstEdgeID;
2129 list< TopoDS_Edge >::iterator eIt;
2130 list< TPoint* >::iterator pIt;
2131 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2133 // UV by isos stored in TPoint.myXYZ
2134 list< TPoint* > & ePoints = getShapePoints( eID++ );
2135 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2137 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2139 // UV by an edge p-curve
2141 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2142 double dU = ( l - f ) / ( maxNbPnt - 1 );
2143 for ( int i = 0; i < maxNbPnt; i++ )
2144 eBndBox.Add( C2d->Value( f + i * dU ));
2147 // transform UVs by isos
2148 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2149 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2150 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2151 #ifdef DBG_SETFIRSTEDGE
2152 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2153 << eMinPar[1] << " - " << eMaxPar[1] );
2155 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2157 double dMin = eMinPar[i] - minPar[i];
2158 double dMax = eMaxPar[i] - maxPar[i];
2159 double dPar = maxPar[i] - minPar[i];
2160 eID = theFirstEdgeID;
2161 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2163 list< TPoint* > & ePoints = getShapePoints( eID++ );
2164 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2166 double par = (*pIt)->myXYZ.Coord( iC );
2167 double r = ( par - minPar[i] ) / dPar;
2168 par += ( 1 - r ) * dMin + r * dMax;
2169 (*pIt)->myXYZ.SetCoord( iC, par );
2175 double minDist = DBL_MAX;
2176 for ( iE = 0 ; iE < nbEdges; iE++ )
2178 #ifdef DBG_SETFIRSTEDGE
2179 MESSAGE ( " VARIANT " << iE );
2181 // evaluate the distance between UV computed by the 2 methods:
2182 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2184 int eID = theFirstEdgeID;
2185 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2187 list< TPoint* > & ePoints = getShapePoints( eID++ );
2188 computeUVOnEdge( *eIt, ePoints );
2189 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2191 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2192 #ifdef DBG_SETFIRSTEDGE
2193 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2194 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2198 #ifdef DBG_SETFIRSTEDGE
2199 MESSAGE ( "dist -- " << dist );
2201 if ( dist < minDist ) {
2203 eBest = theWire.front();
2205 // check variant with another first edge
2206 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2208 // put the best first edge to the theWire front
2209 if ( eBest != theWire.front() ) {
2210 eIt = find ( theWire.begin(), theWire.end(), eBest );
2211 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2217 //=======================================================================
2218 //function : sortSameSizeWires
2219 //purpose : sort wires in theWireList from theFromWire until theToWire,
2220 // the wires are set in the order to correspond to the order
2221 // of boundaries; after sorting, edges in the wires are put
2222 // in a good order, point UVs on edges are computed and points
2223 // are appended to theEdgesPointsList
2224 //=======================================================================
2226 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2227 const TListOfEdgesList::iterator& theFromWire,
2228 const TListOfEdgesList::iterator& theToWire,
2229 const int theFirstEdgeID,
2230 list< list< TPoint* > >& theEdgesPointsList )
2232 TopoDS_Face F = TopoDS::Face( myShape );
2233 int iW, nbWires = 0;
2234 TListOfEdgesList::iterator wlIt = theFromWire;
2235 while ( wlIt++ != theToWire )
2238 // Recompute key-point UVs by isolines intersection,
2239 // compute CG of key-points for each wire and bnd boxes of GCs
2242 gp_XY orig( gp::Origin2d().XY() );
2243 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2244 Bnd_Box2d bndBox, vBndBox;
2245 int eID = theFirstEdgeID;
2246 list< TopoDS_Edge >::iterator eIt;
2247 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2249 list< TopoDS_Edge > & wire = *wlIt;
2250 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2252 list< TPoint* > & ePoints = getShapePoints( eID++ );
2253 TPoint* p = ePoints.front();
2254 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2255 MESSAGE("cant sortSameSizeWires()");
2258 gcVec[iW] += p->myUV;
2259 bndBox.Add( gp_Pnt2d( p->myUV ));
2260 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2261 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2262 vGcVec[iW] += vXY.XY();
2264 // keep the computed UV to compare against by setFirstEdge()
2265 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2267 gcVec[iW] /= nbWires;
2268 vGcVec[iW] /= nbWires;
2269 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2270 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2273 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2275 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2276 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2277 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2278 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2280 double dMin = vMinPar[i] - minPar[i];
2281 double dMax = vMaxPar[i] - maxPar[i];
2282 double dPar = maxPar[i] - minPar[i];
2283 if ( Abs( dPar ) <= DBL_MIN )
2285 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2286 double par = gcVec[iW].Coord( iC );
2287 double r = ( par - minPar[i] ) / dPar;
2288 par += ( 1 - r ) * dMin + r * dMax;
2289 gcVec[iW].SetCoord( iC, par );
2293 // Define boundary - wire correspondence by GC closeness
2295 TListOfEdgesList tmpWList;
2296 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2297 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2298 TIntWirePosMap bndIndWirePosMap;
2299 vector< bool > bndFound( nbWires, false );
2300 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2302 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2303 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2304 double minDist = DBL_MAX;
2305 gp_XY & wGc = vGcVec[ iW ];
2307 for ( int iB = 0; iB < nbWires; iB++ ) {
2308 if ( bndFound[ iB ] ) continue;
2309 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2310 if ( dist < minDist ) {
2315 bndFound[ bIndex ] = true;
2316 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2321 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2322 eID = theFirstEdgeID;
2323 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2325 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2326 list < TopoDS_Edge > & wire = ( *wirePos );
2328 // choose the best first edge of a wire
2329 setFirstEdge( wire, eID );
2331 // compute eventual UV and fill theEdgesPointsList
2332 theEdgesPointsList.push_back( list< TPoint* >() );
2333 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2334 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2336 list< TPoint* > & ePoints = getShapePoints( eID++ );
2337 computeUVOnEdge( *eIt, ePoints );
2338 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2340 // put wire back to theWireList
2342 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2348 //=======================================================================
2350 //purpose : Compute nodes coordinates applying
2351 // the loaded pattern to <theFace>. The first key-point
2352 // will be mapped into <theVertexOnKeyPoint1>
2353 //=======================================================================
2355 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2356 const TopoDS_Vertex& theVertexOnKeyPoint1,
2357 const bool theReverse)
2359 MESSAGE(" ::Apply(face) " );
2360 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2361 if ( !setShapeToMesh( face ))
2364 // find points on edges, it fills myNbKeyPntInBoundary
2365 if ( !findBoundaryPoints() )
2368 // Define the edges order so that the first edge starts at
2369 // theVertexOnKeyPoint1
2371 list< TopoDS_Edge > eList;
2372 list< int > nbVertexInWires;
2373 int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2374 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2376 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2377 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2379 // check nb wires and edges
2380 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2381 l1.sort(); l2.sort();
2384 MESSAGE( "Wrong nb vertices in wires" );
2385 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2388 // here shapes get IDs, for the outer wire IDs are OK
2389 list<TopoDS_Edge>::iterator elIt = eList.begin();
2390 for ( ; elIt != eList.end(); elIt++ ) {
2391 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2392 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2393 // BEGIN: jfa for bug 0019943
2396 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2397 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2399 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2400 if (we.Current().IsSame(*elIt)) {
2402 if (nbe == 2) isClosed1 = true;
2407 // END: jfa for bug 0019943
2409 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2411 int nbVertices = myShapeIDMap.Extent();
2413 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2414 myShapeIDMap.Add( *elIt );
2416 myShapeIDMap.Add( face );
2418 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2419 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2420 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2423 // points on edges to be used for UV computation of in-face points
2424 list< list< TPoint* > > edgesPointsList;
2425 edgesPointsList.push_back( list< TPoint* >() );
2426 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2427 list< TPoint* >::iterator pIt;
2429 // compute UV of points on the outer wire
2430 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2431 for (iE = 0, elIt = eList.begin();
2432 iE < nbEdgesInOuterWire && elIt != eList.end();
2435 list< TPoint* > & ePoints = getShapePoints( *elIt );
2437 computeUVOnEdge( *elIt, ePoints );
2438 // collect on-edge points (excluding the last one)
2439 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2442 // If there are several wires, define the order of edges of inner wires:
2443 // compute UV of inner edge-points using 2 methods: the one for in-face points
2444 // and the one for on-edge points and then choose the best edge order
2445 // by the best correspondance of the 2 results
2448 // compute UV of inner edge-points using the method for in-face points
2449 // and devide eList into a list of separate wires
2451 list< list< TopoDS_Edge > > wireList;
2452 list<TopoDS_Edge>::iterator eIt = elIt;
2453 list<int>::iterator nbEIt = nbVertexInWires.begin();
2454 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2456 int nbEdges = *nbEIt;
2457 wireList.push_back( list< TopoDS_Edge >() );
2458 list< TopoDS_Edge > & wire = wireList.back();
2459 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2461 list< TPoint* > & ePoints = getShapePoints( *eIt );
2462 pIt = ePoints.begin();
2463 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2465 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2466 MESSAGE("cant Apply(face)");
2469 // keep the computed UV to compare against by setFirstEdge()
2470 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2472 wire.push_back( *eIt );
2475 // remove inner edges from eList
2476 eList.erase( elIt, eList.end() );
2478 // sort wireList by nb edges in a wire
2479 sortBySize< TopoDS_Edge > ( wireList );
2481 // an ID of the first edge of a boundary
2482 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2483 // if ( nbSeamShapes > 0 )
2484 // id1 += 2; // 2 vertices more
2486 // find points - edge correspondence for wires of unique size,
2487 // edge order within a wire should be defined only
2489 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2490 while ( wlIt != wireList.end() )
2492 list< TopoDS_Edge >& wire = (*wlIt);
2493 int nbEdges = wire.size();
2495 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2497 // choose the best first edge of a wire
2498 setFirstEdge( wire, id1 );
2500 // compute eventual UV and collect on-edge points
2501 edgesPointsList.push_back( list< TPoint* >() );
2502 edgesPoints = & edgesPointsList.back();
2504 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2506 list< TPoint* > & ePoints = getShapePoints( eID++ );
2507 computeUVOnEdge( *eIt, ePoints );
2508 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2514 // find boundary - wire correspondence for several wires of same size
2516 id1 = nbVertices + nbEdgesInOuterWire + 1;
2517 wlIt = wireList.begin();
2518 while ( wlIt != wireList.end() )
2520 int nbSameSize = 0, nbEdges = (*wlIt).size();
2521 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2523 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2527 if ( nbSameSize > 0 )
2528 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2531 id1 += nbEdges * ( nbSameSize + 1 );
2534 // add well-ordered edges to eList
2536 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2538 list< TopoDS_Edge >& wire = (*wlIt);
2539 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2542 // re-fill myShapeIDMap - all shapes get good IDs
2544 myShapeIDMap.Clear();
2545 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2546 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2547 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2548 myShapeIDMap.Add( *elIt );
2549 myShapeIDMap.Add( face );
2551 } // there are inner wires
2553 // Compute XYZ of on-edge points
2555 TopLoc_Location loc;
2556 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2558 BRepAdaptor_Curve C3d( *elIt );
2559 list< TPoint* > & ePoints = getShapePoints( iE++ );
2560 pIt = ePoints.begin();
2561 for ( pIt++; pIt != ePoints.end(); pIt++ )
2563 TPoint* point = *pIt;
2564 point->myXYZ = C3d.Value( point->myU );
2568 // Compute UV and XYZ of in-face points
2570 // try to use a simple algo
2571 list< TPoint* > & fPoints = getShapePoints( face );
2572 bool isDeformed = false;
2573 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2574 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2575 (*pIt)->myUV, isDeformed )) {
2576 MESSAGE("cant Apply(face)");
2579 // try to use a complex algo if it is a difficult case
2580 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2582 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2583 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2584 (*pIt)->myUV, isDeformed )) {
2585 MESSAGE("cant Apply(face)");
2590 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2591 const gp_Trsf & aTrsf = loc.Transformation();
2592 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2594 TPoint * point = *pIt;
2595 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2596 if ( !loc.IsIdentity() )
2597 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2600 myIsComputed = true;
2602 return setErrorCode( ERR_OK );
2605 //=======================================================================
2607 //purpose : Compute nodes coordinates applying
2608 // the loaded pattern to <theFace>. The first key-point
2609 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2610 //=======================================================================
2612 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2613 const int theNodeIndexOnKeyPoint1,
2614 const bool theReverse)
2616 // MESSAGE(" ::Apply(MeshFace) " );
2618 if ( !IsLoaded() ) {
2619 MESSAGE( "Pattern not loaded" );
2620 return setErrorCode( ERR_APPL_NOT_LOADED );
2623 // check nb of nodes
2624 const int nbFaceNodes = theFace->NbCornerNodes();
2625 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2626 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2627 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2630 // find points on edges, it fills myNbKeyPntInBoundary
2631 if ( !findBoundaryPoints() )
2634 // check that there are no holes in a pattern
2635 if (myNbKeyPntInBoundary.size() > 1 ) {
2636 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2639 // Define the nodes order
2641 list< const SMDS_MeshNode* > nodes;
2642 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2643 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2645 while ( noIt->more() && iSub < nbFaceNodes ) {
2646 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2647 nodes.push_back( node );
2648 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2651 if ( n != nodes.end() ) {
2653 if ( n != --nodes.end() )
2654 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2657 else if ( n != nodes.begin() )
2658 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2660 list< gp_XYZ > xyzList;
2661 myOrderedNodes.resize( nbFaceNodes );
2662 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2663 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2664 myOrderedNodes[ iSub++] = *n;
2667 // Define a face plane
2669 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2670 gp_Pnt P ( *xyzIt++ );
2671 gp_Vec Vx( P, *xyzIt++ ), N;
2673 N = Vx ^ gp_Vec( P, *xyzIt++ );
2674 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2675 if ( N.SquareMagnitude() <= DBL_MIN )
2676 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2677 gp_Ax2 pos( P, N, Vx );
2679 // Compute UV of key-points on a plane
2680 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2682 gp_Vec vec ( pos.Location(), *xyzIt );
2683 TPoint* p = getShapePoints( iSub ).front();
2684 p->myUV.SetX( vec * pos.XDirection() );
2685 p->myUV.SetY( vec * pos.YDirection() );
2689 // points on edges to be used for UV computation of in-face points
2690 list< list< TPoint* > > edgesPointsList;
2691 edgesPointsList.push_back( list< TPoint* >() );
2692 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2693 list< TPoint* >::iterator pIt;
2695 // compute UV and XYZ of points on edges
2697 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2699 gp_XYZ& xyz1 = *xyzIt++;
2700 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2702 list< TPoint* > & ePoints = getShapePoints( iSub );
2703 ePoints.back()->myInitU = 1.0;
2704 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2705 while ( *pIt != ePoints.back() )
2708 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2709 gp_Vec vec ( pos.Location(), p->myXYZ );
2710 p->myUV.SetX( vec * pos.XDirection() );
2711 p->myUV.SetY( vec * pos.YDirection() );
2713 // collect on-edge points (excluding the last one)
2714 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2717 // Compute UV and XYZ of in-face points
2719 // try to use a simple algo to compute UV
2720 list< TPoint* > & fPoints = getShapePoints( iSub );
2721 bool isDeformed = false;
2722 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2723 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2724 (*pIt)->myUV, isDeformed )) {
2725 MESSAGE("cant Apply(face)");
2728 // try to use a complex algo if it is a difficult case
2729 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2731 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2732 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2733 (*pIt)->myUV, isDeformed )) {
2734 MESSAGE("cant Apply(face)");
2739 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2741 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2744 myIsComputed = true;
2746 return setErrorCode( ERR_OK );
2749 //=======================================================================
2751 //purpose : Compute nodes coordinates applying
2752 // the loaded pattern to <theFace>. The first key-point
2753 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2754 //=======================================================================
2756 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2757 const SMDS_MeshFace* theFace,
2758 const TopoDS_Shape& theSurface,
2759 const int theNodeIndexOnKeyPoint1,
2760 const bool theReverse)
2762 // MESSAGE(" ::Apply(MeshFace) " );
2763 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2764 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2766 const TopoDS_Face& face = TopoDS::Face( theSurface );
2767 TopLoc_Location loc;
2768 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2769 const gp_Trsf & aTrsf = loc.Transformation();
2771 if ( !IsLoaded() ) {
2772 MESSAGE( "Pattern not loaded" );
2773 return setErrorCode( ERR_APPL_NOT_LOADED );
2776 // check nb of nodes
2777 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2778 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2779 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2782 // find points on edges, it fills myNbKeyPntInBoundary
2783 if ( !findBoundaryPoints() )
2786 // check that there are no holes in a pattern
2787 if (myNbKeyPntInBoundary.size() > 1 ) {
2788 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2791 // Define the nodes order
2793 list< const SMDS_MeshNode* > nodes;
2794 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2795 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2797 while ( noIt->more() ) {
2798 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2799 nodes.push_back( node );
2800 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2803 if ( n != nodes.end() ) {
2805 if ( n != --nodes.end() )
2806 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2809 else if ( n != nodes.begin() )
2810 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2813 // find a node not on a seam edge, if necessary
2814 SMESH_MesherHelper helper( *theMesh );
2815 helper.SetSubShape( theSurface );
2816 const SMDS_MeshNode* inFaceNode = 0;
2817 if ( helper.GetNodeUVneedInFaceNode() )
2819 SMESH_MeshEditor editor( theMesh );
2820 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2821 int shapeID = editor.FindShape( *n );
2823 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2824 if ( !helper.IsSeamShape( shapeID ))
2829 // Set UV of key-points (i.e. of nodes of theFace )
2830 vector< gp_XY > keyUV( theFace->NbNodes() );
2831 myOrderedNodes.resize( theFace->NbNodes() );
2832 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2834 TPoint* p = getShapePoints( iSub ).front();
2835 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2836 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2838 keyUV[ iSub-1 ] = p->myUV;
2839 myOrderedNodes[ iSub-1 ] = *n;
2842 // points on edges to be used for UV computation of in-face points
2843 list< list< TPoint* > > edgesPointsList;
2844 edgesPointsList.push_back( list< TPoint* >() );
2845 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2846 list< TPoint* >::iterator pIt;
2848 // compute UV and XYZ of points on edges
2850 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2852 gp_XY& uv1 = keyUV[ i ];
2853 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2855 list< TPoint* > & ePoints = getShapePoints( iSub );
2856 ePoints.back()->myInitU = 1.0;
2857 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2858 while ( *pIt != ePoints.back() )
2861 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2862 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2863 if ( !loc.IsIdentity() )
2864 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2866 // collect on-edge points (excluding the last one)
2867 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2870 // Compute UV and XYZ of in-face points
2872 // try to use a simple algo to compute UV
2873 list< TPoint* > & fPoints = getShapePoints( iSub );
2874 bool isDeformed = false;
2875 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2876 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2877 (*pIt)->myUV, isDeformed )) {
2878 MESSAGE("cant Apply(face)");
2881 // try to use a complex algo if it is a difficult case
2882 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2884 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2885 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2886 (*pIt)->myUV, isDeformed )) {
2887 MESSAGE("cant Apply(face)");
2892 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2894 TPoint * point = *pIt;
2895 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2896 if ( !loc.IsIdentity() )
2897 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2900 myIsComputed = true;
2902 return setErrorCode( ERR_OK );
2905 //=======================================================================
2906 //function : undefinedXYZ
2908 //=======================================================================
2910 static const gp_XYZ& undefinedXYZ()
2912 static gp_XYZ xyz( 1.e100, 0., 0. );
2916 //=======================================================================
2917 //function : isDefined
2919 //=======================================================================
2921 inline static bool isDefined(const gp_XYZ& theXYZ)
2923 return theXYZ.X() < 1.e100;
2926 //=======================================================================
2928 //purpose : Compute nodes coordinates applying
2929 // the loaded pattern to <theFaces>. The first key-point
2930 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2931 //=======================================================================
2933 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2934 std::set<const SMDS_MeshFace*>& theFaces,
2935 const int theNodeIndexOnKeyPoint1,
2936 const bool theReverse)
2938 MESSAGE(" ::Apply(set<MeshFace>) " );
2940 if ( !IsLoaded() ) {
2941 MESSAGE( "Pattern not loaded" );
2942 return setErrorCode( ERR_APPL_NOT_LOADED );
2945 // find points on edges, it fills myNbKeyPntInBoundary
2946 if ( !findBoundaryPoints() )
2949 // check that there are no holes in a pattern
2950 if (myNbKeyPntInBoundary.size() > 1 ) {
2951 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2956 myElemXYZIDs.clear();
2957 myXYZIdToNodeMap.clear();
2959 myIdsOnBoundary.clear();
2960 myReverseConnectivity.clear();
2962 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2963 myElements.reserve( theFaces.size() );
2965 // to find point index
2966 map< TPoint*, int > pointIndex;
2967 for ( int i = 0; i < myPoints.size(); i++ )
2968 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2970 int ind1 = 0; // lowest point index for a face
2975 // SMESH_MeshEditor editor( theMesh );
2977 // apply to each face in theFaces set
2978 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2979 for ( ; face != theFaces.end(); ++face )
2981 // int curShapeId = editor.FindShape( *face );
2982 // if ( curShapeId != shapeID ) {
2983 // if ( curShapeId )
2984 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2987 // shapeID = curShapeId;
2990 if ( shape.IsNull() )
2991 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2993 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2995 MESSAGE( "Failed on " << *face );
2998 myElements.push_back( *face );
3000 // store computed points belonging to elements
3001 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3002 for ( ; ll != myElemPointIDs.end(); ++ll )
3004 myElemXYZIDs.push_back(TElemDef());
3005 TElemDef& xyzIds = myElemXYZIDs.back();
3006 TElemDef& pIds = *ll;
3007 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3008 int pIndex = *id + ind1;
3009 xyzIds.push_back( pIndex );
3010 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3011 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3014 // put points on links to myIdsOnBoundary,
3015 // they will be used to sew new elements on adjacent refined elements
3016 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3017 for ( int i = 0; i < nbNodes; i++ )
3019 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3020 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3021 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
3022 // make a link and a node set
3023 TNodeSet linkSet, node1Set;
3024 linkSet.insert( n1 );
3025 linkSet.insert( n2 );
3026 node1Set.insert( n1 );
3027 list< TPoint* >::iterator p = linkPoints.begin();
3029 // map the first link point to n1
3030 int nId = pointIndex[ *p ] + ind1;
3031 myXYZIdToNodeMap[ nId ] = n1;
3032 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3033 groups.push_back(list< int > ());
3034 groups.back().push_back( nId );
3036 // add the linkSet to the map
3037 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3038 groups.push_back(list< int > ());
3039 list< int >& indList = groups.back();
3040 // add points to the map excluding the end points
3041 for ( p++; *p != linkPoints.back(); p++ )
3042 indList.push_back( pointIndex[ *p ] + ind1 );
3044 ind1 += myPoints.size();
3047 return !myElemXYZIDs.empty();
3050 //=======================================================================
3052 //purpose : Compute nodes coordinates applying
3053 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3054 // will be mapped into <theNode000Index>-th node. The
3055 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3057 //=======================================================================
3059 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3060 const int theNode000Index,
3061 const int theNode001Index)
3063 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3065 if ( !IsLoaded() ) {
3066 MESSAGE( "Pattern not loaded" );
3067 return setErrorCode( ERR_APPL_NOT_LOADED );
3070 // bind ID to points
3071 if ( !findBoundaryPoints() )
3074 // check that there are no holes in a pattern
3075 if (myNbKeyPntInBoundary.size() > 1 ) {
3076 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3081 myElemXYZIDs.clear();
3082 myXYZIdToNodeMap.clear();
3084 myIdsOnBoundary.clear();
3085 myReverseConnectivity.clear();
3087 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3088 myElements.reserve( theVolumes.size() );
3090 // to find point index
3091 map< TPoint*, int > pointIndex;
3092 for ( int i = 0; i < myPoints.size(); i++ )
3093 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3095 int ind1 = 0; // lowest point index for an element
3097 // apply to each element in theVolumes set
3098 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3099 for ( ; vol != theVolumes.end(); ++vol )
3101 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3102 MESSAGE( "Failed on " << *vol );
3105 myElements.push_back( *vol );
3107 // store computed points belonging to elements
3108 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3109 for ( ; ll != myElemPointIDs.end(); ++ll )
3111 myElemXYZIDs.push_back(TElemDef());
3112 TElemDef& xyzIds = myElemXYZIDs.back();
3113 TElemDef& pIds = *ll;
3114 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3115 int pIndex = *id + ind1;
3116 xyzIds.push_back( pIndex );
3117 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3118 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3121 // put points on edges and faces to myIdsOnBoundary,
3122 // they will be used to sew new elements on adjacent refined elements
3123 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3125 // make a set of sub-points
3127 vector< int > subIDs;
3128 if ( SMESH_Block::IsVertexID( Id )) {
3129 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3131 else if ( SMESH_Block::IsEdgeID( Id )) {
3132 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3133 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3134 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3137 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3138 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3139 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3140 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3141 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3142 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3143 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3144 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3147 list< TPoint* > & points = getShapePoints( Id );
3148 list< TPoint* >::iterator p = points.begin();
3149 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3150 groups.push_back(list< int > ());
3151 list< int >& indList = groups.back();
3152 for ( ; p != points.end(); p++ )
3153 indList.push_back( pointIndex[ *p ] + ind1 );
3154 if ( subNodes.size() == 1 ) // vertex case
3155 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3157 ind1 += myPoints.size();
3160 return !myElemXYZIDs.empty();
3163 //=======================================================================
3165 //purpose : Create a pattern from the mesh built on <theBlock>
3166 //=======================================================================
3168 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3169 const TopoDS_Shell& theBlock)
3171 MESSAGE(" ::Load(volume) " );
3174 SMESHDS_SubMesh * aSubMesh;
3176 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3178 // load shapes in myShapeIDMap
3180 TopoDS_Vertex v1, v2;
3181 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3182 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3185 int nbNodes = 0, shapeID;
3186 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3188 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3189 aSubMesh = getSubmeshWithElements( theMesh, S );
3191 nbNodes += aSubMesh->NbNodes();
3193 myPoints.resize( nbNodes );
3195 // load U of points on edges
3196 TNodePointIDMap nodePointIDMap;
3198 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3200 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3201 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3202 aSubMesh = getSubmeshWithElements( theMesh, S );
3203 if ( ! aSubMesh ) continue;
3204 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3205 if ( !nIt->more() ) continue;
3207 // store a node and a point
3208 while ( nIt->more() ) {
3209 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3210 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3212 nodePointIDMap.insert( make_pair( node, iPoint ));
3213 if ( block.IsVertexID( shapeID ))
3214 myKeyPointIDs.push_back( iPoint );
3215 TPoint* p = & myPoints[ iPoint++ ];
3216 shapePoints.push_back( p );
3217 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3218 p->myInitXYZ.SetCoord( 0,0,0 );
3220 list< TPoint* >::iterator pIt = shapePoints.begin();
3223 switch ( S.ShapeType() )
3228 for ( ; pIt != shapePoints.end(); pIt++ ) {
3229 double * coef = block.GetShapeCoef( shapeID );
3230 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3231 if ( coef[ iCoord - 1] > 0 )
3232 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3234 if ( S.ShapeType() == TopAbs_VERTEX )
3237 const TopoDS_Edge& edge = TopoDS::Edge( S );
3239 BRep_Tool::Range( edge, f, l );
3240 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3241 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3242 pIt = shapePoints.begin();
3243 nIt = aSubMesh->GetNodes();
3244 for ( ; nIt->more(); pIt++ )
3246 const SMDS_MeshNode* node = nIt->next();
3247 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3249 const SMDS_EdgePosition* epos =
3250 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3251 double u = ( epos->GetUParameter() - f ) / ( l - f );
3252 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3257 for ( ; pIt != shapePoints.end(); pIt++ )
3259 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3260 MESSAGE( "!block.ComputeParameters()" );
3261 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3265 } // loop on block sub-shapes
3269 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3272 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3273 while ( elemIt->more() ) {
3274 const SMDS_MeshElement* elem = elemIt->next();
3275 myElemPointIDs.push_back( TElemDef() );
3276 TElemDef& elemPoints = myElemPointIDs.back();
3277 int nbNodes = elem->NbCornerNodes();
3278 for ( int i = 0;i < nbNodes; ++i )
3279 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3283 myIsBoundaryPointsFound = true;
3285 return setErrorCode( ERR_OK );
3288 //=======================================================================
3289 //function : getSubmeshWithElements
3290 //purpose : return submesh containing elements bound to theBlock in theMesh
3291 //=======================================================================
3293 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3294 const TopoDS_Shape& theShape)
3296 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3297 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3300 if ( theShape.ShapeType() == TopAbs_SHELL )
3302 // look for submesh of VOLUME
3303 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3304 for (; it.More(); it.Next()) {
3305 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3306 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3314 //=======================================================================
3316 //purpose : Compute nodes coordinates applying
3317 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3318 // will be mapped into <theVertex000>. The (0,0,1)
3319 // fifth key-point will be mapped into <theVertex001>.
3320 //=======================================================================
3322 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3323 const TopoDS_Vertex& theVertex000,
3324 const TopoDS_Vertex& theVertex001)
3326 MESSAGE(" ::Apply(volume) " );
3328 if (!findBoundaryPoints() || // bind ID to points
3329 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3332 SMESH_Block block; // bind ID to shape
3333 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3334 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3336 // compute XYZ of points on shapes
3338 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3340 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3341 list< TPoint* >::iterator pIt = shapePoints.begin();
3342 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3343 switch ( S.ShapeType() )
3345 case TopAbs_VERTEX: {
3347 for ( ; pIt != shapePoints.end(); pIt++ )
3348 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3353 for ( ; pIt != shapePoints.end(); pIt++ )
3354 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3359 for ( ; pIt != shapePoints.end(); pIt++ )
3360 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3364 for ( ; pIt != shapePoints.end(); pIt++ )
3365 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3367 } // loop on block sub-shapes
3369 myIsComputed = true;
3371 return setErrorCode( ERR_OK );
3374 //=======================================================================
3376 //purpose : Compute nodes coordinates applying
3377 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3378 // will be mapped into <theNode000Index>-th node. The
3379 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3381 //=======================================================================
3383 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3384 const int theNode000Index,
3385 const int theNode001Index)
3387 //MESSAGE(" ::Apply(MeshVolume) " );
3389 if (!findBoundaryPoints()) // bind ID to points
3392 SMESH_Block block; // bind ID to shape
3393 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3394 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3395 // compute XYZ of points on shapes
3397 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3399 list< TPoint* > & shapePoints = getShapePoints( ID );
3400 list< TPoint* >::iterator pIt = shapePoints.begin();
3402 if ( block.IsVertexID( ID ))
3403 for ( ; pIt != shapePoints.end(); pIt++ ) {
3404 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3406 else if ( block.IsEdgeID( ID ))
3407 for ( ; pIt != shapePoints.end(); pIt++ ) {
3408 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3410 else if ( block.IsFaceID( ID ))
3411 for ( ; pIt != shapePoints.end(); pIt++ ) {
3412 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3415 for ( ; pIt != shapePoints.end(); pIt++ )
3416 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3417 } // loop on block sub-shapes
3419 myIsComputed = true;
3421 return setErrorCode( ERR_OK );
3424 //=======================================================================
3425 //function : mergePoints
3426 //purpose : Merge XYZ on edges and/or faces.
3427 //=======================================================================
3429 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3431 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3432 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3434 list<list< int > >& groups = idListIt->second;
3435 if ( groups.size() < 2 )
3439 const TNodeSet& nodes = idListIt->first;
3440 double tol2 = 1.e-10;
3441 if ( nodes.size() > 1 ) {
3443 TNodeSet::const_iterator n = nodes.begin();
3444 for ( ; n != nodes.end(); ++n )
3445 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3446 double x, y, z, X, Y, Z;
3447 box.Get( x, y, z, X, Y, Z );
3448 gp_Pnt p( x, y, z ), P( X, Y, Z );
3449 tol2 = 1.e-4 * p.SquareDistance( P );
3452 // to unite groups on link
3453 bool unite = ( uniteGroups && nodes.size() == 2 );
3454 map< double, int > distIndMap;
3455 const SMDS_MeshNode* node = *nodes.begin();
3456 gp_Pnt P( node->X(), node->Y(), node->Z() );
3458 // compare points, replace indices
3460 list< int >::iterator ind1, ind2;
3461 list< list< int > >::iterator grpIt1, grpIt2;
3462 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3464 list< int >& indices1 = *grpIt1;
3466 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3468 list< int >& indices2 = *grpIt2;
3469 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3471 gp_XYZ& p1 = myXYZ[ *ind1 ];
3472 ind2 = indices2.begin();
3473 while ( ind2 != indices2.end() )
3475 gp_XYZ& p2 = myXYZ[ *ind2 ];
3476 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3477 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3479 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3480 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3481 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3482 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3484 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3485 myXYZ[ *ind2 ] = undefinedXYZ();
3486 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3488 ind2 = indices2.erase( ind2 );
3495 if ( unite ) { // sort indices using distIndMap
3496 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3498 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3499 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3500 distIndMap.insert( make_pair( dist, *ind1 ));
3504 if ( unite ) { // put all sorted indices into the first group
3505 list< int >& g = groups.front();
3507 map< double, int >::iterator dist_ind = distIndMap.begin();
3508 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3509 g.push_back( dist_ind->second );
3511 } // loop on myIdsOnBoundary
3514 //=======================================================================
3515 //function : makePolyElements
3516 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3517 //=======================================================================
3519 void SMESH_Pattern::
3520 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3521 const bool toCreatePolygons,
3522 const bool toCreatePolyedrs)
3524 myPolyElemXYZIDs.clear();
3525 myPolyElems.clear();
3526 myPolyElems.reserve( myIdsOnBoundary.size() );
3528 // make a set of refined elements
3529 TIDSortedElemSet avoidSet, elemSet;
3530 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3531 for(; itv!=myElements.end(); itv++) {
3532 const SMDS_MeshElement* el = (*itv);
3533 avoidSet.insert( el );
3535 //avoidSet.insert( myElements.begin(), myElements.end() );
3537 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3539 if ( toCreatePolygons )
3541 int lastFreeId = myXYZ.size();
3543 // loop on links of refined elements
3544 indListIt = myIdsOnBoundary.begin();
3545 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3547 const TNodeSet & linkNodes = indListIt->first;
3548 if ( linkNodes.size() != 2 )
3549 continue; // skip face
3550 const SMDS_MeshNode* n1 = * linkNodes.begin();
3551 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3553 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3554 if ( idGroups.empty() || idGroups.front().empty() )
3557 // find not refined face having n1-n2 link
3561 const SMDS_MeshElement* face =
3562 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3565 avoidSet.insert ( face );
3566 myPolyElems.push_back( face );
3568 // some links of <face> are split;
3569 // make list of xyz for <face>
3570 myPolyElemXYZIDs.push_back(TElemDef());
3571 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3572 // loop on links of a <face>
3573 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3574 int i = 0, nbNodes = face->NbNodes();
3575 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3576 while ( nIt->more() )
3577 nodes[ i++ ] = smdsNode( nIt->next() );
3578 nodes[ i ] = nodes[ 0 ];
3579 for ( i = 0; i < nbNodes; ++i )
3581 // look for point mapped on a link
3582 TNodeSet faceLinkNodes;
3583 faceLinkNodes.insert( nodes[ i ] );
3584 faceLinkNodes.insert( nodes[ i + 1 ] );
3585 if ( faceLinkNodes == linkNodes )
3586 nn_IdList = indListIt;
3588 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3589 // add face point ids
3590 faceNodeIds.push_back( ++lastFreeId );
3591 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3592 if ( nn_IdList != myIdsOnBoundary.end() )
3594 // there are points mapped on a link
3595 list< int >& mappedIds = nn_IdList->second.front();
3596 if ( isReversed( nodes[ i ], mappedIds ))
3597 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3599 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3601 } // loop on links of a <face>
3607 if ( myIs2D && idGroups.size() > 1 ) {
3609 // sew new elements on 2 refined elements sharing n1-n2 link
3611 list< int >& idsOnLink = idGroups.front();
3612 // temporarily add ids of link nodes to idsOnLink
3613 bool rev = isReversed( n1, idsOnLink );
3614 for ( int i = 0; i < 2; ++i )
3617 nodeSet.insert( i ? n2 : n1 );
3618 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3619 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3620 int nodeId = groups.front().front();
3622 if ( rev ) append = !append;
3624 idsOnLink.push_back( nodeId );
3626 idsOnLink.push_front( nodeId );
3628 list< int >::iterator id = idsOnLink.begin();
3629 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3631 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3632 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3633 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3635 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3636 // look for <id> in element definition
3637 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3638 ASSERT ( idDef != pIdList->end() );
3639 // look for 2 neighbour ids of <id> in element definition
3640 for ( int prev = 0; prev < 2; ++prev ) {
3641 TElemDef::iterator idDef2 = idDef;
3643 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3645 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3646 // look for idDef2 on a link starting from id
3647 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3648 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3649 // insert ids located on link between <id> and <id2>
3650 // into the element definition between idDef and idDef2
3652 for ( ; id2 != id; --id2 )
3653 pIdList->insert( idDef, *id2 );
3655 list< int >::iterator id1 = id;
3656 for ( ++id1, ++id2; id1 != id2; ++id1 )
3657 pIdList->insert( idDef2, *id1 );
3663 // remove ids of link nodes
3664 idsOnLink.pop_front();
3665 idsOnLink.pop_back();
3667 } // loop on myIdsOnBoundary
3668 } // if ( toCreatePolygons )
3670 if ( toCreatePolyedrs )
3672 // check volumes adjacent to the refined elements
3673 SMDS_VolumeTool volTool;
3674 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3675 for ( ; refinedElem != myElements.end(); ++refinedElem )
3677 // loop on nodes of refinedElem
3678 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3679 while ( nIt->more() ) {
3680 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3681 // loop on inverse elements of node
3682 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3683 while ( eIt->more() )
3685 const SMDS_MeshElement* elem = eIt->next();
3686 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3687 continue; // skip faces or refined elements
3688 // add polyhedron definition
3689 myPolyhedronQuantities.push_back(vector<int> ());
3690 myPolyElemXYZIDs.push_back(TElemDef());
3691 vector<int>& quantity = myPolyhedronQuantities.back();
3692 TElemDef & elemDef = myPolyElemXYZIDs.back();
3693 // get definitions of new elements on volume faces
3694 bool makePoly = false;
3695 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3697 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3698 volTool.NbFaceNodes( iF ),
3699 theNodes, elemDef, quantity))
3703 myPolyElems.push_back( elem );
3705 myPolyhedronQuantities.pop_back();
3706 myPolyElemXYZIDs.pop_back();
3714 //=======================================================================
3715 //function : getFacesDefinition
3716 //purpose : return faces definition for a volume face defined by theBndNodes
3717 //=======================================================================
3719 bool SMESH_Pattern::
3720 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3721 const int theNbBndNodes,
3722 const vector< const SMDS_MeshNode* >& theNodes,
3723 list< int >& theFaceDefs,
3724 vector<int>& theQuantity)
3726 bool makePoly = false;
3728 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3730 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3732 // make a set of all nodes on a face
3734 if ( !myIs2D ) { // for 2D, merge only edges
3735 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3736 if ( nn_IdList != myIdsOnBoundary.end() ) {
3737 list< int > & faceIds = nn_IdList->second.front();
3738 if ( !faceIds.empty() ) {
3740 ids.insert( faceIds.begin(), faceIds.end() );
3745 // add ids on links and bnd nodes
3746 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3747 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3748 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3750 // add id of iN-th bnd node
3752 nSet.insert( theBndNodes[ iN ] );
3753 nn_IdList = myIdsOnBoundary.find( nSet );
3754 int bndId = ++lastFreeId;
3755 if ( nn_IdList != myIdsOnBoundary.end() ) {
3756 bndId = nn_IdList->second.front().front();
3757 ids.insert( bndId );
3760 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3762 faceDef.push_back( bndId );
3763 // add ids on a link
3765 linkNodes.insert( theBndNodes[ iN ]);
3766 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3767 nn_IdList = myIdsOnBoundary.find( linkNodes );
3768 if ( nn_IdList != myIdsOnBoundary.end() ) {
3769 list< int > & linkIds = nn_IdList->second.front();
3770 if ( !linkIds.empty() )
3773 ids.insert( linkIds.begin(), linkIds.end() );
3774 if ( isReversed( theBndNodes[ iN ], linkIds ))
3775 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3777 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3782 // find faces definition of new volumes
3784 bool defsAdded = false;
3785 if ( !myIs2D ) { // for 2D, merge only edges
3786 SMDS_VolumeTool vol;
3787 set< TElemDef* > checkedVolDefs;
3788 set< int >::iterator id = ids.begin();
3789 for ( ; id != ids.end(); ++id )
3791 // definitions of volumes sharing id
3792 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3793 ASSERT( !defList.empty() );
3794 // loop on volume definitions
3795 list< TElemDef* >::iterator pIdList = defList.begin();
3796 for ( ; pIdList != defList.end(); ++pIdList)
3798 if ( !checkedVolDefs.insert( *pIdList ).second )
3799 continue; // skip already checked volume definition
3800 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3801 // loop on face defs of a volume
3802 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3803 if ( volType == SMDS_VolumeTool::UNKNOWN )
3805 int nbFaces = vol.NbFaces( volType );
3806 for ( int iF = 0; iF < nbFaces; ++iF )
3808 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3809 int iN, nbN = vol.NbFaceNodes( volType, iF );
3810 // check if all nodes of a faces are in <ids>
3812 for ( iN = 0; iN < nbN && all; ++iN ) {
3813 int nodeId = idVec[ nodeInds[ iN ]];
3814 all = ( ids.find( nodeId ) != ids.end() );
3817 // store a face definition
3818 for ( iN = 0; iN < nbN; ++iN ) {
3819 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3821 theQuantity.push_back( nbN );
3829 theQuantity.push_back( faceDef.size() );
3830 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3836 //=======================================================================
3837 //function : clearSubMesh
3839 //=======================================================================
3841 static bool clearSubMesh( SMESH_Mesh* theMesh,
3842 const TopoDS_Shape& theShape)
3844 bool removed = false;
3845 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3847 removed = !aSubMesh->IsEmpty();
3849 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3852 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3853 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3855 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3856 removed = eIt->more();
3857 while ( eIt->more() )
3858 aMeshDS->RemoveElement( eIt->next() );
3859 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3860 removed = removed || nIt->more();
3861 while ( nIt->more() )
3862 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3868 //=======================================================================
3869 //function : clearMesh
3870 //purpose : clear mesh elements existing on myShape in theMesh
3871 //=======================================================================
3873 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3876 if ( !myShape.IsNull() )
3878 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3879 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3880 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3882 clearSubMesh( theMesh, it.Value() );
3888 //=======================================================================
3889 //function : MakeMesh
3890 //purpose : Create nodes and elements in <theMesh> using nodes
3891 // coordinates computed by either of Apply...() methods
3892 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3893 // it does not care of nodes and elements already existing on
3894 // sub-shapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3895 //=======================================================================
3897 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3898 const bool toCreatePolygons,
3899 const bool toCreatePolyedrs)
3901 MESSAGE(" ::MakeMesh() " );
3902 if ( !myIsComputed )
3903 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3905 mergePoints( toCreatePolygons );
3907 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3909 // clear elements and nodes existing on myShape
3912 bool onMeshElements = ( !myElements.empty() );
3914 // Create missing nodes
3916 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3917 if ( onMeshElements )
3919 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3920 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3921 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3922 nodesVector[ i_node->first ] = i_node->second;
3924 for ( int i = 0; i < myXYZ.size(); ++i ) {
3925 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3926 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3933 nodesVector.resize( myPoints.size(), 0 );
3935 // to find point index
3936 map< TPoint*, int > pointIndex;
3937 for ( int i = 0; i < myPoints.size(); i++ )
3938 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3940 // loop on sub-shapes of myShape: create nodes
3941 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3942 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3945 //SMESHDS_SubMesh * subMeshDS = 0;
3946 if ( !myShapeIDMap.IsEmpty() ) {
3947 S = myShapeIDMap( idPointIt->first );
3948 //subMeshDS = aMeshDS->MeshElements( S );
3950 list< TPoint* > & points = idPointIt->second;
3951 list< TPoint* >::iterator pIt = points.begin();
3952 for ( ; pIt != points.end(); pIt++ )
3954 TPoint* point = *pIt;
3955 int pIndex = pointIndex[ point ];
3956 if ( nodesVector [ pIndex ] )
3958 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3961 nodesVector [ pIndex ] = node;
3963 if ( !S.IsNull() /*subMeshDS*/ ) {
3964 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3965 switch ( S.ShapeType() ) {
3966 case TopAbs_VERTEX: {
3967 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3970 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3973 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3974 point->myUV.X(), point->myUV.Y() ); break;
3977 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3986 if ( onMeshElements )
3988 // prepare data to create poly elements
3989 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3992 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3993 // sew old and new elements
3994 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3998 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4001 aMeshDS->compactMesh();
4003 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4004 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4005 // for ( ; i_sm != sm.end(); i_sm++ )
4007 // cout << " SM " << i_sm->first << " ";
4008 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4009 // //SMDS_ElemIteratorPtr GetElements();
4010 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4011 // while ( nit->more() )
4012 // cout << nit->next()->GetID() << " ";
4015 return setErrorCode( ERR_OK );
4018 //=======================================================================
4019 //function : createElements
4020 //purpose : add elements to the mesh
4021 //=======================================================================
4023 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4024 const vector<const SMDS_MeshNode* >& theNodesVector,
4025 const list< TElemDef > & theElemNodeIDs,
4026 const vector<const SMDS_MeshElement*>& theElements)
4028 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4029 SMESH_MeshEditor editor( theMesh );
4031 bool onMeshElements = !theElements.empty();
4033 // shapes and groups theElements are on
4034 vector< int > shapeIDs;
4035 vector< list< SMESHDS_Group* > > groups;
4036 set< const SMDS_MeshNode* > shellNodes;
4037 if ( onMeshElements )
4039 shapeIDs.resize( theElements.size() );
4040 groups.resize( theElements.size() );
4041 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4042 set<SMESHDS_GroupBase*>::const_iterator grIt;
4043 for ( int i = 0; i < theElements.size(); i++ )
4045 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4046 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4047 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4048 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4049 groups[ i ].push_back( group );
4052 // get all nodes bound to shells because their SpacePosition is not set
4053 // by SMESHDS_Mesh::SetNodeInVolume()
4054 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4055 if ( !aMainShape.IsNull() ) {
4056 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4057 for ( ; shellExp.More(); shellExp.Next() )
4059 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4061 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4062 while ( nIt->more() )
4063 shellNodes.insert( nIt->next() );
4068 // nb new elements per a refined element
4069 int nbNewElemsPerOld = 1;
4070 if ( onMeshElements )
4071 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4075 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4076 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4077 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4079 const TElemDef & elemNodeInd = *enIt;
4081 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4082 TElemDef::const_iterator id = elemNodeInd.begin();
4084 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4085 if ( *id < theNodesVector.size() )
4086 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4088 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4090 // dim of refined elem
4091 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4092 if ( onMeshElements ) {
4093 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4096 const SMDS_MeshElement* elem = 0;
4098 switch ( nbNodes ) {
4100 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4102 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4104 if ( !onMeshElements ) {// create a quadratic face
4105 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4106 nodes[4], nodes[5] ); break;
4107 } // else do not break but create a polygon
4109 if ( !onMeshElements ) {// create a quadratic face
4110 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4111 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4112 } // else do not break but create a polygon
4114 elem = aMeshDS->AddPolygonalFace( nodes );
4118 switch ( nbNodes ) {
4120 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4122 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4125 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4126 nodes[4], nodes[5] ); break;
4128 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4129 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4131 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4134 // set element on a shape
4135 if ( elem && onMeshElements ) // applied to mesh elements
4137 int shapeID = shapeIDs[ elemIndex ];
4138 if ( shapeID > 0 ) {
4139 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4140 // set nodes on a shape
4141 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4142 if ( S.ShapeType() == TopAbs_SOLID ) {
4143 TopoDS_Iterator shellIt( S );
4144 if ( shellIt.More() )
4145 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4147 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4148 while ( noIt->more() ) {
4149 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4150 if (!node->getshapeId() &&
4151 shellNodes.find( node ) == shellNodes.end() ) {
4152 if ( S.ShapeType() == TopAbs_FACE )
4153 aMeshDS->SetNodeOnFace( node, shapeID,
4154 Precision::Infinite(),// <- it's a sign that UV is not set
4155 Precision::Infinite());
4157 aMeshDS->SetNodeInVolume( node, shapeID );
4158 shellNodes.insert( node );
4163 // add elem in groups
4164 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4165 for ( ; g != groups[ elemIndex ].end(); ++g )
4166 (*g)->SMDSGroup().Add( elem );
4168 if ( elem && !myShape.IsNull() ) // applied to shape
4169 aMeshDS->SetMeshElementOnShape( elem, myShape );
4172 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4173 // so that operations with hypotheses will erase the mesh being built
4175 SMESH_subMesh * subMesh;
4176 if ( !myShape.IsNull() ) {
4177 subMesh = theMesh->GetSubMesh( myShape );
4179 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4181 if ( onMeshElements ) {
4182 list< int > elemIDs;
4183 for ( int i = 0; i < theElements.size(); i++ )
4185 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4187 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4189 elemIDs.push_back( theElements[ i ]->GetID() );
4191 // remove refined elements
4192 editor.Remove( elemIDs, false );
4196 //=======================================================================
4197 //function : isReversed
4198 //purpose : check xyz ids order in theIdsList taking into account
4199 // theFirstNode on a link
4200 //=======================================================================
4202 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4203 const list< int >& theIdsList) const
4205 if ( theIdsList.size() < 2 )
4208 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4210 list<int>::const_iterator id = theIdsList.begin();
4211 for ( int i = 0; i < 2; ++i, ++id ) {
4212 if ( *id < myXYZ.size() )
4213 P[ i ] = myXYZ[ *id ];
4215 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4216 i_n = myXYZIdToNodeMap.find( *id );
4217 ASSERT( i_n != myXYZIdToNodeMap.end() );
4218 const SMDS_MeshNode* n = i_n->second;
4219 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4222 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4226 //=======================================================================
4227 //function : arrangeBoundaries
4228 //purpose : if there are several wires, arrange boundaryPoints so that
4229 // the outer wire goes first and fix inner wires orientation
4230 // update myKeyPointIDs to correspond to the order of key-points
4231 // in boundaries; sort internal boundaries by the nb of key-points
4232 //=======================================================================
4234 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4236 typedef list< list< TPoint* > >::iterator TListOfListIt;
4237 TListOfListIt bndIt;
4238 list< TPoint* >::iterator pIt;
4240 int nbBoundaries = boundaryList.size();
4241 if ( nbBoundaries > 1 )
4243 // sort boundaries by nb of key-points
4244 if ( nbBoundaries > 2 )
4246 // move boundaries in tmp list
4247 list< list< TPoint* > > tmpList;
4248 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4249 // make a map nb-key-points to boundary-position-in-tmpList,
4250 // boundary-positions get ordered in it
4251 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4252 TNbKpBndPosMap nbKpBndPosMap;
4253 bndIt = tmpList.begin();
4254 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4255 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4256 int nb = *nbKpIt * nbBoundaries;
4257 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4259 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4261 // move boundaries back to boundaryList
4262 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4263 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4264 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4265 TListOfListIt bndPos1 = bndPos2++;
4266 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4270 // Look for the outer boundary: the one with the point with the least X
4271 double leastX = DBL_MAX;
4272 TListOfListIt outerBndPos;
4273 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4275 list< TPoint* >& boundary = (*bndIt);
4276 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4278 TPoint* point = *pIt;
4279 if ( point->myInitXYZ.X() < leastX ) {
4280 leastX = point->myInitXYZ.X();
4281 outerBndPos = bndIt;
4286 if ( outerBndPos != boundaryList.begin() )
4287 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4289 } // if nbBoundaries > 1
4291 // Check boundaries orientation and re-fill myKeyPointIDs
4293 set< TPoint* > keyPointSet;
4294 list< int >::iterator kpIt = myKeyPointIDs.begin();
4295 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4296 keyPointSet.insert( & myPoints[ *kpIt ]);
4297 myKeyPointIDs.clear();
4299 // update myNbKeyPntInBoundary also
4300 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4302 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4304 // find the point with the least X
4305 double leastX = DBL_MAX;
4306 list< TPoint* >::iterator xpIt;
4307 list< TPoint* >& boundary = (*bndIt);
4308 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4310 TPoint* point = *pIt;
4311 if ( point->myInitXYZ.X() < leastX ) {
4312 leastX = point->myInitXYZ.X();
4316 // find points next to the point with the least X
4317 TPoint* p = *xpIt, *pPrev, *pNext;
4318 if ( p == boundary.front() )
4319 pPrev = *(++boundary.rbegin());
4325 if ( p == boundary.back() )
4326 pNext = *(++boundary.begin());
4331 // vectors of boundary direction near <p>
4332 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4333 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4334 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4335 double yPrev = v1.Y() / sqrt( sqMag1 );
4336 double yNext = v2.Y() / sqrt( sqMag2 );
4337 double sumY = yPrev + yNext;
4339 if ( bndIt == boundaryList.begin() ) // outer boundary
4347 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4348 (*nbKpIt) = 0; // count nb of key-points again
4349 pIt = boundary.begin();
4350 for ( ; pIt != boundary.end(); pIt++)
4352 TPoint* point = *pIt;
4353 if ( keyPointSet.find( point ) == keyPointSet.end() )
4355 // find an index of a keypoint
4357 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4358 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4359 if ( &(*pVecIt) == point )
4361 myKeyPointIDs.push_back( index );
4364 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4367 } // loop on a list of boundaries
4369 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4372 //=======================================================================
4373 //function : findBoundaryPoints
4374 //purpose : if loaded from file, find points to map on edges and faces and
4375 // compute their parameters
4376 //=======================================================================
4378 bool SMESH_Pattern::findBoundaryPoints()
4380 if ( myIsBoundaryPointsFound ) return true;
4382 MESSAGE(" findBoundaryPoints() ");
4384 myNbKeyPntInBoundary.clear();
4388 set< TPoint* > pointsInElems;
4390 // Find free links of elements:
4391 // put links of all elements in a set and remove links encountered twice
4393 typedef pair< TPoint*, TPoint*> TLink;
4394 set< TLink > linkSet;
4395 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4396 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4398 TElemDef & elemPoints = *epIt;
4399 TElemDef::iterator pIt = elemPoints.begin();
4400 int prevP = elemPoints.back();
4401 for ( ; pIt != elemPoints.end(); pIt++ ) {
4402 TPoint* p1 = & myPoints[ prevP ];
4403 TPoint* p2 = & myPoints[ *pIt ];
4404 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4405 ASSERT( link.first != link.second );
4406 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4407 if ( !itUniq.second )
4408 linkSet.erase( itUniq.first );
4411 pointsInElems.insert( p1 );
4414 // Now linkSet contains only free links,
4415 // find the points order that they have in boundaries
4417 // 1. make a map of key-points
4418 set< TPoint* > keyPointSet;
4419 list< int >::iterator kpIt = myKeyPointIDs.begin();
4420 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4421 keyPointSet.insert( & myPoints[ *kpIt ]);
4423 // 2. chain up boundary points
4424 list< list< TPoint* > > boundaryList;
4425 boundaryList.push_back( list< TPoint* >() );
4426 list< TPoint* > * boundary = & boundaryList.back();
4428 TPoint *point1, *point2, *keypoint1;
4429 kpIt = myKeyPointIDs.begin();
4430 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4431 // loop on free links: look for the next point
4433 set< TLink >::iterator lIt = linkSet.begin();
4434 while ( lIt != linkSet.end() )
4436 if ( (*lIt).first == point1 )
4437 point2 = (*lIt).second;
4438 else if ( (*lIt).second == point1 )
4439 point2 = (*lIt).first;
4444 linkSet.erase( lIt );
4445 lIt = linkSet.begin();
4447 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4449 boundary->push_back( point2 );
4451 else // a key-point found
4453 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4455 if ( point2 != keypoint1 ) // its not the boundary end
4457 boundary->push_back( point2 );
4459 else // the boundary end reached
4461 boundary->push_front( keypoint1 );
4462 boundary->push_back( keypoint1 );
4463 myNbKeyPntInBoundary.push_back( iKeyPoint );
4464 if ( keyPointSet.empty() )
4465 break; // all boundaries containing key-points are found
4467 // prepare to search for the next boundary
4468 boundaryList.push_back( list< TPoint* >() );
4469 boundary = & boundaryList.back();
4470 point2 = keypoint1 = (*keyPointSet.begin());
4474 } // loop on the free links set
4476 if ( boundary->empty() ) {
4477 MESSAGE(" a separate key-point");
4478 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4481 // if there are several wires, arrange boundaryPoints so that
4482 // the outer wire goes first and fix inner wires orientation;
4483 // sort myKeyPointIDs to correspond to the order of key-points
4485 arrangeBoundaries( boundaryList );
4487 // Find correspondence shape ID - points,
4488 // compute points parameter on edge
4490 keyPointSet.clear();
4491 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4492 keyPointSet.insert( & myPoints[ *kpIt ]);
4494 set< TPoint* > edgePointSet; // to find in-face points
4495 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4496 int edgeID = myKeyPointIDs.size() + 1;
4498 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4499 for ( ; bndIt != boundaryList.end(); bndIt++ )
4501 boundary = & (*bndIt);
4502 double edgeLength = 0;
4503 list< TPoint* >::iterator pIt = boundary->begin();
4504 getShapePoints( edgeID ).push_back( *pIt );
4505 getShapePoints( vertexID++ ).push_back( *pIt );
4506 for ( pIt++; pIt != boundary->end(); pIt++)
4508 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4509 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4510 TPoint* point = *pIt;
4511 edgePointSet.insert( point );
4512 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4514 edgePoints.push_back( point );
4515 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4516 point->myInitU = edgeLength;
4520 // treat points on the edge which ends up: compute U [0,1]
4521 edgePoints.push_back( point );
4522 if ( edgePoints.size() > 2 ) {
4523 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4524 list< TPoint* >::iterator epIt = edgePoints.begin();
4525 for ( ; epIt != edgePoints.end(); epIt++ )
4526 (*epIt)->myInitU /= edgeLength;
4528 // begin the next edge treatment
4531 if ( point != boundary->front() ) { // not the first key-point again
4532 getShapePoints( edgeID ).push_back( point );
4533 getShapePoints( vertexID++ ).push_back( point );
4539 // find in-face points
4540 list< TPoint* > & facePoints = getShapePoints( edgeID );
4541 vector< TPoint >::iterator pVecIt = myPoints.begin();
4542 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4543 TPoint* point = &(*pVecIt);
4544 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4545 pointsInElems.find( point ) != pointsInElems.end())
4546 facePoints.push_back( point );
4553 // bind points to shapes according to point parameters
4554 vector< TPoint >::iterator pVecIt = myPoints.begin();
4555 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4556 TPoint* point = &(*pVecIt);
4557 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4558 getShapePoints( shapeID ).push_back( point );
4559 // detect key-points
4560 if ( SMESH_Block::IsVertexID( shapeID ))
4561 myKeyPointIDs.push_back( i );
4565 myIsBoundaryPointsFound = true;
4566 return myIsBoundaryPointsFound;
4569 //=======================================================================
4571 //purpose : clear fields
4572 //=======================================================================
4574 void SMESH_Pattern::Clear()
4576 myIsComputed = myIsBoundaryPointsFound = false;
4579 myKeyPointIDs.clear();
4580 myElemPointIDs.clear();
4581 myShapeIDToPointsMap.clear();
4582 myShapeIDMap.Clear();
4584 myNbKeyPntInBoundary.clear();
4587 myElemXYZIDs.clear();
4588 myXYZIdToNodeMap.clear();
4590 myOrderedNodes.clear();
4591 myPolyElems.clear();
4592 myPolyElemXYZIDs.clear();
4593 myPolyhedronQuantities.clear();
4594 myIdsOnBoundary.clear();
4595 myReverseConnectivity.clear();
4598 //================================================================================
4600 * \brief set ErrorCode and return true if it is Ok
4602 //================================================================================
4604 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4606 myErrorCode = theErrorCode;
4607 return myErrorCode == ERR_OK;
4610 //=======================================================================
4611 //function : setShapeToMesh
4612 //purpose : set a shape to be meshed. Return True if meshing is possible
4613 //=======================================================================
4615 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4617 if ( !IsLoaded() ) {
4618 MESSAGE( "Pattern not loaded" );
4619 return setErrorCode( ERR_APPL_NOT_LOADED );
4622 TopAbs_ShapeEnum aType = theShape.ShapeType();
4623 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4625 MESSAGE( "Pattern dimention mismatch" );
4626 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4629 // check if a face is closed
4630 int nbNodeOnSeamEdge = 0;
4632 TopTools_MapOfShape seamVertices;
4633 TopoDS_Face face = TopoDS::Face( theShape );
4634 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4635 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4636 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4637 if ( BRep_Tool::IsClosed(ee, face) ) {
4638 // seam edge and vertices encounter twice in theFace
4639 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4640 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4645 // check nb of vertices
4646 TopTools_IndexedMapOfShape vMap;
4647 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4648 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4649 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4650 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4653 myElements.clear(); // not refine elements
4654 myElemXYZIDs.clear();
4656 myShapeIDMap.Clear();
4661 //=======================================================================
4662 //function : GetMappedPoints
4663 //purpose : Return nodes coordinates computed by Apply() method
4664 //=======================================================================
4666 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4669 if ( !myIsComputed )
4672 if ( myElements.empty() ) { // applied to shape
4673 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4674 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4675 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4677 else { // applied to mesh elements
4678 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4679 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4680 for ( ; xyz != myXYZ.end(); ++xyz )
4681 if ( !isDefined( *xyz ))
4682 thePoints.push_back( definedXYZ );
4684 thePoints.push_back( & (*xyz) );
4686 return !thePoints.empty();
4690 //=======================================================================
4691 //function : GetPoints
4692 //purpose : Return nodes coordinates of the pattern
4693 //=======================================================================
4695 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4702 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4703 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4704 thePoints.push_back( & (*pVecIt).myInitXYZ );
4706 return ( thePoints.size() > 0 );
4709 //=======================================================================
4710 //function : getShapePoints
4711 //purpose : return list of points located on theShape
4712 //=======================================================================
4714 list< SMESH_Pattern::TPoint* > &
4715 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4718 if ( !myShapeIDMap.Contains( theShape ))
4719 aShapeID = myShapeIDMap.Add( theShape );
4721 aShapeID = myShapeIDMap.FindIndex( theShape );
4723 return myShapeIDToPointsMap[ aShapeID ];
4726 //=======================================================================
4727 //function : getShapePoints
4728 //purpose : return list of points located on the shape
4729 //=======================================================================
4731 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4733 return myShapeIDToPointsMap[ theShapeID ];
4736 //=======================================================================
4737 //function : DumpPoints
4739 //=======================================================================
4741 void SMESH_Pattern::DumpPoints() const
4744 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4745 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4746 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4750 //=======================================================================
4751 //function : TPoint()
4753 //=======================================================================
4755 SMESH_Pattern::TPoint::TPoint()
4758 myInitXYZ.SetCoord(0,0,0);
4759 myInitUV.SetCoord(0.,0.);
4761 myXYZ.SetCoord(0,0,0);
4762 myUV.SetCoord(0.,0.);
4767 //=======================================================================
4768 //function : operator <<
4770 //=======================================================================
4772 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4774 gp_XYZ xyz = p.myInitXYZ;
4775 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4776 gp_XY xy = p.myInitUV;
4777 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4778 double u = p.myInitU;
4779 OS << " u( " << u << " )) " << &p << endl;
4780 xyz = p.myXYZ.XYZ();
4781 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4783 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4785 OS << " u( " << u << " ))" << endl;