1 // Copyright (C) 2007-2008 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
22 // File : SMESH_Pattern.hxx
23 // Created : Mon Aug 2 10:30:00 2004
24 // Author : Edward AGAPOV (eap)
26 #include "SMESH_Pattern.hxx"
28 #include <BRepAdaptor_Curve.hxx>
29 #include <BRepTools.hxx>
30 #include <BRepTools_WireExplorer.hxx>
31 #include <BRep_Tool.hxx>
32 #include <Bnd_Box.hxx>
33 #include <Bnd_Box2d.hxx>
35 #include <Extrema_ExtPC.hxx>
36 #include <Extrema_GenExtPS.hxx>
37 #include <Extrema_POnSurf.hxx>
38 #include <Geom2d_Curve.hxx>
39 #include <GeomAdaptor_Surface.hxx>
40 #include <Geom_Curve.hxx>
41 #include <Geom_Surface.hxx>
42 #include <TopAbs_ShapeEnum.hxx>
44 #include <TopExp_Explorer.hxx>
45 #include <TopLoc_Location.hxx>
46 #include <TopTools_ListIteratorOfListOfShape.hxx>
48 #include <TopoDS_Edge.hxx>
49 #include <TopoDS_Face.hxx>
50 #include <TopoDS_Iterator.hxx>
51 #include <TopoDS_Shell.hxx>
52 #include <TopoDS_Vertex.hxx>
53 #include <TopoDS_Wire.hxx>
55 #include <gp_Lin2d.hxx>
56 #include <gp_Pnt2d.hxx>
57 #include <gp_Trsf.hxx>
61 #include "SMDS_EdgePosition.hxx"
62 #include "SMDS_FacePosition.hxx"
63 #include "SMDS_MeshElement.hxx"
64 #include "SMDS_MeshFace.hxx"
65 #include "SMDS_MeshNode.hxx"
66 #include "SMDS_VolumeTool.hxx"
67 #include "SMESHDS_Group.hxx"
68 #include "SMESHDS_Mesh.hxx"
69 #include "SMESHDS_SubMesh.hxx"
70 #include "SMESH_Block.hxx"
71 #include "SMESH_Mesh.hxx"
72 #include "SMESH_MesherHelper.hxx"
73 #include "SMESH_subMesh.hxx"
75 #include "utilities.h"
79 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
81 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
83 //=======================================================================
84 //function : SMESH_Pattern
86 //=======================================================================
88 SMESH_Pattern::SMESH_Pattern ()
91 //=======================================================================
94 //=======================================================================
96 static inline int getInt( const char * theSring )
98 if ( *theSring < '0' || *theSring > '9' )
102 int val = strtol( theSring, &ptr, 10 );
103 if ( ptr == theSring ||
104 // there must not be neither '.' nor ',' nor 'E' ...
105 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
111 //=======================================================================
112 //function : getDouble
114 //=======================================================================
116 static inline double getDouble( const char * theSring )
119 return strtod( theSring, &ptr );
122 //=======================================================================
123 //function : readLine
124 //purpose : Put token starting positions in theFields until '\n' or '\0'
125 // Return the number of the found tokens
126 //=======================================================================
128 static int readLine (list <const char*> & theFields,
129 const char* & theLineBeg,
130 const bool theClearFields )
132 if ( theClearFields )
137 /* switch ( symbol ) { */
138 /* case white-space: */
139 /* look for a non-space symbol; */
140 /* case string-end: */
143 /* case comment beginning: */
144 /* skip all till a line-end; */
146 /* put its position in theFields, skip till a white-space;*/
152 bool stopReading = false;
155 bool isNumber = false;
156 switch ( *theLineBeg )
158 case ' ': // white space
163 case '\n': // a line ends
164 stopReading = ( nbRead > 0 );
169 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
173 case '\0': // file ends
176 case '-': // real number
181 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
183 theFields.push_back( theLineBeg );
186 while (*theLineBeg != ' ' &&
187 *theLineBeg != '\n' &&
188 *theLineBeg != '\0');
192 return 0; // incorrect file format
198 } while ( !stopReading );
203 //=======================================================================
205 //purpose : Load a pattern from <theFile>
206 //=======================================================================
208 bool SMESH_Pattern::Load (const char* theFileContents)
210 MESSAGE("Load( file ) ");
214 // ! This is a comment
215 // NB_POINTS ! 1 integer - the number of points in the pattern.
216 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
217 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
219 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
220 // ! elements description goes after all
221 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
226 const char* lineBeg = theFileContents;
227 list <const char*> fields;
228 const bool clearFields = true;
230 // NB_POINTS ! 1 integer - the number of points in the pattern.
232 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
233 MESSAGE("Error reading NB_POINTS");
234 return setErrorCode( ERR_READ_NB_POINTS );
236 int nbPoints = getInt( fields.front() );
238 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
240 // read the first point coordinates to define pattern dimention
241 int dim = readLine( fields, lineBeg, clearFields );
247 MESSAGE("Error reading points: wrong nb of coordinates");
248 return setErrorCode( ERR_READ_POINT_COORDS );
250 if ( nbPoints <= dim ) {
251 MESSAGE(" Too few points ");
252 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
255 // read the rest points
257 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
258 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
259 MESSAGE("Error reading points : wrong nb of coordinates ");
260 return setErrorCode( ERR_READ_POINT_COORDS );
262 // store point coordinates
263 myPoints.resize( nbPoints );
264 list <const char*>::iterator fIt = fields.begin();
265 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
267 TPoint & p = myPoints[ iPoint ];
268 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
270 double coord = getDouble( *fIt );
271 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
272 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
274 return setErrorCode( ERR_READ_3D_COORD );
276 p.myInitXYZ.SetCoord( iCoord, coord );
278 p.myInitUV.SetCoord( iCoord, coord );
282 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
285 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
286 MESSAGE("Error: missing key-points");
288 return setErrorCode( ERR_READ_NO_KEYPOINT );
291 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
293 int pointIndex = getInt( *fIt );
294 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
295 MESSAGE("Error: invalid point index " << pointIndex );
297 return setErrorCode( ERR_READ_BAD_INDEX );
299 if ( idSet.insert( pointIndex ).second ) // unique?
300 myKeyPointIDs.push_back( pointIndex );
304 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
306 while ( readLine( fields, lineBeg, clearFields ))
308 myElemPointIDs.push_back( TElemDef() );
309 TElemDef& elemPoints = myElemPointIDs.back();
310 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
312 int pointIndex = getInt( *fIt );
313 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
314 MESSAGE("Error: invalid point index " << pointIndex );
316 return setErrorCode( ERR_READ_BAD_INDEX );
318 elemPoints.push_back( pointIndex );
320 // check the nb of nodes in element
322 switch ( elemPoints.size() ) {
323 case 3: if ( !myIs2D ) Ok = false; break;
327 case 8: if ( myIs2D ) Ok = false; break;
331 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
333 return setErrorCode( ERR_READ_ELEM_POINTS );
336 if ( myElemPointIDs.empty() ) {
337 MESSAGE("Error: no elements");
339 return setErrorCode( ERR_READ_NO_ELEMS );
342 findBoundaryPoints(); // sort key-points
344 return setErrorCode( ERR_OK );
347 //=======================================================================
349 //purpose : Save the loaded pattern into the file <theFileName>
350 //=======================================================================
352 bool SMESH_Pattern::Save (ostream& theFile)
354 MESSAGE(" ::Save(file) " );
356 MESSAGE(" Pattern not loaded ");
357 return setErrorCode( ERR_SAVE_NOT_LOADED );
360 theFile << "!!! SALOME Mesh Pattern file" << endl;
361 theFile << "!!!" << endl;
362 theFile << "!!! Nb of points:" << endl;
363 theFile << myPoints.size() << endl;
367 // theFile.width( 8 );
368 // theFile.setf(ios::fixed);// use 123.45 floating notation
369 // theFile.setf(ios::right);
370 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
371 // theFile.setf(ios::showpoint); // do not show trailing zeros
372 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
373 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
374 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
375 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
376 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
377 theFile << " !- " << i << endl; // point id to ease reading by a human being
381 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
382 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
383 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
384 theFile << " " << *kpIt;
385 if ( !myKeyPointIDs.empty() )
389 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
390 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
391 for ( ; epIt != myElemPointIDs.end(); epIt++ )
393 const TElemDef & elemPoints = *epIt;
394 TElemDef::const_iterator iIt = elemPoints.begin();
395 for ( ; iIt != elemPoints.end(); iIt++ )
396 theFile << " " << *iIt;
402 return setErrorCode( ERR_OK );
405 //=======================================================================
406 //function : sortBySize
407 //purpose : sort theListOfList by size
408 //=======================================================================
410 template<typename T> struct TSizeCmp {
411 bool operator ()( const list < T > & l1, const list < T > & l2 )
412 const { return l1.size() < l2.size(); }
415 template<typename T> void sortBySize( list< list < T > > & theListOfList )
417 if ( theListOfList.size() > 2 ) {
418 TSizeCmp< T > SizeCmp;
419 theListOfList.sort( SizeCmp );
423 //=======================================================================
426 //=======================================================================
428 static gp_XY project (const SMDS_MeshNode* theNode,
429 Extrema_GenExtPS & theProjectorPS)
431 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
432 theProjectorPS.Perform( P );
433 if ( !theProjectorPS.IsDone() ) {
434 MESSAGE( "SMESH_Pattern: point projection FAILED");
437 double u, v, minVal = DBL_MAX;
438 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
439 if ( theProjectorPS.Value( i ) < minVal ) {
440 minVal = theProjectorPS.Value( i );
441 theProjectorPS.Point( i ).Parameter( u, v );
443 return gp_XY( u, v );
446 //=======================================================================
447 //function : areNodesBound
448 //purpose : true if all nodes of faces are bound to shapes
449 //=======================================================================
451 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
453 while ( faceItr->more() )
455 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
456 while ( nIt->more() )
458 const SMDS_MeshNode* node = smdsNode( nIt->next() );
459 SMDS_PositionPtr pos = node->GetPosition();
460 if ( !pos || !pos->GetShapeId() ) {
468 //=======================================================================
469 //function : isMeshBoundToShape
470 //purpose : return true if all 2d elements are bound to shape
471 // if aFaceSubmesh != NULL, then check faces bound to it
472 // else check all faces in aMeshDS
473 //=======================================================================
475 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
476 SMESHDS_SubMesh * aFaceSubmesh,
477 const bool isMainShape)
480 // check that all faces are bound to aFaceSubmesh
481 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
485 // check face nodes binding
486 if ( aFaceSubmesh ) {
487 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
488 return areNodesBound( fIt );
490 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
491 return areNodesBound( fIt );
494 //=======================================================================
496 //purpose : Create a pattern from the mesh built on <theFace>.
497 // <theProject>==true makes override nodes positions
498 // on <theFace> computed by mesher
499 //=======================================================================
501 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
502 const TopoDS_Face& theFace,
505 MESSAGE(" ::Load(face) " );
509 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
510 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
511 SMESH_MesherHelper helper( *theMesh );
512 helper.SetSubShape( theFace );
514 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
515 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
516 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
518 MESSAGE( "No elements bound to the face");
519 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
522 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
524 // check if face is closed
525 bool isClosed = helper.HasSeam();
527 list<TopoDS_Edge> eList;
528 list<TopoDS_Edge>::iterator elIt;
529 SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
531 // check that requested or needed projection is possible
532 bool isMainShape = theMesh->IsMainShape( face );
533 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
534 bool canProject = ( nbElems ? true : isMainShape );
536 canProject = false; // so far
538 if ( ( theProject || needProject ) && !canProject )
539 return setErrorCode( ERR_LOADF_CANT_PROJECT );
541 Extrema_GenExtPS projector;
542 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
543 if ( theProject || needProject )
544 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
547 TNodePointIDMap nodePointIDMap;
548 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
552 MESSAGE("Project the submesh");
553 // ---------------------------------------------------------------
554 // The case where the submesh is projected to theFace
555 // ---------------------------------------------------------------
558 list< const SMDS_MeshElement* > faces;
560 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
561 while ( fIt->more() ) {
562 const SMDS_MeshElement* f = fIt->next();
563 if ( f && f->GetType() == SMDSAbs_Face )
564 faces.push_back( f );
568 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
569 while ( fIt->more() )
570 faces.push_back( fIt->next() );
573 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
574 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
575 for ( ; fIt != faces.end(); ++fIt )
577 myElemPointIDs.push_back( TElemDef() );
578 TElemDef& elemPoints = myElemPointIDs.back();
579 SMDS_ElemIteratorPtr nIt = (*fIt)->nodesIterator();
580 while ( nIt->more() )
582 const SMDS_MeshElement* node = nIt->next();
583 TNodePointIDMap::iterator nIdIt = nodePointIDMap.find( node );
584 if ( nIdIt == nodePointIDMap.end() )
586 elemPoints.push_back( iPoint );
587 nodePointIDMap.insert( make_pair( node, iPoint++ ));
590 elemPoints.push_back( (*nIdIt).second );
593 myPoints.resize( iPoint );
595 // project all nodes of 2d elements to theFace
596 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
597 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
599 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
600 TPoint * p = & myPoints[ (*nIdIt).second ];
601 p->myInitUV = project( node, projector );
602 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
604 // find key-points: the points most close to UV of vertices
605 TopExp_Explorer vExp( face, TopAbs_VERTEX );
606 set<int> foundIndices;
607 for ( ; vExp.More(); vExp.Next() ) {
608 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
609 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
610 double minDist = DBL_MAX;
612 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
613 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
614 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
615 if ( dist < minDist ) {
620 if ( foundIndices.insert( index ).second ) // unique?
621 myKeyPointIDs.push_back( index );
623 myIsBoundaryPointsFound = false;
628 // ---------------------------------------------------------------------
629 // The case where a pattern is being made from the mesh built by mesher
630 // ---------------------------------------------------------------------
632 // Load shapes in the consequent order and count nb of points
635 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
636 int nbV = myShapeIDMap.Extent();
637 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
638 bool added = ( nbV < myShapeIDMap.Extent() );
639 if ( !added ) { // vertex encountered twice
640 // a seam vertex have two corresponding key points
641 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
644 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
645 nbNodes += eSubMesh->NbNodes() + 1;
648 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
649 myShapeIDMap.Add( *elIt );
651 myShapeIDMap.Add( face );
653 myPoints.resize( nbNodes );
655 // Load U of points on edges
657 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
659 TopoDS_Edge & edge = *elIt;
660 list< TPoint* > & ePoints = getShapePoints( edge );
662 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
663 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
665 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
666 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
667 // to make adjacent edges share key-point, we make v2 FORWARD too
668 // (as we have different points for same shape with different orienation)
671 // on closed face we must have REVERSED some of seam vertices
673 if ( helper.IsSeamShape( edge ) ) {
674 if ( helper.IsRealSeam( edge ) && !isForward ) {
675 // reverse on reversed SEAM edge
680 else { // on CLOSED edge (i.e. having one vertex with different orienations)
681 for ( int is2 = 0; is2 < 2; ++is2 ) {
682 TopoDS_Shape & v = is2 ? v2 : v1;
683 if ( helper.IsRealSeam( v ) ) {
684 // reverse or not depending on orientation of adjacent seam
686 list<TopoDS_Edge>::iterator eIt2 = elIt;
688 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
690 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
691 if ( seam.Orientation() == TopAbs_REVERSED )
698 // the forward key-point
699 list< TPoint* > * vPoint = & getShapePoints( v1 );
700 if ( vPoint->empty() )
702 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
703 if ( vSubMesh && vSubMesh->NbNodes() ) {
704 myKeyPointIDs.push_back( iPoint );
705 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
706 const SMDS_MeshNode* node = nIt->next();
707 if ( v1.Orientation() == TopAbs_REVERSED )
708 closeNodePointIDMap.insert( make_pair( node, iPoint ));
710 nodePointIDMap.insert( make_pair( node, iPoint ));
712 TPoint* keyPoint = &myPoints[ iPoint++ ];
713 vPoint->push_back( keyPoint );
715 keyPoint->myInitUV = project( node, projector );
717 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
718 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
721 if ( !vPoint->empty() )
722 ePoints.push_back( vPoint->front() );
725 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
726 if ( eSubMesh && eSubMesh->NbNodes() )
728 // loop on nodes of an edge: sort them by param on edge
729 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
730 TParamNodeMap paramNodeMap;
731 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
732 while ( nIt->more() )
734 const SMDS_MeshNode* node = smdsNode( nIt->next() );
735 const SMDS_EdgePosition* epos =
736 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
737 double u = epos->GetUParameter();
738 paramNodeMap.insert( make_pair( u, node ));
740 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
741 // wrong U on edge, project
743 BRepAdaptor_Curve aCurve( edge );
744 proj.Initialize( aCurve, f, l );
745 paramNodeMap.clear();
746 nIt = eSubMesh->GetNodes();
747 for ( int iNode = 0; nIt->more(); ++iNode ) {
748 const SMDS_MeshNode* node = smdsNode( nIt->next() );
749 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
751 if ( proj.IsDone() ) {
752 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
753 if ( proj.IsMin( i )) {
754 u = proj.Point( i ).Parameter();
758 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
760 paramNodeMap.insert( make_pair( u, node ));
763 // put U in [0,1] so that the first key-point has U==0
764 bool isSeam = helper.IsRealSeam( edge );
766 TParamNodeMap::iterator unIt = paramNodeMap.begin();
767 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
768 while ( unIt != paramNodeMap.end() )
770 TPoint* p = & myPoints[ iPoint ];
771 ePoints.push_back( p );
772 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
773 if ( isSeam && !isForward )
774 closeNodePointIDMap.insert( make_pair( node, iPoint ));
776 nodePointIDMap.insert ( make_pair( node, iPoint ));
779 p->myInitUV = project( node, projector );
781 double u = isForward ? (*unIt).first : (*unRIt).first;
782 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
783 p->myInitUV = C2d->Value( u ).XY();
785 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
790 // the reverse key-point
791 vPoint = & getShapePoints( v2 );
792 if ( vPoint->empty() )
794 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
795 if ( vSubMesh && vSubMesh->NbNodes() ) {
796 myKeyPointIDs.push_back( iPoint );
797 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
798 const SMDS_MeshNode* node = nIt->next();
799 if ( v2.Orientation() == TopAbs_REVERSED )
800 closeNodePointIDMap.insert( make_pair( node, iPoint ));
802 nodePointIDMap.insert( make_pair( node, iPoint ));
804 TPoint* keyPoint = &myPoints[ iPoint++ ];
805 vPoint->push_back( keyPoint );
807 keyPoint->myInitUV = project( node, projector );
809 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
810 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
813 if ( !vPoint->empty() )
814 ePoints.push_back( vPoint->front() );
816 // compute U of edge-points
819 double totalDist = 0;
820 list< TPoint* >::iterator pIt = ePoints.begin();
821 TPoint* prevP = *pIt;
822 prevP->myInitU = totalDist;
823 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
825 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
826 p->myInitU = totalDist;
829 if ( totalDist > DBL_MIN)
830 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
832 p->myInitU /= totalDist;
835 } // loop on edges of a wire
837 // Load in-face points and elements
839 if ( fSubMesh && fSubMesh->NbElements() )
841 list< TPoint* > & fPoints = getShapePoints( face );
842 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
843 while ( nIt->more() )
845 const SMDS_MeshNode* node = smdsNode( nIt->next() );
846 nodePointIDMap.insert( make_pair( node, iPoint ));
847 TPoint* p = &myPoints[ iPoint++ ];
848 fPoints.push_back( p );
850 p->myInitUV = project( node, projector );
852 const SMDS_FacePosition* pos =
853 static_cast<const SMDS_FacePosition*>(node->GetPosition().get());
854 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
856 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
859 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
860 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
861 while ( elemIt->more() )
863 const SMDS_MeshElement* elem = elemIt->next();
864 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
865 myElemPointIDs.push_back( TElemDef() );
866 TElemDef& elemPoints = myElemPointIDs.back();
867 // find point indices corresponding to element nodes
868 while ( nIt->more() )
870 const SMDS_MeshNode* node = smdsNode( nIt->next() );
871 iPoint = nodePointIDMap[ node ]; // point index of interest
872 // for a node on a seam edge there are two points
873 if ( helper.IsRealSeam( node->GetPosition()->GetShapeId() ) &&
874 ( n_id = closeNodePointIDMap.find( node )) != not_found )
876 TPoint & p1 = myPoints[ iPoint ];
877 TPoint & p2 = myPoints[ n_id->second ];
878 // Select point closest to the rest nodes of element in UV space
879 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
880 const SMDS_MeshNode* notSeamNode = 0;
881 // find node not on a seam edge
882 while ( nIt2->more() && !notSeamNode ) {
883 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
884 if ( !helper.IsSeamShape( n->GetPosition()->GetShapeId() ))
887 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
888 double dist1 = uv.SquareDistance( p1.myInitUV );
889 double dist2 = uv.SquareDistance( p2.myInitUV );
891 iPoint = n_id->second;
893 elemPoints.push_back( iPoint );
898 myIsBoundaryPointsFound = true;
901 // Assure that U range is proportional to V range
904 vector< TPoint >::iterator pVecIt = myPoints.begin();
905 for ( ; pVecIt != myPoints.end(); pVecIt++ )
906 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
907 double minU, minV, maxU, maxV;
908 bndBox.Get( minU, minV, maxU, maxV );
909 double dU = maxU - minU, dV = maxV - minV;
910 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
913 // define where is the problem, in the face or in the mesh
914 TopExp_Explorer vExp( face, TopAbs_VERTEX );
915 for ( ; vExp.More(); vExp.Next() ) {
916 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
919 bndBox.Get( minU, minV, maxU, maxV );
920 dU = maxU - minU, dV = maxV - minV;
921 if ( dU <= DBL_MIN || dV <= DBL_MIN )
923 return setErrorCode( ERR_LOADF_NARROW_FACE );
925 // mesh is projected onto a line, e.g.
926 return setErrorCode( ERR_LOADF_CANT_PROJECT );
928 double ratio = dU / dV, maxratio = 3, scale;
930 if ( ratio > maxratio ) {
931 scale = ratio / maxratio;
934 else if ( ratio < 1./maxratio ) {
935 scale = maxratio / ratio;
940 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
941 TPoint & p = *pVecIt;
942 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
943 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
946 if ( myElemPointIDs.empty() ) {
947 MESSAGE( "No elements bound to the face");
948 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
951 return setErrorCode( ERR_OK );
954 //=======================================================================
955 //function : computeUVOnEdge
956 //purpose : compute coordinates of points on theEdge
957 //=======================================================================
959 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
960 const list< TPoint* > & ePoints )
962 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
964 Handle(Geom2d_Curve) C2d =
965 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
967 ePoints.back()->myInitU = 1.0;
968 list< TPoint* >::const_iterator pIt = ePoints.begin();
969 for ( pIt++; pIt != ePoints.end(); pIt++ )
971 TPoint* point = *pIt;
973 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
974 point->myU = ( f * ( 1 - du ) + l * du );
976 point->myUV = C2d->Value( point->myU ).XY();
980 //=======================================================================
981 //function : intersectIsolines
983 //=======================================================================
985 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
986 const gp_XY& uv21, const gp_XY& uv22, const double r2,
990 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
991 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
992 resUV = 0.5 * ( loc1 + loc2 );
993 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
994 // SKL 26.07.2007 for NPAL16567
995 double d1 = (uv11-uv12).Modulus();
996 double d2 = (uv21-uv22).Modulus();
997 // double delta = d1*d2*1e-6; PAL17233
998 double delta = min( d1, d2 ) / 10.;
999 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1001 // double len1 = ( uv11 - uv12 ).Modulus();
1002 // double len2 = ( uv21 - uv22 ).Modulus();
1003 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1007 // gp_Lin2d line1( uv11, uv12 - uv11 );
1008 // gp_Lin2d line2( uv21, uv22 - uv21 );
1009 // double angle = Abs( line1.Angle( line2 ) );
1011 // IntAna2d_AnaIntersection inter;
1012 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1013 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1015 // gp_Pnt2d interUV = inter.Point(1).Value();
1016 // resUV += interUV.XY();
1017 // inter.Perform( line1, line2 );
1018 // interUV = inter.Point(1).Value();
1019 // resUV += interUV.XY();
1024 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1025 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1030 //=======================================================================
1031 //function : compUVByIsoIntersection
1033 //=======================================================================
1035 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1036 const gp_XY& theInitUV,
1038 bool & theIsDeformed )
1040 // compute UV by intersection of 2 iso lines
1041 //gp_Lin2d isoLine[2];
1042 gp_XY uv1[2], uv2[2];
1044 const double zero = DBL_MIN;
1045 for ( int iIso = 0; iIso < 2; iIso++ )
1047 // to build an iso line:
1048 // find 2 pairs of consequent edge-points such that the range of their
1049 // initial parameters encloses the in-face point initial parameter
1050 gp_XY UV[2], initUV[2];
1051 int nbUV = 0, iCoord = iIso + 1;
1052 double initParam = theInitUV.Coord( iCoord );
1054 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1055 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1057 const list< TPoint* > & bndPoints = * bndIt;
1058 TPoint* prevP = bndPoints.back(); // this is the first point
1059 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1060 bool coincPrev = false;
1061 // loop on the edge-points
1062 for ( ; pIt != bndPoints.end(); pIt++ )
1064 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1065 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1066 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1067 if (!coincPrev && // ignore if initParam coincides with prev point param
1068 sumOfDiff > zero && // ignore if both points coincide with initParam
1069 prevParamDiff * paramDiff <= zero )
1071 // find UV in parametric space of theFace
1072 double r = Abs(prevParamDiff) / sumOfDiff;
1073 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1076 // throw away uv most distant from <theInitUV>
1077 gp_XY vec0 = initUV[0] - theInitUV;
1078 gp_XY vec1 = initUV[1] - theInitUV;
1079 gp_XY vec = uvInit - theInitUV;
1080 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1081 double dist0 = vec0.SquareModulus();
1082 double dist1 = vec1.SquareModulus();
1083 double dist = vec .SquareModulus();
1084 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1085 i = ( dist0 < dist1 ? 1 : 0 );
1086 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1087 i = 3; // theInitUV must remain between
1091 initUV[ i ] = uvInit;
1092 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1094 coincPrev = ( Abs(paramDiff) <= zero );
1101 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1102 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1103 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1104 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1106 // an iso line should be normal to UV[0] - UV[1] direction
1107 // and be located at the same relative distance as from initial ends
1108 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1110 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1111 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1112 //isoLine[ iIso ] = iso.Normal( isoLoc );
1113 uv1[ iIso ] = UV[0];
1114 uv2[ iIso ] = UV[1];
1117 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1118 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1119 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1120 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1127 // ==========================================================
1128 // structure representing a node of a grid of iso-poly-lines
1129 // ==========================================================
1136 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1137 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1138 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1139 TIsoNode(double initU, double initV):
1140 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1141 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1142 bool IsUVComputed() const
1143 { return myUV.X() != 1e100; }
1144 bool IsMovable() const
1145 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1146 void SetNotMovable()
1147 { myIsMovable = false; }
1148 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1149 { myBndNodes[ iDir + i * 2 ] = node; }
1150 TIsoNode* GetBoundaryNode(int iDir, int i)
1151 { return myBndNodes[ iDir + i * 2 ]; }
1152 void SetNext(TIsoNode* node, int iDir, int isForward)
1153 { myNext[ iDir + isForward * 2 ] = node; }
1154 TIsoNode* GetNext(int iDir, int isForward)
1155 { return myNext[ iDir + isForward * 2 ]; }
1158 //=======================================================================
1159 //function : getNextNode
1161 //=======================================================================
1163 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1165 TIsoNode* n = node->myNext[ dir ];
1166 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1167 n = 0;//node->myBndNodes[ dir ];
1168 // MESSAGE("getNextNode: use bnd for node "<<
1169 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1173 //=======================================================================
1174 //function : checkQuads
1175 //purpose : check if newUV destortes quadrangles around node,
1176 // and if ( crit == FIX_OLD ) fix newUV in this case
1177 //=======================================================================
1179 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1181 static bool checkQuads (const TIsoNode* node,
1183 const bool reversed,
1184 const int crit = FIX_OLD,
1185 double fixSize = 0.)
1187 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1188 int nbOldFix = 0, nbOldImpr = 0;
1189 double newBadRate = 0, oldBadRate = 0;
1190 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1191 int i, dir1 = 0, dir2 = 3;
1192 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1194 if ( dir2 > 3 ) dir2 = 0;
1196 // walking counterclockwise around a quad,
1197 // nodes are in the order: node, n[0], n[1], n[2]
1198 n[0] = getNextNode( node, dir1 );
1199 n[2] = getNextNode( node, dir2 );
1200 if ( !n[0] || !n[2] ) continue;
1201 n[1] = getNextNode( n[0], dir2 );
1202 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1203 bool isTriangle = ( !n[1] );
1205 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1207 // if ( fixSize != 0 ) {
1208 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1209 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1210 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1211 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1213 // check if a quadrangle is degenerated
1215 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1216 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1219 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1222 // find min size of the diagonal node-n[1]
1223 double minDiag = fixSize;
1224 if ( minDiag == 0. ) {
1225 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1226 if ( !isTriangle ) {
1227 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1228 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1230 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1231 minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1234 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1235 // ( behind means "to the right of")
1237 // 1. newUV is not behind 01 and 12 dirs
1238 // 2. or newUV is not behind 02 dir and n[2] is convex
1239 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1240 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1241 gp_Vec2d moveVec[3], outVec[3];
1242 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1244 bool isDiag = ( i == 2 );
1245 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1249 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1251 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1253 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1255 gp_Vec2d newDir( n[i]->myUV, newUV );
1256 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1258 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1259 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1260 if ( crit == FIX_OLD ) {
1261 wasIn[i] = ( outDir * oldDir < 0 );
1262 wasOk[i] = ( outDir * oldDir < -minDiag );
1264 newBadRate += outDir * newDir;
1266 oldBadRate += outDir * oldDir;
1269 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1270 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1271 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1272 moveVec[i] = ( oldDist - minDiag ) * outDir;
1277 // check if n[2] is convex
1280 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1282 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1283 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1284 newIsOk = ( newIsOk && isNewOk );
1285 newIsIn = ( newIsIn && isNewIn );
1287 if ( crit != FIX_OLD ) {
1288 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1289 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1293 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1294 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1295 oldIsIn = ( oldIsIn && isOldIn );
1296 oldIsOk = ( oldIsOk && isOldIn );
1299 if ( !isOldIn ) { // node is outside a quadrangle
1300 // move newUV inside a quadrangle
1301 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1302 // node and newUV are outside: push newUV inside
1304 if ( convex || isTriangle ) {
1305 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1308 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1309 double outSize = out.Magnitude();
1310 if ( outSize > DBL_MIN )
1313 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1314 uv = n[1]->myUV - minDiag * out.XY();
1316 oldUVFixed[ nbOldFix++ ] = uv;
1317 //node->myUV = newUV;
1319 else if ( !isOldOk ) {
1320 // try to fix old UV: move node inside as less as possible
1321 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1322 gp_XY uv1, uv2 = node->myUV;
1323 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1325 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1326 while ( !isOldOk ) {
1327 // find the least moveVec
1329 double minMove2 = 1e100;
1330 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1332 if ( moveVec[i].Coord(1) < 1e100 ) {
1333 double move2 = moveVec[i].SquareMagnitude();
1334 if ( move2 < minMove2 ) {
1343 // move node to newUV
1344 uv1 = node->myUV + moveVec[ iMin ].XY();
1345 uv2 += moveVec[ iMin ].XY();
1346 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1347 // check if uv1 is ok
1348 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1349 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1350 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1352 oldUVImpr[ nbOldImpr++ ] = uv1;
1354 // check if uv2 is ok
1355 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1356 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1357 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1359 oldUVImpr[ nbOldImpr++ ] = uv2;
1364 } // loop on 4 quadrangles around <node>
1366 if ( crit == CHECK_NEW_OK )
1368 if ( crit == CHECK_NEW_IN )
1377 if ( oldIsIn && nbOldImpr ) {
1378 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1379 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1380 gp_XY uv = oldUVImpr[ 0 ];
1381 for ( int i = 1; i < nbOldImpr; i++ )
1382 uv += oldUVImpr[ i ];
1384 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1389 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1392 if ( !oldIsIn && nbOldFix ) {
1393 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1394 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1395 gp_XY uv = oldUVFixed[ 0 ];
1396 for ( int i = 1; i < nbOldFix; i++ )
1397 uv += oldUVFixed[ i ];
1399 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1404 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1407 if ( newIsIn && oldIsIn )
1408 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1409 else if ( !newIsIn )
1416 //=======================================================================
1417 //function : compUVByElasticIsolines
1418 //purpose : compute UV as nodes of iso-poly-lines consisting of
1419 // segments keeping relative size as in the pattern
1420 //=======================================================================
1421 //#define DEB_COMPUVBYELASTICISOLINES
1422 bool SMESH_Pattern::
1423 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1424 const list< TPoint* >& thePntToCompute)
1426 return false; // PAL17233
1427 //cout << "============================== KEY POINTS =============================="<<endl;
1428 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1429 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1430 // TPoint& p = myPoints[ *kpIt ];
1431 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1432 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1434 //cout << "=============================="<<endl;
1436 // Define parameters of iso-grid nodes in U and V dir
1438 set< double > paramSet[ 2 ];
1439 list< list< TPoint* > >::const_iterator pListIt;
1440 list< TPoint* >::const_iterator pIt;
1441 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1442 const list< TPoint* > & pList = * pListIt;
1443 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1444 paramSet[0].insert( (*pIt)->myInitUV.X() );
1445 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1448 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1449 paramSet[0].insert( (*pIt)->myInitUV.X() );
1450 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1452 // unite close parameters and split too long segments
1455 for ( iDir = 0; iDir < 2; iDir++ )
1457 set< double > & params = paramSet[ iDir ];
1458 double range = ( *params.rbegin() - *params.begin() );
1459 double toler = range / 1e6;
1460 tol[ iDir ] = toler;
1461 // double maxSegment = range / params.size() / 2.;
1463 // set< double >::iterator parIt = params.begin();
1464 // double prevPar = *parIt;
1465 // for ( parIt++; parIt != params.end(); parIt++ )
1467 // double segLen = (*parIt) - prevPar;
1468 // if ( segLen < toler )
1469 // ;//params.erase( prevPar ); // unite
1470 // else if ( segLen > maxSegment )
1471 // params.insert( prevPar + 0.5 * segLen ); // split
1472 // prevPar = (*parIt);
1476 // Make nodes of a grid of iso-poly-lines
1478 list < TIsoNode > nodes;
1479 typedef list < TIsoNode *> TIsoLine;
1480 map < double, TIsoLine > isoMap[ 2 ];
1482 set< double > & params0 = paramSet[ 0 ];
1483 set< double >::iterator par0It = params0.begin();
1484 for ( ; par0It != params0.end(); par0It++ )
1486 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1487 set< double > & params1 = paramSet[ 1 ];
1488 set< double >::iterator par1It = params1.begin();
1489 for ( ; par1It != params1.end(); par1It++ )
1491 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1492 isoLine0.push_back( & nodes.back() );
1493 isoMap[1][ *par1It ].push_back( & nodes.back() );
1497 // Compute intersections of boundaries with iso-lines:
1498 // only boundary nodes will have computed UV so far
1501 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1502 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1503 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1505 const list< TPoint* > & bndPoints = * bndIt;
1506 TPoint* prevP = bndPoints.back(); // this is the first point
1507 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1508 // loop on the edge-points
1509 for ( ; pIt != bndPoints.end(); pIt++ )
1511 TPoint* point = *pIt;
1512 for ( iDir = 0; iDir < 2; iDir++ )
1514 const int iCoord = iDir + 1;
1515 const int iOtherCoord = 2 - iDir;
1516 double par1 = prevP->myInitUV.Coord( iCoord );
1517 double par2 = point->myInitUV.Coord( iCoord );
1518 double parDif = par2 - par1;
1519 if ( Abs( parDif ) <= DBL_MIN )
1521 // find iso-lines intersecting a bounadry
1522 double toler = tol[ 1 - iDir ];
1523 double minPar = Min ( par1, par2 );
1524 double maxPar = Max ( par1, par2 );
1525 map < double, TIsoLine >& isos = isoMap[ iDir ];
1526 map < double, TIsoLine >::iterator isoIt = isos.begin();
1527 for ( ; isoIt != isos.end(); isoIt++ )
1529 double isoParam = (*isoIt).first;
1530 if ( isoParam < minPar || isoParam > maxPar )
1532 double r = ( isoParam - par1 ) / parDif;
1533 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1534 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1535 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1536 // find existing node with otherPar or insert a new one
1537 TIsoLine & isoLine = (*isoIt).second;
1539 TIsoLine::iterator nIt = isoLine.begin();
1540 for ( ; nIt != isoLine.end(); nIt++ ) {
1541 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1542 if ( nodePar >= otherPar )
1546 if ( Abs( nodePar - otherPar ) <= toler )
1547 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1549 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1550 node = & nodes.back();
1551 isoLine.insert( nIt, node );
1553 node->SetNotMovable();
1555 uvBnd.Add( gp_Pnt2d( uv ));
1556 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1558 gp_XY tgt( point->myUV - prevP->myUV );
1559 if ( ::IsEqual( r, 1. ))
1560 node->myDir[ 0 ] = tgt;
1561 else if ( ::IsEqual( r, 0. ))
1562 node->myDir[ 1 ] = tgt;
1564 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1565 // keep boundary nodes corresponding to boundary points
1566 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1567 if ( bndNodes.empty() || bndNodes.back() != node )
1568 bndNodes.push_back( node );
1569 } // loop on isolines
1570 } // loop on 2 directions
1572 } // loop on boundary points
1573 } // loop on boundaries
1575 // Define orientation
1577 // find the point with the least X
1578 double leastX = DBL_MAX;
1579 TIsoNode * leftNode;
1580 list < TIsoNode >::iterator nodeIt = nodes.begin();
1581 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1582 TIsoNode & node = *nodeIt;
1583 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1584 leastX = node.myUV.X();
1587 // if ( node.IsUVComputed() ) {
1588 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1589 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1590 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1591 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1594 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1595 //SCRUTE( reversed );
1597 // Prepare internal nodes:
1599 // 2. compute ratios
1600 // 3. find boundary nodes for each node
1601 // 4. remove nodes out of the boundary
1602 for ( iDir = 0; iDir < 2; iDir++ )
1604 const int iCoord = 2 - iDir; // coord changing along an isoline
1605 map < double, TIsoLine >& isos = isoMap[ iDir ];
1606 map < double, TIsoLine >::iterator isoIt = isos.begin();
1607 for ( ; isoIt != isos.end(); isoIt++ )
1609 TIsoLine & isoLine = (*isoIt).second;
1610 bool firstCompNodeFound = false;
1611 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1612 nPrevIt = nIt = nNextIt = isoLine.begin();
1614 nNextIt++; nNextIt++;
1615 while ( nIt != isoLine.end() )
1617 // 1. connect prev - cur
1618 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1619 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1620 firstCompNodeFound = true;
1621 lastCompNodePos = nPrevIt;
1623 if ( firstCompNodeFound ) {
1624 node->SetNext( prevNode, iDir, 0 );
1625 prevNode->SetNext( node, iDir, 1 );
1628 if ( nNextIt != isoLine.end() ) {
1629 double par1 = prevNode->myInitUV.Coord( iCoord );
1630 double par2 = node->myInitUV.Coord( iCoord );
1631 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1632 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1634 // 3. find boundary nodes
1635 if ( node->IsUVComputed() )
1636 lastCompNodePos = nIt;
1637 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1638 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1639 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1640 if ( (*nIt2)->IsUVComputed() )
1642 if ( nIt2 != isoLine.end() ) {
1644 node->SetBoundaryNode( bndNode1, iDir, 0 );
1645 node->SetBoundaryNode( bndNode2, iDir, 1 );
1646 // cout << "--------------------------------------------------"<<endl;
1647 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1648 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1649 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1650 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1651 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1652 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1655 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1656 node->SetBoundaryNode( 0, iDir, 0 );
1657 node->SetBoundaryNode( 0, iDir, 1 );
1661 if ( nNextIt != isoLine.end() ) nNextIt++;
1662 // 4. remove nodes out of the boundary
1663 if ( !firstCompNodeFound )
1664 isoLine.pop_front();
1665 } // loop on isoLine nodes
1667 // remove nodes after the boundary
1668 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1669 // (*nIt)->SetNotMovable();
1670 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1671 } // loop on isolines
1672 } // loop on 2 directions
1674 // Compute local isoline direction for internal nodes
1677 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1678 map < double, TIsoLine >::iterator isoIt = isos.begin();
1679 for ( ; isoIt != isos.end(); isoIt++ )
1681 TIsoLine & isoLine = (*isoIt).second;
1682 TIsoLine::iterator nIt = isoLine.begin();
1683 for ( ; nIt != isoLine.end(); nIt++ )
1685 TIsoNode* node = *nIt;
1686 if ( node->IsUVComputed() || !node->IsMovable() )
1688 gp_Vec2d aTgt[2], aNorm[2];
1691 for ( iDir = 0; iDir < 2; iDir++ )
1693 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1694 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1695 if ( !bndNode1 || !bndNode2 ) {
1699 const int iCoord = 2 - iDir; // coord changing along an isoline
1700 double par1 = bndNode1->myInitUV.Coord( iCoord );
1701 double par2 = node->myInitUV.Coord( iCoord );
1702 double par3 = bndNode2->myInitUV.Coord( iCoord );
1703 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1705 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1706 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1707 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1708 else tgt1.Reverse();
1709 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1711 if ( ratio[ iDir ] < 0.5 )
1712 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1714 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1716 aNorm[ iDir ].Reverse(); // along iDir isoline
1718 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1719 // maybe angle is more than |PI|
1720 if ( Abs( angle ) > PI / 2. ) {
1721 // check direction of the last but one perpendicular isoline
1722 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1723 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1724 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1725 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1726 if ( isoDir * tgt2 < 0 )
1728 double angle2 = tgt1.Angle( isoDir );
1729 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1730 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1731 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1732 //MESSAGE("REVERSE ANGLE");
1735 if ( Abs( angle2 ) > Abs( angle ) ||
1736 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1737 //MESSAGE("Add PI");
1738 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1739 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1740 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1741 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1742 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1743 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1746 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1750 for ( iDir = 0; iDir < 2; iDir++ )
1752 aTgt[iDir].Normalize();
1753 aNorm[1-iDir].Normalize();
1754 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1757 node->myDir[iDir] = //aTgt[iDir];
1758 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1760 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1761 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1762 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1763 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1765 } // loop on iso nodes
1766 } // loop on isolines
1768 // Find nodes to start computing UV from
1770 list< TIsoNode* > startNodes;
1771 list< TIsoNode* >::iterator nIt = bndNodes.end();
1772 TIsoNode* node = *(--nIt);
1773 TIsoNode* prevNode = *(--nIt);
1774 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1776 TIsoNode* nextNode = *nIt;
1777 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1778 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1779 double initAngle = initTgt1.Angle( initTgt2 );
1780 double angle = node->myDir[0].Angle( node->myDir[1] );
1781 if ( reversed ) angle = -angle;
1782 if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1783 // find a close internal node
1784 TIsoNode* nClose = 0;
1785 list< TIsoNode* > testNodes;
1786 testNodes.push_back( node );
1787 list< TIsoNode* >::iterator it = testNodes.begin();
1788 for ( ; !nClose && it != testNodes.end(); it++ )
1790 for (int i = 0; i < 4; i++ )
1792 nClose = (*it)->myNext[ i ];
1794 if ( !nClose->IsUVComputed() )
1797 testNodes.push_back( nClose );
1803 startNodes.push_back( nClose );
1804 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1805 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1806 // "initAngle: " << initAngle << " angle: " << angle << endl;
1807 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1808 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1809 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1810 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1816 // Compute starting UV of internal nodes
1818 list < TIsoNode* > internNodes;
1819 bool needIteration = true;
1820 if ( startNodes.empty() ) {
1821 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1822 needIteration = false;
1823 map < double, TIsoLine >& isos = isoMap[ 0 ];
1824 map < double, TIsoLine >::iterator isoIt = isos.begin();
1825 for ( ; isoIt != isos.end(); isoIt++ )
1827 TIsoLine & isoLine = (*isoIt).second;
1828 TIsoLine::iterator nIt = isoLine.begin();
1829 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1831 TIsoNode* node = *nIt;
1832 if ( !node->IsUVComputed() && node->IsMovable() ) {
1833 internNodes.push_back( node );
1835 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1836 node->myUV, needIteration ))
1837 node->myUV = node->myInitUV;
1841 if ( needIteration )
1842 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1844 TIsoNode* node = *nIt, *nClose = 0;
1845 list< TIsoNode* > testNodes;
1846 testNodes.push_back( node );
1847 list< TIsoNode* >::iterator it = testNodes.begin();
1848 for ( ; !nClose && it != testNodes.end(); it++ )
1850 for (int i = 0; i < 4; i++ )
1852 nClose = (*it)->myNext[ i ];
1854 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1857 testNodes.push_back( nClose );
1863 startNodes.push_back( nClose );
1867 double aMin[2], aMax[2], step[2];
1868 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1869 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1870 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1871 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1872 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1874 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1876 TIsoNode* prevN[2], *node = *nIt;
1877 if ( node->IsUVComputed() || !node->IsMovable() )
1879 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1880 int nbComp = 0, nbPrev = 0;
1881 for ( iDir = 0; iDir < 2; iDir++ )
1883 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1884 TIsoNode* n = node->GetNext( iDir, 0 );
1885 if ( n->IsUVComputed() )
1888 startNodes.push_back( n );
1889 n = node->GetNext( iDir, 1 );
1890 if ( n->IsUVComputed() )
1893 startNodes.push_back( n );
1895 prevNode1 = prevNode2;
1898 if ( prevNode1 ) nbPrev++;
1899 if ( prevNode2 ) nbPrev++;
1902 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1903 double par = node->myInitUV.Coord( 2 - iDir );
1904 bool isEnd = ( prevPar > par );
1905 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1906 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1907 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1909 MESSAGE("Why we are here?");
1912 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1913 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1914 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1915 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1916 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1917 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1918 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1919 //" par: " << prevPar << endl;
1920 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1921 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1923 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1924 gp_XY & uv1 = prevNode1->myUV;
1925 gp_XY & uv2 = prevNode2->myUV;
1926 // dir = ( uv2 - uv1 );
1927 // double len = dir.Modulus();
1928 // if ( len > DBL_MIN )
1929 // dir /= len * 0.5;
1930 double r = node->myRatio[ iDir ];
1931 newUV += uv1 * ( 1 - r ) + uv2 * r;
1934 newUV += prevNode1->myUV + dir * step[ iDir ];
1937 prevN[ iDir ] = prevNode1;
1941 if ( !nbComp ) continue;
1944 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1946 // check if a quadrangle is not distorted
1948 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1949 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1950 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1951 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1955 internNodes.push_back( node );
1960 static int maxNbIter = 100;
1961 #ifdef DEB_COMPUVBYELASTICISOLINES
1963 bool useNbMoveNode = 0;
1964 static int maxNbNodeMove = 100;
1967 if ( !useNbMoveNode )
1968 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1973 if ( !needIteration) break;
1974 #ifdef DEB_COMPUVBYELASTICISOLINES
1975 if ( nbIter >= maxNbIter ) break;
1978 list < TIsoNode* >::iterator nIt = internNodes.begin();
1979 for ( ; nIt != internNodes.end(); nIt++ ) {
1980 #ifdef DEB_COMPUVBYELASTICISOLINES
1982 cout << nbNodeMove <<" =================================================="<<endl;
1984 TIsoNode * node = *nIt;
1988 for ( iDir = 0; iDir < 2; iDir++ )
1990 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
1991 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
1992 double r = node->myRatio[ iDir ];
1993 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
1994 // line[ iDir ].SetLocation( loc[ iDir ] );
1995 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
1998 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
1999 double locR[2] = { 0, 0 };
2000 for ( iDir = 0; iDir < 2; iDir++ )
2002 const int iCoord = 2 - iDir; // coord changing along an isoline
2003 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2004 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2005 if ( !bndNode1 || !bndNode2 ) {
2008 double par1 = bndNode1->myInitUV.Coord( iCoord );
2009 double par2 = node->myInitUV.Coord( iCoord );
2010 double par3 = bndNode2->myInitUV.Coord( iCoord );
2011 double r = ( par2 - par1 ) / ( par3 - par1 );
2012 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2013 locR[ iDir ] = ( 1 - r * r ) * 0.25;
2015 //locR[0] = locR[1] = 0.25;
2016 // intersect the 2 lines and move a node
2017 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2018 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2020 // double intR = 1 - locR[0] - locR[1];
2021 // gp_XY newUV = inter.Point(1).Value().XY();
2022 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2023 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2025 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2026 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2027 // avoid parallel isolines intersection
2028 checkQuads( node, newUV, reversed );
2030 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2032 } // intersection found
2033 #ifdef DEB_COMPUVBYELASTICISOLINES
2034 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2036 } // loop on internal nodes
2037 #ifdef DEB_COMPUVBYELASTICISOLINES
2038 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2040 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2042 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2044 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2045 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2046 #ifndef DEB_COMPUVBYELASTICISOLINES
2051 // Set computed UV to points
2053 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2054 TPoint* point = *pIt;
2055 //gp_XY oldUV = point->myUV;
2056 double minDist = DBL_MAX;
2057 list < TIsoNode >::iterator nIt = nodes.begin();
2058 for ( ; nIt != nodes.end(); nIt++ ) {
2059 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2060 if ( dist < minDist ) {
2062 point->myUV = (*nIt).myUV;
2071 //=======================================================================
2072 //function : setFirstEdge
2073 //purpose : choose the best first edge of theWire; return the summary distance
2074 // between point UV computed by isolines intersection and
2075 // eventual UV got from edge p-curves
2076 //=======================================================================
2078 //#define DBG_SETFIRSTEDGE
2079 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2081 int iE, nbEdges = theWire.size();
2085 // Transform UVs computed by iso to fit bnd box of a wire
2087 // max nb of points on an edge
2089 int eID = theFirstEdgeID;
2090 for ( iE = 0; iE < nbEdges; iE++ )
2091 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2093 // compute bnd boxes
2094 TopoDS_Face face = TopoDS::Face( myShape );
2095 Bnd_Box2d bndBox, eBndBox;
2096 eID = theFirstEdgeID;
2097 list< TopoDS_Edge >::iterator eIt;
2098 list< TPoint* >::iterator pIt;
2099 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2101 // UV by isos stored in TPoint.myXYZ
2102 list< TPoint* > & ePoints = getShapePoints( eID++ );
2103 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2105 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2107 // UV by an edge p-curve
2109 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2110 double dU = ( l - f ) / ( maxNbPnt - 1 );
2111 for ( int i = 0; i < maxNbPnt; i++ )
2112 eBndBox.Add( C2d->Value( f + i * dU ));
2115 // transform UVs by isos
2116 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2117 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2118 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2119 #ifdef DBG_SETFIRSTEDGE
2120 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2121 << eMinPar[1] << " - " << eMaxPar[1] );
2123 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2125 double dMin = eMinPar[i] - minPar[i];
2126 double dMax = eMaxPar[i] - maxPar[i];
2127 double dPar = maxPar[i] - minPar[i];
2128 eID = theFirstEdgeID;
2129 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2131 list< TPoint* > & ePoints = getShapePoints( eID++ );
2132 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2134 double par = (*pIt)->myXYZ.Coord( iC );
2135 double r = ( par - minPar[i] ) / dPar;
2136 par += ( 1 - r ) * dMin + r * dMax;
2137 (*pIt)->myXYZ.SetCoord( iC, par );
2143 double minDist = DBL_MAX;
2144 for ( iE = 0 ; iE < nbEdges; iE++ )
2146 #ifdef DBG_SETFIRSTEDGE
2147 MESSAGE ( " VARIANT " << iE );
2149 // evaluate the distance between UV computed by the 2 methods:
2150 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2152 int eID = theFirstEdgeID;
2153 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2155 list< TPoint* > & ePoints = getShapePoints( eID++ );
2156 computeUVOnEdge( *eIt, ePoints );
2157 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2159 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2160 #ifdef DBG_SETFIRSTEDGE
2161 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2162 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2166 #ifdef DBG_SETFIRSTEDGE
2167 MESSAGE ( "dist -- " << dist );
2169 if ( dist < minDist ) {
2171 eBest = theWire.front();
2173 // check variant with another first edge
2174 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2176 // put the best first edge to the theWire front
2177 if ( eBest != theWire.front() ) {
2178 eIt = find ( theWire.begin(), theWire.end(), eBest );
2179 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2185 //=======================================================================
2186 //function : sortSameSizeWires
2187 //purpose : sort wires in theWireList from theFromWire until theToWire,
2188 // the wires are set in the order to correspond to the order
2189 // of boundaries; after sorting, edges in the wires are put
2190 // in a good order, point UVs on edges are computed and points
2191 // are appended to theEdgesPointsList
2192 //=======================================================================
2194 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2195 const TListOfEdgesList::iterator& theFromWire,
2196 const TListOfEdgesList::iterator& theToWire,
2197 const int theFirstEdgeID,
2198 list< list< TPoint* > >& theEdgesPointsList )
2200 TopoDS_Face F = TopoDS::Face( myShape );
2201 int iW, nbWires = 0;
2202 TListOfEdgesList::iterator wlIt = theFromWire;
2203 while ( wlIt++ != theToWire )
2206 // Recompute key-point UVs by isolines intersection,
2207 // compute CG of key-points for each wire and bnd boxes of GCs
2210 gp_XY orig( gp::Origin2d().XY() );
2211 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2212 Bnd_Box2d bndBox, vBndBox;
2213 int eID = theFirstEdgeID;
2214 list< TopoDS_Edge >::iterator eIt;
2215 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2217 list< TopoDS_Edge > & wire = *wlIt;
2218 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2220 list< TPoint* > & ePoints = getShapePoints( eID++ );
2221 TPoint* p = ePoints.front();
2222 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2223 MESSAGE("cant sortSameSizeWires()");
2226 gcVec[iW] += p->myUV;
2227 bndBox.Add( gp_Pnt2d( p->myUV ));
2228 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2229 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2230 vGcVec[iW] += vXY.XY();
2232 // keep the computed UV to compare against by setFirstEdge()
2233 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2235 gcVec[iW] /= nbWires;
2236 vGcVec[iW] /= nbWires;
2237 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2238 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2241 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2243 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2244 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2245 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2246 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2248 double dMin = vMinPar[i] - minPar[i];
2249 double dMax = vMaxPar[i] - maxPar[i];
2250 double dPar = maxPar[i] - minPar[i];
2251 if ( Abs( dPar ) <= DBL_MIN )
2253 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2254 double par = gcVec[iW].Coord( iC );
2255 double r = ( par - minPar[i] ) / dPar;
2256 par += ( 1 - r ) * dMin + r * dMax;
2257 gcVec[iW].SetCoord( iC, par );
2261 // Define boundary - wire correspondence by GC closeness
2263 TListOfEdgesList tmpWList;
2264 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2265 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2266 TIntWirePosMap bndIndWirePosMap;
2267 vector< bool > bndFound( nbWires, false );
2268 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2270 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2271 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2272 double minDist = DBL_MAX;
2273 gp_XY & wGc = vGcVec[ iW ];
2275 for ( int iB = 0; iB < nbWires; iB++ ) {
2276 if ( bndFound[ iB ] ) continue;
2277 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2278 if ( dist < minDist ) {
2283 bndFound[ bIndex ] = true;
2284 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2289 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2290 eID = theFirstEdgeID;
2291 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2293 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2294 list < TopoDS_Edge > & wire = ( *wirePos );
2296 // choose the best first edge of a wire
2297 setFirstEdge( wire, eID );
2299 // compute eventual UV and fill theEdgesPointsList
2300 theEdgesPointsList.push_back( list< TPoint* >() );
2301 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2302 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2304 list< TPoint* > & ePoints = getShapePoints( eID++ );
2305 computeUVOnEdge( *eIt, ePoints );
2306 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2308 // put wire back to theWireList
2310 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2316 //=======================================================================
2318 //purpose : Compute nodes coordinates applying
2319 // the loaded pattern to <theFace>. The first key-point
2320 // will be mapped into <theVertexOnKeyPoint1>
2321 //=======================================================================
2323 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2324 const TopoDS_Vertex& theVertexOnKeyPoint1,
2325 const bool theReverse)
2327 MESSAGE(" ::Apply(face) " );
2328 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2329 if ( !setShapeToMesh( face ))
2332 // find points on edges, it fills myNbKeyPntInBoundary
2333 if ( !findBoundaryPoints() )
2336 // Define the edges order so that the first edge starts at
2337 // theVertexOnKeyPoint1
2339 list< TopoDS_Edge > eList;
2340 list< int > nbVertexInWires;
2341 int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2342 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2344 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2345 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2347 // check nb wires and edges
2348 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2349 l1.sort(); l2.sort();
2352 MESSAGE( "Wrong nb vertices in wires" );
2353 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2356 // here shapes get IDs, for the outer wire IDs are OK
2357 list<TopoDS_Edge>::iterator elIt = eList.begin();
2358 for ( ; elIt != eList.end(); elIt++ ) {
2359 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2360 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2361 // BEGIN: jfa for bug 0019943
2364 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2365 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2367 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2368 if (we.Current().IsSame(*elIt)) {
2370 if (nbe == 2) isClosed1 = true;
2375 // END: jfa for bug 0019943
2377 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2379 int nbVertices = myShapeIDMap.Extent();
2381 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2382 myShapeIDMap.Add( *elIt );
2384 myShapeIDMap.Add( face );
2386 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2387 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2388 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2391 // points on edges to be used for UV computation of in-face points
2392 list< list< TPoint* > > edgesPointsList;
2393 edgesPointsList.push_back( list< TPoint* >() );
2394 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2395 list< TPoint* >::iterator pIt;
2397 // compute UV of points on the outer wire
2398 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2399 for (iE = 0, elIt = eList.begin();
2400 iE < nbEdgesInOuterWire && elIt != eList.end();
2403 list< TPoint* > & ePoints = getShapePoints( *elIt );
2405 computeUVOnEdge( *elIt, ePoints );
2406 // collect on-edge points (excluding the last one)
2407 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2410 // If there are several wires, define the order of edges of inner wires:
2411 // compute UV of inner edge-points using 2 methods: the one for in-face points
2412 // and the one for on-edge points and then choose the best edge order
2413 // by the best correspondance of the 2 results
2416 // compute UV of inner edge-points using the method for in-face points
2417 // and devide eList into a list of separate wires
2419 list< list< TopoDS_Edge > > wireList;
2420 list<TopoDS_Edge>::iterator eIt = elIt;
2421 list<int>::iterator nbEIt = nbVertexInWires.begin();
2422 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2424 int nbEdges = *nbEIt;
2425 wireList.push_back( list< TopoDS_Edge >() );
2426 list< TopoDS_Edge > & wire = wireList.back();
2427 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2429 list< TPoint* > & ePoints = getShapePoints( *eIt );
2430 pIt = ePoints.begin();
2431 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2433 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2434 MESSAGE("cant Apply(face)");
2437 // keep the computed UV to compare against by setFirstEdge()
2438 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2440 wire.push_back( *eIt );
2443 // remove inner edges from eList
2444 eList.erase( elIt, eList.end() );
2446 // sort wireList by nb edges in a wire
2447 sortBySize< TopoDS_Edge > ( wireList );
2449 // an ID of the first edge of a boundary
2450 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2451 // if ( nbSeamShapes > 0 )
2452 // id1 += 2; // 2 vertices more
2454 // find points - edge correspondence for wires of unique size,
2455 // edge order within a wire should be defined only
2457 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2458 while ( wlIt != wireList.end() )
2460 list< TopoDS_Edge >& wire = (*wlIt);
2461 int nbEdges = wire.size();
2463 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2465 // choose the best first edge of a wire
2466 setFirstEdge( wire, id1 );
2468 // compute eventual UV and collect on-edge points
2469 edgesPointsList.push_back( list< TPoint* >() );
2470 edgesPoints = & edgesPointsList.back();
2472 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2474 list< TPoint* > & ePoints = getShapePoints( eID++ );
2475 computeUVOnEdge( *eIt, ePoints );
2476 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2482 // find boundary - wire correspondence for several wires of same size
2484 id1 = nbVertices + nbEdgesInOuterWire + 1;
2485 wlIt = wireList.begin();
2486 while ( wlIt != wireList.end() )
2488 int nbSameSize = 0, nbEdges = (*wlIt).size();
2489 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2491 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2495 if ( nbSameSize > 0 )
2496 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2499 id1 += nbEdges * ( nbSameSize + 1 );
2502 // add well-ordered edges to eList
2504 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2506 list< TopoDS_Edge >& wire = (*wlIt);
2507 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2510 // re-fill myShapeIDMap - all shapes get good IDs
2512 myShapeIDMap.Clear();
2513 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2514 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2515 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2516 myShapeIDMap.Add( *elIt );
2517 myShapeIDMap.Add( face );
2519 } // there are inner wires
2521 // Compute XYZ of on-edge points
2523 TopLoc_Location loc;
2524 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2526 BRepAdaptor_Curve C3d( *elIt );
2527 list< TPoint* > & ePoints = getShapePoints( iE++ );
2528 pIt = ePoints.begin();
2529 for ( pIt++; pIt != ePoints.end(); pIt++ )
2531 TPoint* point = *pIt;
2532 point->myXYZ = C3d.Value( point->myU );
2536 // Compute UV and XYZ of in-face points
2538 // try to use a simple algo
2539 list< TPoint* > & fPoints = getShapePoints( face );
2540 bool isDeformed = false;
2541 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2542 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2543 (*pIt)->myUV, isDeformed )) {
2544 MESSAGE("cant Apply(face)");
2547 // try to use a complex algo if it is a difficult case
2548 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2550 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2551 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2552 (*pIt)->myUV, isDeformed )) {
2553 MESSAGE("cant Apply(face)");
2558 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2559 const gp_Trsf & aTrsf = loc.Transformation();
2560 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2562 TPoint * point = *pIt;
2563 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2564 if ( !loc.IsIdentity() )
2565 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2568 myIsComputed = true;
2570 return setErrorCode( ERR_OK );
2573 //=======================================================================
2575 //purpose : Compute nodes coordinates applying
2576 // the loaded pattern to <theFace>. The first key-point
2577 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2578 //=======================================================================
2580 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2581 const int theNodeIndexOnKeyPoint1,
2582 const bool theReverse)
2584 // MESSAGE(" ::Apply(MeshFace) " );
2586 if ( !IsLoaded() ) {
2587 MESSAGE( "Pattern not loaded" );
2588 return setErrorCode( ERR_APPL_NOT_LOADED );
2591 // check nb of nodes
2592 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2593 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2594 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2597 // find points on edges, it fills myNbKeyPntInBoundary
2598 if ( !findBoundaryPoints() )
2601 // check that there are no holes in a pattern
2602 if (myNbKeyPntInBoundary.size() > 1 ) {
2603 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2606 // Define the nodes order
2608 list< const SMDS_MeshNode* > nodes;
2609 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2610 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2612 while ( noIt->more() ) {
2613 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2614 nodes.push_back( node );
2615 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2618 if ( n != nodes.end() ) {
2620 if ( n != --nodes.end() )
2621 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2624 else if ( n != nodes.begin() )
2625 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2627 list< gp_XYZ > xyzList;
2628 myOrderedNodes.resize( theFace->NbNodes() );
2629 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2630 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2631 myOrderedNodes[ iSub++] = *n;
2634 // Define a face plane
2636 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2637 gp_Pnt P ( *xyzIt++ );
2638 gp_Vec Vx( P, *xyzIt++ ), N;
2640 N = Vx ^ gp_Vec( P, *xyzIt++ );
2641 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2642 if ( N.SquareMagnitude() <= DBL_MIN )
2643 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2644 gp_Ax2 pos( P, N, Vx );
2646 // Compute UV of key-points on a plane
2647 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2649 gp_Vec vec ( pos.Location(), *xyzIt );
2650 TPoint* p = getShapePoints( iSub ).front();
2651 p->myUV.SetX( vec * pos.XDirection() );
2652 p->myUV.SetY( vec * pos.YDirection() );
2656 // points on edges to be used for UV computation of in-face points
2657 list< list< TPoint* > > edgesPointsList;
2658 edgesPointsList.push_back( list< TPoint* >() );
2659 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2660 list< TPoint* >::iterator pIt;
2662 // compute UV and XYZ of points on edges
2664 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2666 gp_XYZ& xyz1 = *xyzIt++;
2667 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2669 list< TPoint* > & ePoints = getShapePoints( iSub );
2670 ePoints.back()->myInitU = 1.0;
2671 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2672 while ( *pIt != ePoints.back() )
2675 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2676 gp_Vec vec ( pos.Location(), p->myXYZ );
2677 p->myUV.SetX( vec * pos.XDirection() );
2678 p->myUV.SetY( vec * pos.YDirection() );
2680 // collect on-edge points (excluding the last one)
2681 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2684 // Compute UV and XYZ of in-face points
2686 // try to use a simple algo to compute UV
2687 list< TPoint* > & fPoints = getShapePoints( iSub );
2688 bool isDeformed = false;
2689 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2690 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2691 (*pIt)->myUV, isDeformed )) {
2692 MESSAGE("cant Apply(face)");
2695 // try to use a complex algo if it is a difficult case
2696 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2698 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2699 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2700 (*pIt)->myUV, isDeformed )) {
2701 MESSAGE("cant Apply(face)");
2706 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2708 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2711 myIsComputed = true;
2713 return setErrorCode( ERR_OK );
2716 //=======================================================================
2718 //purpose : Compute nodes coordinates applying
2719 // the loaded pattern to <theFace>. The first key-point
2720 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2721 //=======================================================================
2723 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2724 const SMDS_MeshFace* theFace,
2725 const TopoDS_Shape& theSurface,
2726 const int theNodeIndexOnKeyPoint1,
2727 const bool theReverse)
2729 // MESSAGE(" ::Apply(MeshFace) " );
2730 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2731 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2733 const TopoDS_Face& face = TopoDS::Face( theSurface );
2734 TopLoc_Location loc;
2735 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2736 const gp_Trsf & aTrsf = loc.Transformation();
2738 if ( !IsLoaded() ) {
2739 MESSAGE( "Pattern not loaded" );
2740 return setErrorCode( ERR_APPL_NOT_LOADED );
2743 // check nb of nodes
2744 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2745 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2746 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2749 // find points on edges, it fills myNbKeyPntInBoundary
2750 if ( !findBoundaryPoints() )
2753 // check that there are no holes in a pattern
2754 if (myNbKeyPntInBoundary.size() > 1 ) {
2755 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2758 // Define the nodes order
2760 list< const SMDS_MeshNode* > nodes;
2761 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2762 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2764 while ( noIt->more() ) {
2765 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2766 nodes.push_back( node );
2767 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2770 if ( n != nodes.end() ) {
2772 if ( n != --nodes.end() )
2773 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2776 else if ( n != nodes.begin() )
2777 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2780 // find a node not on a seam edge, if necessary
2781 SMESH_MesherHelper helper( *theMesh );
2782 helper.SetSubShape( theSurface );
2783 const SMDS_MeshNode* inFaceNode = 0;
2784 if ( helper.GetNodeUVneedInFaceNode() )
2786 SMESH_MeshEditor editor( theMesh );
2787 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2788 int shapeID = editor.FindShape( *n );
2790 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2791 if ( !helper.IsSeamShape( shapeID ))
2796 // Set UV of key-points (i.e. of nodes of theFace )
2797 vector< gp_XY > keyUV( theFace->NbNodes() );
2798 myOrderedNodes.resize( theFace->NbNodes() );
2799 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2801 TPoint* p = getShapePoints( iSub ).front();
2802 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2803 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2805 keyUV[ iSub-1 ] = p->myUV;
2806 myOrderedNodes[ iSub-1 ] = *n;
2809 // points on edges to be used for UV computation of in-face points
2810 list< list< TPoint* > > edgesPointsList;
2811 edgesPointsList.push_back( list< TPoint* >() );
2812 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2813 list< TPoint* >::iterator pIt;
2815 // compute UV and XYZ of points on edges
2817 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2819 gp_XY& uv1 = keyUV[ i ];
2820 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2822 list< TPoint* > & ePoints = getShapePoints( iSub );
2823 ePoints.back()->myInitU = 1.0;
2824 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2825 while ( *pIt != ePoints.back() )
2828 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2829 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2830 if ( !loc.IsIdentity() )
2831 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2833 // collect on-edge points (excluding the last one)
2834 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2837 // Compute UV and XYZ of in-face points
2839 // try to use a simple algo to compute UV
2840 list< TPoint* > & fPoints = getShapePoints( iSub );
2841 bool isDeformed = false;
2842 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2843 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2844 (*pIt)->myUV, isDeformed )) {
2845 MESSAGE("cant Apply(face)");
2848 // try to use a complex algo if it is a difficult case
2849 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2851 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2852 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2853 (*pIt)->myUV, isDeformed )) {
2854 MESSAGE("cant Apply(face)");
2859 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2861 TPoint * point = *pIt;
2862 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2863 if ( !loc.IsIdentity() )
2864 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2867 myIsComputed = true;
2869 return setErrorCode( ERR_OK );
2872 //=======================================================================
2873 //function : undefinedXYZ
2875 //=======================================================================
2877 static const gp_XYZ& undefinedXYZ()
2879 static gp_XYZ xyz( 1.e100, 0., 0. );
2883 //=======================================================================
2884 //function : isDefined
2886 //=======================================================================
2888 inline static bool isDefined(const gp_XYZ& theXYZ)
2890 return theXYZ.X() < 1.e100;
2893 //=======================================================================
2895 //purpose : Compute nodes coordinates applying
2896 // the loaded pattern to <theFaces>. The first key-point
2897 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2898 //=======================================================================
2900 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2901 std::set<const SMDS_MeshFace*>& theFaces,
2902 const int theNodeIndexOnKeyPoint1,
2903 const bool theReverse)
2905 MESSAGE(" ::Apply(set<MeshFace>) " );
2907 if ( !IsLoaded() ) {
2908 MESSAGE( "Pattern not loaded" );
2909 return setErrorCode( ERR_APPL_NOT_LOADED );
2912 // find points on edges, it fills myNbKeyPntInBoundary
2913 if ( !findBoundaryPoints() )
2916 // check that there are no holes in a pattern
2917 if (myNbKeyPntInBoundary.size() > 1 ) {
2918 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2923 myElemXYZIDs.clear();
2924 myXYZIdToNodeMap.clear();
2926 myIdsOnBoundary.clear();
2927 myReverseConnectivity.clear();
2929 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2930 myElements.reserve( theFaces.size() );
2932 // to find point index
2933 map< TPoint*, int > pointIndex;
2934 for ( int i = 0; i < myPoints.size(); i++ )
2935 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2937 int ind1 = 0; // lowest point index for a face
2942 // SMESH_MeshEditor editor( theMesh );
2944 // apply to each face in theFaces set
2945 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2946 for ( ; face != theFaces.end(); ++face )
2948 // int curShapeId = editor.FindShape( *face );
2949 // if ( curShapeId != shapeID ) {
2950 // if ( curShapeId )
2951 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2954 // shapeID = curShapeId;
2957 if ( shape.IsNull() )
2958 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2960 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2962 MESSAGE( "Failed on " << *face );
2965 myElements.push_back( *face );
2967 // store computed points belonging to elements
2968 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2969 for ( ; ll != myElemPointIDs.end(); ++ll )
2971 myElemXYZIDs.push_back(TElemDef());
2972 TElemDef& xyzIds = myElemXYZIDs.back();
2973 TElemDef& pIds = *ll;
2974 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
2975 int pIndex = *id + ind1;
2976 xyzIds.push_back( pIndex );
2977 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
2978 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
2981 // put points on links to myIdsOnBoundary,
2982 // they will be used to sew new elements on adjacent refined elements
2983 int nbNodes = (*face)->NbNodes(), eID = nbNodes + 1;
2984 for ( int i = 0; i < nbNodes; i++ )
2986 list< TPoint* > & linkPoints = getShapePoints( eID++ );
2987 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
2988 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
2989 // make a link and a node set
2990 TNodeSet linkSet, node1Set;
2991 linkSet.insert( n1 );
2992 linkSet.insert( n2 );
2993 node1Set.insert( n1 );
2994 list< TPoint* >::iterator p = linkPoints.begin();
2996 // map the first link point to n1
2997 int nId = pointIndex[ *p ] + ind1;
2998 myXYZIdToNodeMap[ nId ] = n1;
2999 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3000 groups.push_back(list< int > ());
3001 groups.back().push_back( nId );
3003 // add the linkSet to the map
3004 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3005 groups.push_back(list< int > ());
3006 list< int >& indList = groups.back();
3007 // add points to the map excluding the end points
3008 for ( p++; *p != linkPoints.back(); p++ )
3009 indList.push_back( pointIndex[ *p ] + ind1 );
3011 ind1 += myPoints.size();
3014 return !myElemXYZIDs.empty();
3017 //=======================================================================
3019 //purpose : Compute nodes coordinates applying
3020 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3021 // will be mapped into <theNode000Index>-th node. The
3022 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3024 //=======================================================================
3026 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3027 const int theNode000Index,
3028 const int theNode001Index)
3030 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3032 if ( !IsLoaded() ) {
3033 MESSAGE( "Pattern not loaded" );
3034 return setErrorCode( ERR_APPL_NOT_LOADED );
3037 // bind ID to points
3038 if ( !findBoundaryPoints() )
3041 // check that there are no holes in a pattern
3042 if (myNbKeyPntInBoundary.size() > 1 ) {
3043 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3048 myElemXYZIDs.clear();
3049 myXYZIdToNodeMap.clear();
3051 myIdsOnBoundary.clear();
3052 myReverseConnectivity.clear();
3054 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3055 myElements.reserve( theVolumes.size() );
3057 // to find point index
3058 map< TPoint*, int > pointIndex;
3059 for ( int i = 0; i < myPoints.size(); i++ )
3060 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3062 int ind1 = 0; // lowest point index for an element
3064 // apply to each element in theVolumes set
3065 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3066 for ( ; vol != theVolumes.end(); ++vol )
3068 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3069 MESSAGE( "Failed on " << *vol );
3072 myElements.push_back( *vol );
3074 // store computed points belonging to elements
3075 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3076 for ( ; ll != myElemPointIDs.end(); ++ll )
3078 myElemXYZIDs.push_back(TElemDef());
3079 TElemDef& xyzIds = myElemXYZIDs.back();
3080 TElemDef& pIds = *ll;
3081 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3082 int pIndex = *id + ind1;
3083 xyzIds.push_back( pIndex );
3084 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3085 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3088 // put points on edges and faces to myIdsOnBoundary,
3089 // they will be used to sew new elements on adjacent refined elements
3090 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3092 // make a set of sub-points
3094 vector< int > subIDs;
3095 if ( SMESH_Block::IsVertexID( Id )) {
3096 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3098 else if ( SMESH_Block::IsEdgeID( Id )) {
3099 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3100 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3101 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3104 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3105 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3106 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3107 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3108 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3109 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3110 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3111 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3114 list< TPoint* > & points = getShapePoints( Id );
3115 list< TPoint* >::iterator p = points.begin();
3116 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3117 groups.push_back(list< int > ());
3118 list< int >& indList = groups.back();
3119 for ( ; p != points.end(); p++ )
3120 indList.push_back( pointIndex[ *p ] + ind1 );
3121 if ( subNodes.size() == 1 ) // vertex case
3122 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3124 ind1 += myPoints.size();
3127 return !myElemXYZIDs.empty();
3130 //=======================================================================
3132 //purpose : Create a pattern from the mesh built on <theBlock>
3133 //=======================================================================
3135 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3136 const TopoDS_Shell& theBlock)
3138 MESSAGE(" ::Load(volume) " );
3141 SMESHDS_SubMesh * aSubMesh;
3143 // load shapes in myShapeIDMap
3145 TopoDS_Vertex v1, v2;
3146 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3147 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3150 int nbNodes = 0, shapeID;
3151 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3153 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3154 aSubMesh = getSubmeshWithElements( theMesh, S );
3156 nbNodes += aSubMesh->NbNodes();
3158 myPoints.resize( nbNodes );
3160 // load U of points on edges
3161 TNodePointIDMap nodePointIDMap;
3163 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3165 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3166 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3167 aSubMesh = getSubmeshWithElements( theMesh, S );
3168 if ( ! aSubMesh ) continue;
3169 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3170 if ( !nIt->more() ) continue;
3172 // store a node and a point
3173 while ( nIt->more() ) {
3174 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3175 nodePointIDMap.insert( make_pair( node, iPoint ));
3176 if ( block.IsVertexID( shapeID ))
3177 myKeyPointIDs.push_back( iPoint );
3178 TPoint* p = & myPoints[ iPoint++ ];
3179 shapePoints.push_back( p );
3180 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3181 p->myInitXYZ.SetCoord( 0,0,0 );
3183 list< TPoint* >::iterator pIt = shapePoints.begin();
3186 switch ( S.ShapeType() )
3191 for ( ; pIt != shapePoints.end(); pIt++ ) {
3192 double * coef = block.GetShapeCoef( shapeID );
3193 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3194 if ( coef[ iCoord - 1] > 0 )
3195 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3197 if ( S.ShapeType() == TopAbs_VERTEX )
3200 const TopoDS_Edge& edge = TopoDS::Edge( S );
3202 BRep_Tool::Range( edge, f, l );
3203 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3204 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3205 pIt = shapePoints.begin();
3206 nIt = aSubMesh->GetNodes();
3207 for ( ; nIt->more(); pIt++ )
3209 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3210 const SMDS_EdgePosition* epos =
3211 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
3212 double u = ( epos->GetUParameter() - f ) / ( l - f );
3213 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3218 for ( ; pIt != shapePoints.end(); pIt++ )
3220 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3221 MESSAGE( "!block.ComputeParameters()" );
3222 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3226 } // loop on block sub-shapes
3230 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3233 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3234 while ( elemIt->more() ) {
3235 SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
3236 myElemPointIDs.push_back( TElemDef() );
3237 TElemDef& elemPoints = myElemPointIDs.back();
3238 while ( nIt->more() )
3239 elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
3243 myIsBoundaryPointsFound = true;
3245 return setErrorCode( ERR_OK );
3248 //=======================================================================
3249 //function : getSubmeshWithElements
3250 //purpose : return submesh containing elements bound to theBlock in theMesh
3251 //=======================================================================
3253 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3254 const TopoDS_Shape& theShape)
3256 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3257 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3260 if ( theShape.ShapeType() == TopAbs_SHELL )
3262 // look for submesh of VOLUME
3263 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3264 for (; it.More(); it.Next()) {
3265 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3266 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3274 //=======================================================================
3276 //purpose : Compute nodes coordinates applying
3277 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3278 // will be mapped into <theVertex000>. The (0,0,1)
3279 // fifth key-point will be mapped into <theVertex001>.
3280 //=======================================================================
3282 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3283 const TopoDS_Vertex& theVertex000,
3284 const TopoDS_Vertex& theVertex001)
3286 MESSAGE(" ::Apply(volume) " );
3288 if (!findBoundaryPoints() || // bind ID to points
3289 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3292 SMESH_Block block; // bind ID to shape
3293 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3294 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3296 // compute XYZ of points on shapes
3298 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3300 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3301 list< TPoint* >::iterator pIt = shapePoints.begin();
3302 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3303 switch ( S.ShapeType() )
3305 case TopAbs_VERTEX: {
3307 for ( ; pIt != shapePoints.end(); pIt++ )
3308 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3313 for ( ; pIt != shapePoints.end(); pIt++ )
3314 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3319 for ( ; pIt != shapePoints.end(); pIt++ )
3320 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3324 for ( ; pIt != shapePoints.end(); pIt++ )
3325 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3327 } // loop on block sub-shapes
3329 myIsComputed = true;
3331 return setErrorCode( ERR_OK );
3334 //=======================================================================
3336 //purpose : Compute nodes coordinates applying
3337 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3338 // will be mapped into <theNode000Index>-th node. The
3339 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3341 //=======================================================================
3343 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3344 const int theNode000Index,
3345 const int theNode001Index)
3347 //MESSAGE(" ::Apply(MeshVolume) " );
3349 if (!findBoundaryPoints()) // bind ID to points
3352 SMESH_Block block; // bind ID to shape
3353 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3354 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3355 // compute XYZ of points on shapes
3357 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3359 list< TPoint* > & shapePoints = getShapePoints( ID );
3360 list< TPoint* >::iterator pIt = shapePoints.begin();
3362 if ( block.IsVertexID( ID ))
3363 for ( ; pIt != shapePoints.end(); pIt++ ) {
3364 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3366 else if ( block.IsEdgeID( ID ))
3367 for ( ; pIt != shapePoints.end(); pIt++ ) {
3368 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3370 else if ( block.IsFaceID( ID ))
3371 for ( ; pIt != shapePoints.end(); pIt++ ) {
3372 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3375 for ( ; pIt != shapePoints.end(); pIt++ )
3376 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3377 } // loop on block sub-shapes
3379 myIsComputed = true;
3381 return setErrorCode( ERR_OK );
3384 //=======================================================================
3385 //function : mergePoints
3386 //purpose : Merge XYZ on edges and/or faces.
3387 //=======================================================================
3389 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3391 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3392 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3394 list<list< int > >& groups = idListIt->second;
3395 if ( groups.size() < 2 )
3399 const TNodeSet& nodes = idListIt->first;
3400 double tol2 = 1.e-10;
3401 if ( nodes.size() > 1 ) {
3403 TNodeSet::const_iterator n = nodes.begin();
3404 for ( ; n != nodes.end(); ++n )
3405 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3406 double x, y, z, X, Y, Z;
3407 box.Get( x, y, z, X, Y, Z );
3408 gp_Pnt p( x, y, z ), P( X, Y, Z );
3409 tol2 = 1.e-4 * p.SquareDistance( P );
3412 // to unite groups on link
3413 bool unite = ( uniteGroups && nodes.size() == 2 );
3414 map< double, int > distIndMap;
3415 const SMDS_MeshNode* node = *nodes.begin();
3416 gp_Pnt P( node->X(), node->Y(), node->Z() );
3418 // compare points, replace indices
3420 list< int >::iterator ind1, ind2;
3421 list< list< int > >::iterator grpIt1, grpIt2;
3422 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3424 list< int >& indices1 = *grpIt1;
3426 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3428 list< int >& indices2 = *grpIt2;
3429 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3431 gp_XYZ& p1 = myXYZ[ *ind1 ];
3432 ind2 = indices2.begin();
3433 while ( ind2 != indices2.end() )
3435 gp_XYZ& p2 = myXYZ[ *ind2 ];
3436 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3437 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3439 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3440 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3441 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3442 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3444 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3445 myXYZ[ *ind2 ] = undefinedXYZ();
3446 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3448 ind2 = indices2.erase( ind2 );
3455 if ( unite ) { // sort indices using distIndMap
3456 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3458 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3459 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3460 distIndMap.insert( make_pair( dist, *ind1 ));
3464 if ( unite ) { // put all sorted indices into the first group
3465 list< int >& g = groups.front();
3467 map< double, int >::iterator dist_ind = distIndMap.begin();
3468 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3469 g.push_back( dist_ind->second );
3471 } // loop on myIdsOnBoundary
3474 //=======================================================================
3475 //function : makePolyElements
3476 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3477 //=======================================================================
3479 void SMESH_Pattern::
3480 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3481 const bool toCreatePolygons,
3482 const bool toCreatePolyedrs)
3484 myPolyElemXYZIDs.clear();
3485 myPolyElems.clear();
3486 myPolyElems.reserve( myIdsOnBoundary.size() );
3488 // make a set of refined elements
3489 TIDSortedElemSet avoidSet, elemSet;
3490 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3491 for(; itv!=myElements.end(); itv++) {
3492 const SMDS_MeshElement* el = (*itv);
3493 avoidSet.insert( el );
3495 //avoidSet.insert( myElements.begin(), myElements.end() );
3497 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3499 if ( toCreatePolygons )
3501 int lastFreeId = myXYZ.size();
3503 // loop on links of refined elements
3504 indListIt = myIdsOnBoundary.begin();
3505 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3507 const TNodeSet & linkNodes = indListIt->first;
3508 if ( linkNodes.size() != 2 )
3509 continue; // skip face
3510 const SMDS_MeshNode* n1 = * linkNodes.begin();
3511 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3513 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3514 if ( idGroups.empty() || idGroups.front().empty() )
3517 // find not refined face having n1-n2 link
3521 const SMDS_MeshElement* face =
3522 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3525 avoidSet.insert ( face );
3526 myPolyElems.push_back( face );
3528 // some links of <face> are split;
3529 // make list of xyz for <face>
3530 myPolyElemXYZIDs.push_back(TElemDef());
3531 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3532 // loop on links of a <face>
3533 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3534 int i = 0, nbNodes = face->NbNodes();
3535 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3536 while ( nIt->more() )
3537 nodes[ i++ ] = smdsNode( nIt->next() );
3538 nodes[ i ] = nodes[ 0 ];
3539 for ( i = 0; i < nbNodes; ++i )
3541 // look for point mapped on a link
3542 TNodeSet faceLinkNodes;
3543 faceLinkNodes.insert( nodes[ i ] );
3544 faceLinkNodes.insert( nodes[ i + 1 ] );
3545 if ( faceLinkNodes == linkNodes )
3546 nn_IdList = indListIt;
3548 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3549 // add face point ids
3550 faceNodeIds.push_back( ++lastFreeId );
3551 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3552 if ( nn_IdList != myIdsOnBoundary.end() )
3554 // there are points mapped on a link
3555 list< int >& mappedIds = nn_IdList->second.front();
3556 if ( isReversed( nodes[ i ], mappedIds ))
3557 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3559 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3561 } // loop on links of a <face>
3567 if ( myIs2D && idGroups.size() > 1 ) {
3569 // sew new elements on 2 refined elements sharing n1-n2 link
3571 list< int >& idsOnLink = idGroups.front();
3572 // temporarily add ids of link nodes to idsOnLink
3573 bool rev = isReversed( n1, idsOnLink );
3574 for ( int i = 0; i < 2; ++i )
3577 nodeSet.insert( i ? n2 : n1 );
3578 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3579 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3580 int nodeId = groups.front().front();
3582 if ( rev ) append = !append;
3584 idsOnLink.push_back( nodeId );
3586 idsOnLink.push_front( nodeId );
3588 list< int >::iterator id = idsOnLink.begin();
3589 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3591 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3592 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3593 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3595 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3596 // look for <id> in element definition
3597 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3598 ASSERT ( idDef != pIdList->end() );
3599 // look for 2 neighbour ids of <id> in element definition
3600 for ( int prev = 0; prev < 2; ++prev ) {
3601 TElemDef::iterator idDef2 = idDef;
3603 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3605 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3606 // look for idDef2 on a link starting from id
3607 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3608 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3609 // insert ids located on link between <id> and <id2>
3610 // into the element definition between idDef and idDef2
3612 for ( ; id2 != id; --id2 )
3613 pIdList->insert( idDef, *id2 );
3615 list< int >::iterator id1 = id;
3616 for ( ++id1, ++id2; id1 != id2; ++id1 )
3617 pIdList->insert( idDef2, *id1 );
3623 // remove ids of link nodes
3624 idsOnLink.pop_front();
3625 idsOnLink.pop_back();
3627 } // loop on myIdsOnBoundary
3628 } // if ( toCreatePolygons )
3630 if ( toCreatePolyedrs )
3632 // check volumes adjacent to the refined elements
3633 SMDS_VolumeTool volTool;
3634 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3635 for ( ; refinedElem != myElements.end(); ++refinedElem )
3637 // loop on nodes of refinedElem
3638 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3639 while ( nIt->more() ) {
3640 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3641 // loop on inverse elements of node
3642 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3643 while ( eIt->more() )
3645 const SMDS_MeshElement* elem = eIt->next();
3646 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3647 continue; // skip faces or refined elements
3648 // add polyhedron definition
3649 myPolyhedronQuantities.push_back(vector<int> ());
3650 myPolyElemXYZIDs.push_back(TElemDef());
3651 vector<int>& quantity = myPolyhedronQuantities.back();
3652 TElemDef & elemDef = myPolyElemXYZIDs.back();
3653 // get definitions of new elements on volume faces
3654 bool makePoly = false;
3655 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3657 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3658 volTool.NbFaceNodes( iF ),
3659 theNodes, elemDef, quantity))
3663 myPolyElems.push_back( elem );
3665 myPolyhedronQuantities.pop_back();
3666 myPolyElemXYZIDs.pop_back();
3674 //=======================================================================
3675 //function : getFacesDefinition
3676 //purpose : return faces definition for a volume face defined by theBndNodes
3677 //=======================================================================
3679 bool SMESH_Pattern::
3680 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3681 const int theNbBndNodes,
3682 const vector< const SMDS_MeshNode* >& theNodes,
3683 list< int >& theFaceDefs,
3684 vector<int>& theQuantity)
3686 bool makePoly = false;
3687 // cout << "FROM FACE NODES: " <<endl;
3688 // for ( int i = 0; i < theNbBndNodes; ++i )
3689 // cout << theBndNodes[ i ];
3691 set< const SMDS_MeshNode* > bndNodeSet;
3692 for ( int i = 0; i < theNbBndNodes; ++i )
3693 bndNodeSet.insert( theBndNodes[ i ]);
3695 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3697 // make a set of all nodes on a face
3699 if ( !myIs2D ) { // for 2D, merge only edges
3700 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3701 if ( nn_IdList != myIdsOnBoundary.end() ) {
3703 list< int > & faceIds = nn_IdList->second.front();
3704 ids.insert( faceIds.begin(), faceIds.end() );
3707 //bool hasIdsInFace = !ids.empty();
3709 // add ids on links and bnd nodes
3710 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3711 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3712 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3714 // add id of iN-th bnd node
3716 nSet.insert( theBndNodes[ iN ] );
3717 nn_IdList = myIdsOnBoundary.find( nSet );
3718 int bndId = ++lastFreeId;
3719 if ( nn_IdList != myIdsOnBoundary.end() ) {
3720 bndId = nn_IdList->second.front().front();
3721 ids.insert( bndId );
3724 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3725 faceDef.push_back( bndId );
3726 // add ids on a link
3728 linkNodes.insert( theBndNodes[ iN ]);
3729 linkNodes.insert( theBndNodes[ iN + 1 == theNbBndNodes ? 0 : iN + 1 ]);
3730 nn_IdList = myIdsOnBoundary.find( linkNodes );
3731 if ( nn_IdList != myIdsOnBoundary.end() ) {
3733 list< int > & linkIds = nn_IdList->second.front();
3734 ids.insert( linkIds.begin(), linkIds.end() );
3735 if ( isReversed( theBndNodes[ iN ], linkIds ))
3736 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3738 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3742 // find faces definition of new volumes
3744 bool defsAdded = false;
3745 if ( !myIs2D ) { // for 2D, merge only edges
3746 SMDS_VolumeTool vol;
3747 set< TElemDef* > checkedVolDefs;
3748 set< int >::iterator id = ids.begin();
3749 for ( ; id != ids.end(); ++id )
3751 // definitions of volumes sharing id
3752 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3753 ASSERT( !defList.empty() );
3754 // loop on volume definitions
3755 list< TElemDef* >::iterator pIdList = defList.begin();
3756 for ( ; pIdList != defList.end(); ++pIdList)
3758 if ( !checkedVolDefs.insert( *pIdList ).second )
3759 continue; // skip already checked volume definition
3760 vector< int > idVec;
3761 idVec.reserve( (*pIdList)->size() );
3762 idVec.insert( idVec.begin(), (*pIdList)->begin(), (*pIdList)->end() );
3763 // loop on face defs of a volume
3764 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3765 if ( volType == SMDS_VolumeTool::UNKNOWN )
3767 int nbFaces = vol.NbFaces( volType );
3768 for ( int iF = 0; iF < nbFaces; ++iF )
3770 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3771 int iN, nbN = vol.NbFaceNodes( volType, iF );
3772 // check if all nodes of a faces are in <ids>
3774 for ( iN = 0; iN < nbN && all; ++iN ) {
3775 int nodeId = idVec[ nodeInds[ iN ]];
3776 all = ( ids.find( nodeId ) != ids.end() );
3779 // store a face definition
3780 for ( iN = 0; iN < nbN; ++iN ) {
3781 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3783 theQuantity.push_back( nbN );
3791 theQuantity.push_back( faceDef.size() );
3792 theFaceDefs.splice( theFaceDefs.end(), faceDef, faceDef.begin(), faceDef.end() );
3798 //=======================================================================
3799 //function : clearSubMesh
3801 //=======================================================================
3803 static bool clearSubMesh( SMESH_Mesh* theMesh,
3804 const TopoDS_Shape& theShape)
3806 bool removed = false;
3807 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3809 removed = !aSubMesh->IsEmpty();
3811 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3814 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3815 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3817 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3818 removed = eIt->more();
3819 while ( eIt->more() )
3820 aMeshDS->RemoveElement( eIt->next() );
3821 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3822 removed = removed || nIt->more();
3823 while ( nIt->more() )
3824 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3830 //=======================================================================
3831 //function : clearMesh
3832 //purpose : clear mesh elements existing on myShape in theMesh
3833 //=======================================================================
3835 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3838 if ( !myShape.IsNull() )
3840 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3841 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3842 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3844 clearSubMesh( theMesh, it.Value() );
3850 //=======================================================================
3851 //function : MakeMesh
3852 //purpose : Create nodes and elements in <theMesh> using nodes
3853 // coordinates computed by either of Apply...() methods
3854 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3855 // it does not care of nodes and elements already existing on
3856 // subshapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3857 //=======================================================================
3859 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3860 const bool toCreatePolygons,
3861 const bool toCreatePolyedrs)
3863 MESSAGE(" ::MakeMesh() " );
3864 if ( !myIsComputed )
3865 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3867 mergePoints( toCreatePolygons );
3869 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3871 // clear elements and nodes existing on myShape
3874 bool onMeshElements = ( !myElements.empty() );
3876 // Create missing nodes
3878 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3879 if ( onMeshElements )
3881 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3882 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3883 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3884 nodesVector[ i_node->first ] = i_node->second;
3886 for ( int i = 0; i < myXYZ.size(); ++i ) {
3887 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3888 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3895 nodesVector.resize( myPoints.size(), 0 );
3897 // to find point index
3898 map< TPoint*, int > pointIndex;
3899 for ( int i = 0; i < myPoints.size(); i++ )
3900 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3902 // loop on sub-shapes of myShape: create nodes
3903 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3904 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3907 //SMESHDS_SubMesh * subMeshDS = 0;
3908 if ( !myShapeIDMap.IsEmpty() ) {
3909 S = myShapeIDMap( idPointIt->first );
3910 //subMeshDS = aMeshDS->MeshElements( S );
3912 list< TPoint* > & points = idPointIt->second;
3913 list< TPoint* >::iterator pIt = points.begin();
3914 for ( ; pIt != points.end(); pIt++ )
3916 TPoint* point = *pIt;
3917 int pIndex = pointIndex[ point ];
3918 if ( nodesVector [ pIndex ] )
3920 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3923 nodesVector [ pIndex ] = node;
3925 if ( true /*subMeshDS*/ ) {
3926 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3927 switch ( S.ShapeType() ) {
3928 case TopAbs_VERTEX: {
3929 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3932 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3935 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3936 point->myUV.X(), point->myUV.Y() ); break;
3939 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3948 if ( onMeshElements )
3950 // prepare data to create poly elements
3951 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3954 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3955 // sew old and new elements
3956 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3960 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3963 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3964 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3965 // for ( ; i_sm != sm.end(); i_sm++ )
3967 // cout << " SM " << i_sm->first << " ";
3968 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
3969 // //SMDS_ElemIteratorPtr GetElements();
3970 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
3971 // while ( nit->more() )
3972 // cout << nit->next()->GetID() << " ";
3975 return setErrorCode( ERR_OK );
3978 //=======================================================================
3979 //function : createElements
3980 //purpose : add elements to the mesh
3981 //=======================================================================
3983 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
3984 const vector<const SMDS_MeshNode* >& theNodesVector,
3985 const list< TElemDef > & theElemNodeIDs,
3986 const vector<const SMDS_MeshElement*>& theElements)
3988 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3989 SMESH_MeshEditor editor( theMesh );
3991 bool onMeshElements = !theElements.empty();
3993 // shapes and groups theElements are on
3994 vector< int > shapeIDs;
3995 vector< list< SMESHDS_Group* > > groups;
3996 set< const SMDS_MeshNode* > shellNodes;
3997 if ( onMeshElements )
3999 shapeIDs.resize( theElements.size() );
4000 groups.resize( theElements.size() );
4001 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4002 set<SMESHDS_GroupBase*>::const_iterator grIt;
4003 for ( int i = 0; i < theElements.size(); i++ )
4005 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4006 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4007 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4008 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4009 groups[ i ].push_back( group );
4012 // get all nodes bound to shells because their SpacePosition is not set
4013 // by SMESHDS_Mesh::SetNodeInVolume()
4014 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4015 if ( !aMainShape.IsNull() ) {
4016 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4017 for ( ; shellExp.More(); shellExp.Next() )
4019 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4021 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4022 while ( nIt->more() )
4023 shellNodes.insert( nIt->next() );
4028 // nb new elements per a refined element
4029 int nbNewElemsPerOld = 1;
4030 if ( onMeshElements )
4031 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4035 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4036 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4037 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4039 const TElemDef & elemNodeInd = *enIt;
4041 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4042 TElemDef::const_iterator id = elemNodeInd.begin();
4044 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4045 if ( *id < theNodesVector.size() )
4046 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4048 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4050 // dim of refined elem
4051 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4052 if ( onMeshElements ) {
4053 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4056 const SMDS_MeshElement* elem = 0;
4058 switch ( nbNodes ) {
4060 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4062 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4064 if ( !onMeshElements ) {// create a quadratic face
4065 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4066 nodes[4], nodes[5] ); break;
4067 } // else do not break but create a polygon
4069 if ( !onMeshElements ) {// create a quadratic face
4070 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4071 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4072 } // else do not break but create a polygon
4074 elem = aMeshDS->AddPolygonalFace( nodes );
4078 switch ( nbNodes ) {
4080 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4082 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4085 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4086 nodes[4], nodes[5] ); break;
4088 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4089 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4091 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4094 // set element on a shape
4095 if ( elem && onMeshElements ) // applied to mesh elements
4097 int shapeID = shapeIDs[ elemIndex ];
4098 if ( shapeID > 0 ) {
4099 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4100 // set nodes on a shape
4101 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4102 if ( S.ShapeType() == TopAbs_SOLID ) {
4103 TopoDS_Iterator shellIt( S );
4104 if ( shellIt.More() )
4105 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4107 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4108 while ( noIt->more() ) {
4109 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4110 if (!node->GetPosition()->GetShapeId() &&
4111 shellNodes.find( node ) == shellNodes.end() ) {
4112 if ( S.ShapeType() == TopAbs_FACE )
4113 aMeshDS->SetNodeOnFace( node, shapeID );
4115 aMeshDS->SetNodeInVolume( node, shapeID );
4116 shellNodes.insert( node );
4121 // add elem in groups
4122 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4123 for ( ; g != groups[ elemIndex ].end(); ++g )
4124 (*g)->SMDSGroup().Add( elem );
4126 if ( elem && !myShape.IsNull() ) // applied to shape
4127 aMeshDS->SetMeshElementOnShape( elem, myShape );
4130 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4131 // so that operations with hypotheses will erase the mesh being built
4133 SMESH_subMesh * subMesh;
4134 if ( !myShape.IsNull() ) {
4135 subMesh = theMesh->GetSubMesh( myShape );
4137 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4139 if ( onMeshElements ) {
4140 list< int > elemIDs;
4141 for ( int i = 0; i < theElements.size(); i++ )
4143 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4145 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4147 elemIDs.push_back( theElements[ i ]->GetID() );
4149 // remove refined elements
4150 editor.Remove( elemIDs, false );
4154 //=======================================================================
4155 //function : isReversed
4156 //purpose : check xyz ids order in theIdsList taking into account
4157 // theFirstNode on a link
4158 //=======================================================================
4160 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4161 const list< int >& theIdsList) const
4163 if ( theIdsList.size() < 2 )
4166 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4168 list<int>::const_iterator id = theIdsList.begin();
4169 for ( int i = 0; i < 2; ++i, ++id ) {
4170 if ( *id < myXYZ.size() )
4171 P[ i ] = myXYZ[ *id ];
4173 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4174 i_n = myXYZIdToNodeMap.find( *id );
4175 ASSERT( i_n != myXYZIdToNodeMap.end() );
4176 const SMDS_MeshNode* n = i_n->second;
4177 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4180 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4184 //=======================================================================
4185 //function : arrangeBoundaries
4186 //purpose : if there are several wires, arrange boundaryPoints so that
4187 // the outer wire goes first and fix inner wires orientation
4188 // update myKeyPointIDs to correspond to the order of key-points
4189 // in boundaries; sort internal boundaries by the nb of key-points
4190 //=======================================================================
4192 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4194 typedef list< list< TPoint* > >::iterator TListOfListIt;
4195 TListOfListIt bndIt;
4196 list< TPoint* >::iterator pIt;
4198 int nbBoundaries = boundaryList.size();
4199 if ( nbBoundaries > 1 )
4201 // sort boundaries by nb of key-points
4202 if ( nbBoundaries > 2 )
4204 // move boundaries in tmp list
4205 list< list< TPoint* > > tmpList;
4206 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4207 // make a map nb-key-points to boundary-position-in-tmpList,
4208 // boundary-positions get ordered in it
4209 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4210 TNbKpBndPosMap nbKpBndPosMap;
4211 bndIt = tmpList.begin();
4212 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4213 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4214 int nb = *nbKpIt * nbBoundaries;
4215 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4217 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4219 // move boundaries back to boundaryList
4220 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4221 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4222 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4223 TListOfListIt bndPos1 = bndPos2++;
4224 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4228 // Look for the outer boundary: the one with the point with the least X
4229 double leastX = DBL_MAX;
4230 TListOfListIt outerBndPos;
4231 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4233 list< TPoint* >& boundary = (*bndIt);
4234 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4236 TPoint* point = *pIt;
4237 if ( point->myInitXYZ.X() < leastX ) {
4238 leastX = point->myInitXYZ.X();
4239 outerBndPos = bndIt;
4244 if ( outerBndPos != boundaryList.begin() )
4245 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4247 } // if nbBoundaries > 1
4249 // Check boundaries orientation and re-fill myKeyPointIDs
4251 set< TPoint* > keyPointSet;
4252 list< int >::iterator kpIt = myKeyPointIDs.begin();
4253 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4254 keyPointSet.insert( & myPoints[ *kpIt ]);
4255 myKeyPointIDs.clear();
4257 // update myNbKeyPntInBoundary also
4258 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4260 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4262 // find the point with the least X
4263 double leastX = DBL_MAX;
4264 list< TPoint* >::iterator xpIt;
4265 list< TPoint* >& boundary = (*bndIt);
4266 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4268 TPoint* point = *pIt;
4269 if ( point->myInitXYZ.X() < leastX ) {
4270 leastX = point->myInitXYZ.X();
4274 // find points next to the point with the least X
4275 TPoint* p = *xpIt, *pPrev, *pNext;
4276 if ( p == boundary.front() )
4277 pPrev = *(++boundary.rbegin());
4283 if ( p == boundary.back() )
4284 pNext = *(++boundary.begin());
4289 // vectors of boundary direction near <p>
4290 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4291 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4292 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4293 double yPrev = v1.Y() / sqrt( sqMag1 );
4294 double yNext = v2.Y() / sqrt( sqMag2 );
4295 double sumY = yPrev + yNext;
4297 if ( bndIt == boundaryList.begin() ) // outer boundary
4305 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4306 (*nbKpIt) = 0; // count nb of key-points again
4307 pIt = boundary.begin();
4308 for ( ; pIt != boundary.end(); pIt++)
4310 TPoint* point = *pIt;
4311 if ( keyPointSet.find( point ) == keyPointSet.end() )
4313 // find an index of a keypoint
4315 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4316 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4317 if ( &(*pVecIt) == point )
4319 myKeyPointIDs.push_back( index );
4322 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4325 } // loop on a list of boundaries
4327 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4330 //=======================================================================
4331 //function : findBoundaryPoints
4332 //purpose : if loaded from file, find points to map on edges and faces and
4333 // compute their parameters
4334 //=======================================================================
4336 bool SMESH_Pattern::findBoundaryPoints()
4338 if ( myIsBoundaryPointsFound ) return true;
4340 MESSAGE(" findBoundaryPoints() ");
4342 myNbKeyPntInBoundary.clear();
4346 set< TPoint* > pointsInElems;
4348 // Find free links of elements:
4349 // put links of all elements in a set and remove links encountered twice
4351 typedef pair< TPoint*, TPoint*> TLink;
4352 set< TLink > linkSet;
4353 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4354 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4356 TElemDef & elemPoints = *epIt;
4357 TElemDef::iterator pIt = elemPoints.begin();
4358 int prevP = elemPoints.back();
4359 for ( ; pIt != elemPoints.end(); pIt++ ) {
4360 TPoint* p1 = & myPoints[ prevP ];
4361 TPoint* p2 = & myPoints[ *pIt ];
4362 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4363 ASSERT( link.first != link.second );
4364 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4365 if ( !itUniq.second )
4366 linkSet.erase( itUniq.first );
4369 pointsInElems.insert( p1 );
4372 // Now linkSet contains only free links,
4373 // find the points order that they have in boundaries
4375 // 1. make a map of key-points
4376 set< TPoint* > keyPointSet;
4377 list< int >::iterator kpIt = myKeyPointIDs.begin();
4378 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4379 keyPointSet.insert( & myPoints[ *kpIt ]);
4381 // 2. chain up boundary points
4382 list< list< TPoint* > > boundaryList;
4383 boundaryList.push_back( list< TPoint* >() );
4384 list< TPoint* > * boundary = & boundaryList.back();
4386 TPoint *point1, *point2, *keypoint1;
4387 kpIt = myKeyPointIDs.begin();
4388 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4389 // loop on free links: look for the next point
4391 set< TLink >::iterator lIt = linkSet.begin();
4392 while ( lIt != linkSet.end() )
4394 if ( (*lIt).first == point1 )
4395 point2 = (*lIt).second;
4396 else if ( (*lIt).second == point1 )
4397 point2 = (*lIt).first;
4402 linkSet.erase( lIt );
4403 lIt = linkSet.begin();
4405 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4407 boundary->push_back( point2 );
4409 else // a key-point found
4411 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4413 if ( point2 != keypoint1 ) // its not the boundary end
4415 boundary->push_back( point2 );
4417 else // the boundary end reached
4419 boundary->push_front( keypoint1 );
4420 boundary->push_back( keypoint1 );
4421 myNbKeyPntInBoundary.push_back( iKeyPoint );
4422 if ( keyPointSet.empty() )
4423 break; // all boundaries containing key-points are found
4425 // prepare to search for the next boundary
4426 boundaryList.push_back( list< TPoint* >() );
4427 boundary = & boundaryList.back();
4428 point2 = keypoint1 = (*keyPointSet.begin());
4432 } // loop on the free links set
4434 if ( boundary->empty() ) {
4435 MESSAGE(" a separate key-point");
4436 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4439 // if there are several wires, arrange boundaryPoints so that
4440 // the outer wire goes first and fix inner wires orientation;
4441 // sort myKeyPointIDs to correspond to the order of key-points
4443 arrangeBoundaries( boundaryList );
4445 // Find correspondence shape ID - points,
4446 // compute points parameter on edge
4448 keyPointSet.clear();
4449 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4450 keyPointSet.insert( & myPoints[ *kpIt ]);
4452 set< TPoint* > edgePointSet; // to find in-face points
4453 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4454 int edgeID = myKeyPointIDs.size() + 1;
4456 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4457 for ( ; bndIt != boundaryList.end(); bndIt++ )
4459 boundary = & (*bndIt);
4460 double edgeLength = 0;
4461 list< TPoint* >::iterator pIt = boundary->begin();
4462 getShapePoints( edgeID ).push_back( *pIt );
4463 getShapePoints( vertexID++ ).push_back( *pIt );
4464 for ( pIt++; pIt != boundary->end(); pIt++)
4466 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4467 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4468 TPoint* point = *pIt;
4469 edgePointSet.insert( point );
4470 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4472 edgePoints.push_back( point );
4473 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4474 point->myInitU = edgeLength;
4478 // treat points on the edge which ends up: compute U [0,1]
4479 edgePoints.push_back( point );
4480 if ( edgePoints.size() > 2 ) {
4481 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4482 list< TPoint* >::iterator epIt = edgePoints.begin();
4483 for ( ; epIt != edgePoints.end(); epIt++ )
4484 (*epIt)->myInitU /= edgeLength;
4486 // begin the next edge treatment
4489 if ( point != boundary->front() ) { // not the first key-point again
4490 getShapePoints( edgeID ).push_back( point );
4491 getShapePoints( vertexID++ ).push_back( point );
4497 // find in-face points
4498 list< TPoint* > & facePoints = getShapePoints( edgeID );
4499 vector< TPoint >::iterator pVecIt = myPoints.begin();
4500 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4501 TPoint* point = &(*pVecIt);
4502 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4503 pointsInElems.find( point ) != pointsInElems.end())
4504 facePoints.push_back( point );
4511 // bind points to shapes according to point parameters
4512 vector< TPoint >::iterator pVecIt = myPoints.begin();
4513 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4514 TPoint* point = &(*pVecIt);
4515 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4516 getShapePoints( shapeID ).push_back( point );
4517 // detect key-points
4518 if ( SMESH_Block::IsVertexID( shapeID ))
4519 myKeyPointIDs.push_back( i );
4523 myIsBoundaryPointsFound = true;
4524 return myIsBoundaryPointsFound;
4527 //=======================================================================
4529 //purpose : clear fields
4530 //=======================================================================
4532 void SMESH_Pattern::Clear()
4534 myIsComputed = myIsBoundaryPointsFound = false;
4537 myKeyPointIDs.clear();
4538 myElemPointIDs.clear();
4539 myShapeIDToPointsMap.clear();
4540 myShapeIDMap.Clear();
4542 myNbKeyPntInBoundary.clear();
4545 //=======================================================================
4546 //function : setShapeToMesh
4547 //purpose : set a shape to be meshed. Return True if meshing is possible
4548 //=======================================================================
4550 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4552 if ( !IsLoaded() ) {
4553 MESSAGE( "Pattern not loaded" );
4554 return setErrorCode( ERR_APPL_NOT_LOADED );
4557 TopAbs_ShapeEnum aType = theShape.ShapeType();
4558 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4560 MESSAGE( "Pattern dimention mismatch" );
4561 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4564 // check if a face is closed
4565 int nbNodeOnSeamEdge = 0;
4567 TopTools_MapOfShape seamVertices;
4568 TopoDS_Face face = TopoDS::Face( theShape );
4569 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4570 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4571 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4572 if ( BRep_Tool::IsClosed(ee, face) ) {
4573 // seam edge and vertices encounter twice in theFace
4574 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4575 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4580 // check nb of vertices
4581 TopTools_IndexedMapOfShape vMap;
4582 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4583 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4584 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4585 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4588 myElements.clear(); // not refine elements
4589 myElemXYZIDs.clear();
4591 myShapeIDMap.Clear();
4596 //=======================================================================
4597 //function : GetMappedPoints
4598 //purpose : Return nodes coordinates computed by Apply() method
4599 //=======================================================================
4601 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4604 if ( !myIsComputed )
4607 if ( myElements.empty() ) { // applied to shape
4608 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4609 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4610 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4612 else { // applied to mesh elements
4613 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4614 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4615 for ( ; xyz != myXYZ.end(); ++xyz )
4616 if ( !isDefined( *xyz ))
4617 thePoints.push_back( definedXYZ );
4619 thePoints.push_back( & (*xyz) );
4621 return !thePoints.empty();
4625 //=======================================================================
4626 //function : GetPoints
4627 //purpose : Return nodes coordinates of the pattern
4628 //=======================================================================
4630 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4637 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4638 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4639 thePoints.push_back( & (*pVecIt).myInitXYZ );
4641 return ( thePoints.size() > 0 );
4644 //=======================================================================
4645 //function : getShapePoints
4646 //purpose : return list of points located on theShape
4647 //=======================================================================
4649 list< SMESH_Pattern::TPoint* > &
4650 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4653 if ( !myShapeIDMap.Contains( theShape ))
4654 aShapeID = myShapeIDMap.Add( theShape );
4656 aShapeID = myShapeIDMap.FindIndex( theShape );
4658 return myShapeIDToPointsMap[ aShapeID ];
4661 //=======================================================================
4662 //function : getShapePoints
4663 //purpose : return list of points located on the shape
4664 //=======================================================================
4666 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4668 return myShapeIDToPointsMap[ theShapeID ];
4671 //=======================================================================
4672 //function : DumpPoints
4674 //=======================================================================
4676 void SMESH_Pattern::DumpPoints() const
4679 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4680 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4681 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4685 //=======================================================================
4686 //function : TPoint()
4688 //=======================================================================
4690 SMESH_Pattern::TPoint::TPoint()
4693 myInitXYZ.SetCoord(0,0,0);
4694 myInitUV.SetCoord(0.,0.);
4696 myXYZ.SetCoord(0,0,0);
4697 myUV.SetCoord(0.,0.);
4702 //=======================================================================
4703 //function : operator <<
4705 //=======================================================================
4707 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4709 gp_XYZ xyz = p.myInitXYZ;
4710 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4711 gp_XY xy = p.myInitUV;
4712 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4713 double u = p.myInitU;
4714 OS << " u( " << u << " )) " << &p << endl;
4715 xyz = p.myXYZ.XYZ();
4716 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4718 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4720 OS << " u( " << u << " ))" << endl;