1 // Copyright (C) 2003 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License.
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // Lesser General Public License for more details.
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : SMESH_Pattern.hxx
21 // Created : Mon Aug 2 10:30:00 2004
22 // Author : Edward AGAPOV (eap)
24 #include "SMESH_Pattern.hxx"
26 #include <BRepAdaptor_Curve.hxx>
27 #include <BRepTools.hxx>
28 #include <BRepTools_WireExplorer.hxx>
29 #include <BRep_Tool.hxx>
30 #include <Bnd_Box.hxx>
31 #include <Bnd_Box2d.hxx>
33 #include <Extrema_GenExtPS.hxx>
34 #include <Extrema_POnSurf.hxx>
35 #include <Geom2d_Curve.hxx>
36 #include <GeomAdaptor_Surface.hxx>
37 #include <Geom_Curve.hxx>
38 #include <Geom_Surface.hxx>
39 #include <IntAna2d_AnaIntersection.hxx>
40 #include <TopAbs_ShapeEnum.hxx>
42 #include <TopLoc_Location.hxx>
44 #include <TopoDS_Edge.hxx>
45 #include <TopoDS_Face.hxx>
46 #include <TopoDS_Iterator.hxx>
47 #include <TopoDS_Shell.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
50 #include <TopTools_ListIteratorOfListOfShape.hxx>
52 #include <gp_Lin2d.hxx>
53 #include <gp_Pnt2d.hxx>
54 #include <gp_Trsf.hxx>
58 #include "SMDS_EdgePosition.hxx"
59 #include "SMDS_FacePosition.hxx"
60 #include "SMDS_MeshElement.hxx"
61 #include "SMDS_MeshFace.hxx"
62 #include "SMDS_MeshNode.hxx"
63 #include "SMDS_VolumeTool.hxx"
64 #include "SMESHDS_Group.hxx"
65 #include "SMESHDS_Mesh.hxx"
66 #include "SMESHDS_SubMesh.hxx"
67 #include "SMESH_Block.hxx"
68 #include "SMESH_Mesh.hxx"
69 #include "SMESH_MeshEditor.hxx"
70 #include "SMESH_subMesh.hxx"
72 #include "utilities.h"
76 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
78 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
80 //=======================================================================
81 //function : SMESH_Pattern
83 //=======================================================================
85 SMESH_Pattern::SMESH_Pattern ()
88 //=======================================================================
91 //=======================================================================
93 static inline int getInt( const char * theSring )
95 if ( *theSring < '0' || *theSring > '9' )
99 int val = strtol( theSring, &ptr, 10 );
100 if ( ptr == theSring ||
101 // there must not be neither '.' nor ',' nor 'E' ...
102 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
108 //=======================================================================
109 //function : getDouble
111 //=======================================================================
113 static inline double getDouble( const char * theSring )
116 return strtod( theSring, &ptr );
119 //=======================================================================
120 //function : readLine
121 //purpose : Put token starting positions in theFields until '\n' or '\0'
122 // Return the number of the found tokens
123 //=======================================================================
125 static int readLine (list <const char*> & theFields,
126 const char* & theLineBeg,
127 const bool theClearFields )
129 if ( theClearFields )
134 /* switch ( symbol ) { */
135 /* case white-space: */
136 /* look for a non-space symbol; */
137 /* case string-end: */
140 /* case comment beginning: */
141 /* skip all till a line-end; */
143 /* put its position in theFields, skip till a white-space;*/
149 bool stopReading = false;
152 bool isNumber = false;
153 switch ( *theLineBeg )
155 case ' ': // white space
160 case '\n': // a line ends
161 stopReading = ( nbRead > 0 );
166 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
170 case '\0': // file ends
173 case '-': // real number
178 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
180 theFields.push_back( theLineBeg );
183 while (*theLineBeg != ' ' &&
184 *theLineBeg != '\n' &&
185 *theLineBeg != '\0');
189 return 0; // incorrect file format
195 } while ( !stopReading );
200 //=======================================================================
202 //purpose : Load a pattern from <theFile>
203 //=======================================================================
205 bool SMESH_Pattern::Load (const char* theFileContents)
207 MESSAGE("Load( file ) ");
211 // ! This is a comment
212 // NB_POINTS ! 1 integer - the number of points in the pattern.
213 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
214 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
216 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
217 // ! elements description goes after all
218 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
223 const char* lineBeg = theFileContents;
224 list <const char*> fields;
225 const bool clearFields = true;
227 // NB_POINTS ! 1 integer - the number of points in the pattern.
229 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
230 MESSAGE("Error reading NB_POINTS");
231 return setErrorCode( ERR_READ_NB_POINTS );
233 int nbPoints = getInt( fields.front() );
235 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
237 // read the first point coordinates to define pattern dimention
238 int dim = readLine( fields, lineBeg, clearFields );
244 MESSAGE("Error reading points: wrong nb of coordinates");
245 return setErrorCode( ERR_READ_POINT_COORDS );
247 if ( nbPoints <= dim ) {
248 MESSAGE(" Too few points ");
249 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
252 // read the rest points
254 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
255 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
256 MESSAGE("Error reading points : wrong nb of coordinates ");
257 return setErrorCode( ERR_READ_POINT_COORDS );
259 // store point coordinates
260 myPoints.resize( nbPoints );
261 list <const char*>::iterator fIt = fields.begin();
262 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
264 TPoint & p = myPoints[ iPoint ];
265 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
267 double coord = getDouble( *fIt );
268 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
269 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
271 return setErrorCode( ERR_READ_3D_COORD );
273 p.myInitXYZ.SetCoord( iCoord, coord );
275 p.myInitUV.SetCoord( iCoord, coord );
279 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
282 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
283 MESSAGE("Error: missing key-points");
285 return setErrorCode( ERR_READ_NO_KEYPOINT );
288 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
290 int pointIndex = getInt( *fIt );
291 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
292 MESSAGE("Error: invalid point index " << pointIndex );
294 return setErrorCode( ERR_READ_BAD_INDEX );
296 if ( idSet.insert( pointIndex ).second ) // unique?
297 myKeyPointIDs.push_back( pointIndex );
301 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
303 while ( readLine( fields, lineBeg, clearFields ))
305 myElemPointIDs.push_back( TElemDef() );
306 TElemDef& elemPoints = myElemPointIDs.back();
307 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
309 int pointIndex = getInt( *fIt );
310 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
311 MESSAGE("Error: invalid point index " << pointIndex );
313 return setErrorCode( ERR_READ_BAD_INDEX );
315 elemPoints.push_back( pointIndex );
317 // check the nb of nodes in element
319 switch ( elemPoints.size() ) {
320 case 3: if ( !myIs2D ) Ok = false; break;
324 case 8: if ( myIs2D ) Ok = false; break;
328 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
330 return setErrorCode( ERR_READ_ELEM_POINTS );
333 if ( myElemPointIDs.empty() ) {
334 MESSAGE("Error: no elements");
336 return setErrorCode( ERR_READ_NO_ELEMS );
339 findBoundaryPoints(); // sort key-points
341 return setErrorCode( ERR_OK );
344 //=======================================================================
346 //purpose : Save the loaded pattern into the file <theFileName>
347 //=======================================================================
349 bool SMESH_Pattern::Save (ostream& theFile)
351 MESSAGE(" ::Save(file) " );
353 MESSAGE(" Pattern not loaded ");
354 return setErrorCode( ERR_SAVE_NOT_LOADED );
357 theFile << "!!! SALOME Mesh Pattern file" << endl;
358 theFile << "!!!" << endl;
359 theFile << "!!! Nb of points:" << endl;
360 theFile << myPoints.size() << endl;
364 // theFile.width( 8 );
365 // theFile.setf(ios::fixed);// use 123.45 floating notation
366 // theFile.setf(ios::right);
367 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
368 // theFile.setf(ios::showpoint); // do not show trailing zeros
369 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
370 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
371 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
372 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
373 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
374 theFile << " !- " << i << endl; // point id to ease reading by a human being
378 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
379 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
380 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
381 theFile << " " << *kpIt;
382 if ( !myKeyPointIDs.empty() )
386 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
387 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
388 for ( ; epIt != myElemPointIDs.end(); epIt++ )
390 const TElemDef & elemPoints = *epIt;
391 TElemDef::const_iterator iIt = elemPoints.begin();
392 for ( ; iIt != elemPoints.end(); iIt++ )
393 theFile << " " << *iIt;
399 return setErrorCode( ERR_OK );
402 //=======================================================================
403 //function : sortBySize
404 //purpose : sort theListOfList by size
405 //=======================================================================
407 template<typename T> struct TSizeCmp {
408 bool operator ()( const list < T > & l1, const list < T > & l2 )
409 const { return l1.size() < l2.size(); }
412 template<typename T> void sortBySize( list< list < T > > & theListOfList )
414 if ( theListOfList.size() > 2 ) {
415 TSizeCmp< T > SizeCmp;
416 theListOfList.sort( SizeCmp );
420 //=======================================================================
423 //=======================================================================
425 static gp_XY project (const SMDS_MeshNode* theNode,
426 Extrema_GenExtPS & theProjectorPS)
428 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
429 theProjectorPS.Perform( P );
430 if ( !theProjectorPS.IsDone() ) {
431 MESSAGE( "SMESH_Pattern: point projection FAILED");
434 double u, v, minVal = DBL_MAX;
435 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
436 if ( theProjectorPS.Value( i ) < minVal ) {
437 minVal = theProjectorPS.Value( i );
438 theProjectorPS.Point( i ).Parameter( u, v );
440 return gp_XY( u, v );
443 //=======================================================================
444 //function : areNodesBound
445 //purpose : true if all nodes of faces are bound to shapes
446 //=======================================================================
448 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
450 while ( faceItr->more() )
452 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
453 while ( nIt->more() )
455 const SMDS_MeshNode* node = smdsNode( nIt->next() );
456 SMDS_PositionPtr pos = node->GetPosition();
457 if ( !pos || !pos->GetShapeId() ) {
465 //=======================================================================
466 //function : isMeshBoundToShape
467 //purpose : return true if all 2d elements are bound to shape
468 // if aFaceSubmesh != NULL, then check faces bound to it
469 // else check all faces in aMeshDS
470 //=======================================================================
472 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
473 SMESHDS_SubMesh * aFaceSubmesh,
474 const bool isMainShape)
477 // check that all faces are bound to aFaceSubmesh
478 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
482 // check face nodes binding
483 if ( aFaceSubmesh ) {
484 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
485 return areNodesBound( fIt );
487 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
488 return areNodesBound( fIt );
491 //=======================================================================
493 //purpose : Create a pattern from the mesh built on <theFace>.
494 // <theProject>==true makes override nodes positions
495 // on <theFace> computed by mesher
496 //=======================================================================
498 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
499 const TopoDS_Face& theFace,
502 MESSAGE(" ::Load(face) " );
506 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
507 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
508 SMESH_MesherHelper helper( *theMesh );
509 helper.SetSubShape( theFace );
511 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
512 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
513 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
515 MESSAGE( "No elements bound to the face");
516 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
519 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
521 // check that face is not closed
522 bool isClosed = helper.HasSeam();
524 list<TopoDS_Edge> eList;
525 list<TopoDS_Edge>::iterator elIt;
526 SMESH_Block::GetOrderedEdges( face, bidon, eList, myNbKeyPntInBoundary );
528 // check that requested or needed projection is possible
529 bool isMainShape = theMesh->IsMainShape( face );
530 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
531 bool canProject = ( nbElems ? true : isMainShape );
533 canProject = false; // so far
535 if ( ( theProject || needProject ) && !canProject )
536 return setErrorCode( ERR_LOADF_CANT_PROJECT );
538 Extrema_GenExtPS projector;
539 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
540 if ( theProject || needProject )
541 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
544 TNodePointIDMap nodePointIDMap;
545 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
549 MESSAGE("Project the submesh");
550 // ---------------------------------------------------------------
551 // The case where the submesh is projected to theFace
552 // ---------------------------------------------------------------
555 list< const SMDS_MeshElement* > faces;
557 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
558 while ( fIt->more() ) {
559 const SMDS_MeshElement* f = fIt->next();
560 if ( f && f->GetType() == SMDSAbs_Face )
561 faces.push_back( f );
565 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
566 while ( fIt->more() )
567 faces.push_back( fIt->next() );
570 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
571 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
572 for ( ; fIt != faces.end(); ++fIt )
574 myElemPointIDs.push_back( TElemDef() );
575 TElemDef& elemPoints = myElemPointIDs.back();
576 SMDS_ElemIteratorPtr nIt = (*fIt)->nodesIterator();
577 while ( nIt->more() )
579 const SMDS_MeshElement* node = nIt->next();
580 TNodePointIDMap::iterator nIdIt = nodePointIDMap.find( node );
581 if ( nIdIt == nodePointIDMap.end() )
583 elemPoints.push_back( iPoint );
584 nodePointIDMap.insert( make_pair( node, iPoint++ ));
587 elemPoints.push_back( (*nIdIt).second );
590 myPoints.resize( iPoint );
592 // project all nodes of 2d elements to theFace
593 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
594 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
596 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
597 TPoint * p = & myPoints[ (*nIdIt).second ];
598 p->myInitUV = project( node, projector );
599 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
601 // find key-points: the points most close to UV of vertices
602 TopExp_Explorer vExp( face, TopAbs_VERTEX );
603 set<int> foundIndices;
604 for ( ; vExp.More(); vExp.Next() ) {
605 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
606 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
607 double minDist = DBL_MAX;
609 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
610 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
611 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
612 if ( dist < minDist ) {
617 if ( foundIndices.insert( index ).second ) // unique?
618 myKeyPointIDs.push_back( index );
620 myIsBoundaryPointsFound = false;
625 // ---------------------------------------------------------------------
626 // The case where a pattern is being made from the mesh built by mesher
627 // ---------------------------------------------------------------------
629 // Load shapes in the consequent order and count nb of points
632 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
633 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
634 if ( BRep_Tool::IsClosed( *elIt, theFace ) )
635 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));
636 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt );
638 nbNodes += eSubMesh->NbNodes() + 1;
641 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
642 myShapeIDMap.Add( *elIt );
644 myShapeIDMap.Add( face );
646 myPoints.resize( nbNodes );
648 // Load U of points on edges
650 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
652 TopoDS_Edge & edge = *elIt;
653 list< TPoint* > & ePoints = getShapePoints( edge );
655 Handle(Geom2d_Curve) C2d;
657 C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
658 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
660 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
661 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
662 // to make adjacent edges share key-point, we make v2 FORWARD too
663 // (as we have different points for same shape with different orienation)
666 // on closed face we must have REVERSED some of seam vertices
667 bool isSeam = helper.IsSeamShape( edge );
669 if ( isSeam ) { // reverse on reversed SEAM edge
675 else { // on CLOSED edge
676 for ( int is2 = 0; is2 < 2; ++is2 ) {
677 TopoDS_Shape & v = is2 ? v2 : v1;
678 if ( helper.IsSeamShape( v ) ) {
679 // reverse or not depending on orientation of adjacent seam
681 list<TopoDS_Edge>::iterator eIt2 = elIt;
683 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
685 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
686 if ( seam.Orientation() == TopAbs_REVERSED )
693 // the forward key-point
694 list< TPoint* > * vPoint = & getShapePoints( v1 );
695 if ( vPoint->empty() )
697 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
698 if ( vSubMesh && vSubMesh->NbNodes() ) {
699 myKeyPointIDs.push_back( iPoint );
700 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
701 const SMDS_MeshNode* node = nIt->next();
702 if ( v1.Orientation() == TopAbs_REVERSED )
703 closeNodePointIDMap.insert( make_pair( node, iPoint ));
705 nodePointIDMap.insert( make_pair( node, iPoint ));
707 TPoint* keyPoint = &myPoints[ iPoint++ ];
708 vPoint->push_back( keyPoint );
710 keyPoint->myInitUV = project( node, projector );
712 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
713 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
716 if ( !vPoint->empty() )
717 ePoints.push_back( vPoint->front() );
720 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
721 if ( eSubMesh && eSubMesh->NbNodes() )
723 // loop on nodes of an edge: sort them by param on edge
724 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
725 TParamNodeMap paramNodeMap;
726 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
727 while ( nIt->more() )
729 const SMDS_MeshNode* node = smdsNode( nIt->next() );
730 const SMDS_EdgePosition* epos =
731 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
732 double u = epos->GetUParameter();
733 paramNodeMap.insert( TParamNodeMap::value_type( u, node ));
735 // put U in [0,1] so that the first key-point has U==0
737 TParamNodeMap::iterator unIt = paramNodeMap.begin();
738 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
739 while ( unIt != paramNodeMap.end() )
741 TPoint* p = & myPoints[ iPoint ];
742 ePoints.push_back( p );
743 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
744 if ( isSeam && !isForward )
745 closeNodePointIDMap.insert( make_pair( node, iPoint ));
747 nodePointIDMap.insert ( make_pair( node, iPoint ));
750 p->myInitUV = project( node, projector );
752 double u = isForward ? (*unIt).first : (*unRIt).first;
753 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
754 p->myInitUV = C2d->Value( u ).XY();
756 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
761 // the reverse key-point
762 vPoint = & getShapePoints( v2 );
763 if ( vPoint->empty() )
765 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
766 if ( vSubMesh && vSubMesh->NbNodes() ) {
767 myKeyPointIDs.push_back( iPoint );
768 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
769 const SMDS_MeshNode* node = nIt->next();
770 if ( v2.Orientation() == TopAbs_REVERSED )
771 closeNodePointIDMap.insert( make_pair( node, iPoint ));
773 nodePointIDMap.insert( make_pair( node, iPoint ));
775 TPoint* keyPoint = &myPoints[ iPoint++ ];
776 vPoint->push_back( keyPoint );
778 keyPoint->myInitUV = project( node, projector );
780 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
781 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
784 if ( !vPoint->empty() )
785 ePoints.push_back( vPoint->front() );
787 // compute U of edge-points
790 double totalDist = 0;
791 list< TPoint* >::iterator pIt = ePoints.begin();
792 TPoint* prevP = *pIt;
793 prevP->myInitU = totalDist;
794 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
796 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
797 p->myInitU = totalDist;
800 if ( totalDist > DBL_MIN)
801 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
803 p->myInitU /= totalDist;
806 } // loop on edges of a wire
808 // Load in-face points and elements
810 if ( fSubMesh && fSubMesh->NbElements() )
812 list< TPoint* > & fPoints = getShapePoints( face );
813 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
814 while ( nIt->more() )
816 const SMDS_MeshNode* node = smdsNode( nIt->next() );
817 nodePointIDMap.insert( make_pair( node, iPoint ));
818 TPoint* p = &myPoints[ iPoint++ ];
819 fPoints.push_back( p );
821 p->myInitUV = project( node, projector );
823 const SMDS_FacePosition* pos =
824 static_cast<const SMDS_FacePosition*>(node->GetPosition().get());
825 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
827 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
830 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
831 while ( elemIt->more() )
833 const SMDS_MeshElement* elem = elemIt->next();
834 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
835 myElemPointIDs.push_back( TElemDef() );
836 TElemDef& elemPoints = myElemPointIDs.back();
837 // find point indices corresponding to element nodes
838 while ( nIt->more() )
840 const SMDS_MeshNode* node = smdsNode( nIt->next() );
841 iPoint = nodePointIDMap[ node ]; // point index of interest
842 // for a node on a seam edge there are two points
843 TNodePointIDMap::iterator n_id = closeNodePointIDMap.end();
844 if ( helper.IsSeamShape( node->GetPosition()->GetShapeId() ))
845 n_id = closeNodePointIDMap.find( node );
846 if ( n_id != closeNodePointIDMap.end() )
848 TPoint & p1 = myPoints[ iPoint ];
849 TPoint & p2 = myPoints[ n_id->second ];
850 // Select point closest to the rest nodes of element in UV space
851 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
852 const SMDS_MeshNode* notSeamNode = 0;
853 // find node not on a seam edge
854 while ( nIt2->more() && !notSeamNode ) {
855 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
856 if ( !helper.IsSeamShape( n->GetPosition()->GetShapeId() ))
859 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
860 double dist1 = uv.SquareDistance( p1.myInitUV );
861 double dist2 = uv.SquareDistance( p2.myInitUV );
863 iPoint = n_id->second;
865 elemPoints.push_back( iPoint );
870 myIsBoundaryPointsFound = true;
873 // Assure that U range is proportional to V range
876 vector< TPoint >::iterator pVecIt = myPoints.begin();
877 for ( ; pVecIt != myPoints.end(); pVecIt++ )
878 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
879 double minU, minV, maxU, maxV;
880 bndBox.Get( minU, minV, maxU, maxV );
881 double dU = maxU - minU, dV = maxV - minV;
882 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
885 // define where is the problem, in the face or in the mesh
886 TopExp_Explorer vExp( face, TopAbs_VERTEX );
887 for ( ; vExp.More(); vExp.Next() ) {
888 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
891 bndBox.Get( minU, minV, maxU, maxV );
892 dU = maxU - minU, dV = maxV - minV;
893 if ( dU <= DBL_MIN || dV <= DBL_MIN )
895 return setErrorCode( ERR_LOADF_NARROW_FACE );
897 // mesh is projected onto a line, e.g.
898 return setErrorCode( ERR_LOADF_CANT_PROJECT );
900 double ratio = dU / dV, maxratio = 3, scale;
902 if ( ratio > maxratio ) {
903 scale = ratio / maxratio;
906 else if ( ratio < 1./maxratio ) {
907 scale = maxratio / ratio;
912 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
913 TPoint & p = *pVecIt;
914 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
915 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
918 if ( myElemPointIDs.empty() ) {
919 MESSAGE( "No elements bound to the face");
920 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
923 return setErrorCode( ERR_OK );
926 //=======================================================================
927 //function : computeUVOnEdge
928 //purpose : compute coordinates of points on theEdge
929 //=======================================================================
931 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
932 const list< TPoint* > & ePoints )
934 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
936 Handle(Geom2d_Curve) C2d =
937 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
939 ePoints.back()->myInitU = 1.0;
940 list< TPoint* >::const_iterator pIt = ePoints.begin();
941 for ( pIt++; pIt != ePoints.end(); pIt++ )
943 TPoint* point = *pIt;
945 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
946 point->myU = ( f * ( 1 - du ) + l * du );
948 point->myUV = C2d->Value( point->myU ).XY();
952 //=======================================================================
953 //function : intersectIsolines
955 //=======================================================================
957 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
958 const gp_XY& uv21, const gp_XY& uv22, const double r2,
962 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
963 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
964 resUV = 0.5 * ( loc1 + loc2 );
965 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
966 // SKL 26.07.2007 for NPAL16567
967 double d1 = (uv11-uv12).Modulus();
968 double d2 = (uv21-uv22).Modulus();
969 double delta = d1*d2*1e-6;
970 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta;
972 // double len1 = ( uv11 - uv12 ).Modulus();
973 // double len2 = ( uv21 - uv22 ).Modulus();
974 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
978 // gp_Lin2d line1( uv11, uv12 - uv11 );
979 // gp_Lin2d line2( uv21, uv22 - uv21 );
980 // double angle = Abs( line1.Angle( line2 ) );
982 // IntAna2d_AnaIntersection inter;
983 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
984 // if ( inter.IsDone() && inter.NbPoints() == 1 )
986 // gp_Pnt2d interUV = inter.Point(1).Value();
987 // resUV += interUV.XY();
988 // inter.Perform( line1, line2 );
989 // interUV = inter.Point(1).Value();
990 // resUV += interUV.XY();
997 //=======================================================================
998 //function : compUVByIsoIntersection
1000 //=======================================================================
1002 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1003 const gp_XY& theInitUV,
1005 bool & theIsDeformed )
1007 // compute UV by intersection of 2 iso lines
1008 //gp_Lin2d isoLine[2];
1009 gp_XY uv1[2], uv2[2];
1011 const double zero = DBL_MIN;
1012 for ( int iIso = 0; iIso < 2; iIso++ )
1014 // to build an iso line:
1015 // find 2 pairs of consequent edge-points such that the range of their
1016 // initial parameters encloses the in-face point initial parameter
1017 gp_XY UV[2], initUV[2];
1018 int nbUV = 0, iCoord = iIso + 1;
1019 double initParam = theInitUV.Coord( iCoord );
1021 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1022 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1024 const list< TPoint* > & bndPoints = * bndIt;
1025 TPoint* prevP = bndPoints.back(); // this is the first point
1026 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1027 bool coincPrev = false;
1028 // loop on the edge-points
1029 for ( ; pIt != bndPoints.end(); pIt++ )
1031 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1032 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1033 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1034 if (!coincPrev && // ignore if initParam coincides with prev point param
1035 sumOfDiff > zero && // ignore if both points coincide with initParam
1036 prevParamDiff * paramDiff <= zero )
1038 // find UV in parametric space of theFace
1039 double r = Abs(prevParamDiff) / sumOfDiff;
1040 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1043 // throw away uv most distant from <theInitUV>
1044 gp_XY vec0 = initUV[0] - theInitUV;
1045 gp_XY vec1 = initUV[1] - theInitUV;
1046 gp_XY vec = uvInit - theInitUV;
1047 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1048 double dist0 = vec0.SquareModulus();
1049 double dist1 = vec1.SquareModulus();
1050 double dist = vec .SquareModulus();
1051 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1052 i = ( dist0 < dist1 ? 1 : 0 );
1053 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1054 i = 3; // theInitUV must remain between
1058 initUV[ i ] = uvInit;
1059 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1061 coincPrev = ( Abs(paramDiff) <= zero );
1068 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1069 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1070 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1071 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1073 // an iso line should be normal to UV[0] - UV[1] direction
1074 // and be located at the same relative distance as from initial ends
1075 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1077 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1078 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1079 //isoLine[ iIso ] = iso.Normal( isoLoc );
1080 uv1[ iIso ] = UV[0];
1081 uv2[ iIso ] = UV[1];
1084 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1085 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1086 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1087 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1094 // ==========================================================
1095 // structure representing a node of a grid of iso-poly-lines
1096 // ==========================================================
1103 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1104 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1105 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1106 TIsoNode(double initU, double initV):
1107 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1108 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1109 bool IsUVComputed() const
1110 { return myUV.X() != 1e100; }
1111 bool IsMovable() const
1112 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1113 void SetNotMovable()
1114 { myIsMovable = false; }
1115 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1116 { myBndNodes[ iDir + i * 2 ] = node; }
1117 TIsoNode* GetBoundaryNode(int iDir, int i)
1118 { return myBndNodes[ iDir + i * 2 ]; }
1119 void SetNext(TIsoNode* node, int iDir, int isForward)
1120 { myNext[ iDir + isForward * 2 ] = node; }
1121 TIsoNode* GetNext(int iDir, int isForward)
1122 { return myNext[ iDir + isForward * 2 ]; }
1125 //=======================================================================
1126 //function : getNextNode
1128 //=======================================================================
1130 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1132 TIsoNode* n = node->myNext[ dir ];
1133 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1134 n = 0;//node->myBndNodes[ dir ];
1135 // MESSAGE("getNextNode: use bnd for node "<<
1136 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1140 //=======================================================================
1141 //function : checkQuads
1142 //purpose : check if newUV destortes quadrangles around node,
1143 // and if ( crit == FIX_OLD ) fix newUV in this case
1144 //=======================================================================
1146 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1148 static bool checkQuads (const TIsoNode* node,
1150 const bool reversed,
1151 const int crit = FIX_OLD,
1152 double fixSize = 0.)
1154 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1155 int nbOldFix = 0, nbOldImpr = 0;
1156 double newBadRate = 0, oldBadRate = 0;
1157 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1158 int i, dir1 = 0, dir2 = 3;
1159 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1161 if ( dir2 > 3 ) dir2 = 0;
1163 // walking counterclockwise around a quad,
1164 // nodes are in the order: node, n[0], n[1], n[2]
1165 n[0] = getNextNode( node, dir1 );
1166 n[2] = getNextNode( node, dir2 );
1167 if ( !n[0] || !n[2] ) continue;
1168 n[1] = getNextNode( n[0], dir2 );
1169 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1170 bool isTriangle = ( !n[1] );
1172 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1174 // if ( fixSize != 0 ) {
1175 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1176 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1177 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1178 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1180 // check if a quadrangle is degenerated
1182 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1183 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1186 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1189 // find min size of the diagonal node-n[1]
1190 double minDiag = fixSize;
1191 if ( minDiag == 0. ) {
1192 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1193 if ( !isTriangle ) {
1194 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1195 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1197 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1198 minDiag = sqrt( maxLen2 ) * PI / 60.; // ~ maxLen * Sin( 3 deg )
1201 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1202 // ( behind means "to the right of")
1204 // 1. newUV is not behind 01 and 12 dirs
1205 // 2. or newUV is not behind 02 dir and n[2] is convex
1206 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1207 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1208 gp_Vec2d moveVec[3], outVec[3];
1209 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1211 bool isDiag = ( i == 2 );
1212 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1216 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1218 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1220 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1222 gp_Vec2d newDir( n[i]->myUV, newUV );
1223 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1225 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1226 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1227 if ( crit == FIX_OLD ) {
1228 wasIn[i] = ( outDir * oldDir < 0 );
1229 wasOk[i] = ( outDir * oldDir < -minDiag );
1231 newBadRate += outDir * newDir;
1233 oldBadRate += outDir * oldDir;
1236 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1237 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1238 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1239 moveVec[i] = ( oldDist - minDiag ) * outDir;
1244 // check if n[2] is convex
1247 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1249 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1250 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1251 newIsOk = ( newIsOk && isNewOk );
1252 newIsIn = ( newIsIn && isNewIn );
1254 if ( crit != FIX_OLD ) {
1255 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1256 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1260 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1261 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1262 oldIsIn = ( oldIsIn && isOldIn );
1263 oldIsOk = ( oldIsOk && isOldIn );
1266 if ( !isOldIn ) { // node is outside a quadrangle
1267 // move newUV inside a quadrangle
1268 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1269 // node and newUV are outside: push newUV inside
1271 if ( convex || isTriangle ) {
1272 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1275 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1276 double outSize = out.Magnitude();
1277 if ( outSize > DBL_MIN )
1280 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1281 uv = n[1]->myUV - minDiag * out.XY();
1283 oldUVFixed[ nbOldFix++ ] = uv;
1284 //node->myUV = newUV;
1286 else if ( !isOldOk ) {
1287 // try to fix old UV: move node inside as less as possible
1288 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1289 gp_XY uv1, uv2 = node->myUV;
1290 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1292 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1293 while ( !isOldOk ) {
1294 // find the least moveVec
1296 double minMove2 = 1e100;
1297 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1299 if ( moveVec[i].Coord(1) < 1e100 ) {
1300 double move2 = moveVec[i].SquareMagnitude();
1301 if ( move2 < minMove2 ) {
1310 // move node to newUV
1311 uv1 = node->myUV + moveVec[ iMin ].XY();
1312 uv2 += moveVec[ iMin ].XY();
1313 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1314 // check if uv1 is ok
1315 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1316 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1317 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1319 oldUVImpr[ nbOldImpr++ ] = uv1;
1321 // check if uv2 is ok
1322 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1323 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1324 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1326 oldUVImpr[ nbOldImpr++ ] = uv2;
1331 } // loop on 4 quadrangles around <node>
1333 if ( crit == CHECK_NEW_OK )
1335 if ( crit == CHECK_NEW_IN )
1344 if ( oldIsIn && nbOldImpr ) {
1345 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1346 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1347 gp_XY uv = oldUVImpr[ 0 ];
1348 for ( int i = 1; i < nbOldImpr; i++ )
1349 uv += oldUVImpr[ i ];
1351 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1356 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1359 if ( !oldIsIn && nbOldFix ) {
1360 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1361 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1362 gp_XY uv = oldUVFixed[ 0 ];
1363 for ( int i = 1; i < nbOldFix; i++ )
1364 uv += oldUVFixed[ i ];
1366 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1371 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1374 if ( newIsIn && oldIsIn )
1375 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1376 else if ( !newIsIn )
1383 //=======================================================================
1384 //function : compUVByElasticIsolines
1385 //purpose : compute UV as nodes of iso-poly-lines consisting of
1386 // segments keeping relative size as in the pattern
1387 //=======================================================================
1388 //#define DEB_COMPUVBYELASTICISOLINES
1389 bool SMESH_Pattern::
1390 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1391 const list< TPoint* >& thePntToCompute)
1394 //cout << "============================== KEY POINTS =============================="<<endl;
1395 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1396 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1397 // TPoint& p = myPoints[ *kpIt ];
1398 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1399 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1401 //cout << "=============================="<<endl;
1403 // Define parameters of iso-grid nodes in U and V dir
1405 set< double > paramSet[ 2 ];
1406 list< list< TPoint* > >::const_iterator pListIt;
1407 list< TPoint* >::const_iterator pIt;
1408 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1409 const list< TPoint* > & pList = * pListIt;
1410 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1411 paramSet[0].insert( (*pIt)->myInitUV.X() );
1412 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1415 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1416 paramSet[0].insert( (*pIt)->myInitUV.X() );
1417 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1419 // unite close parameters and split too long segments
1422 for ( iDir = 0; iDir < 2; iDir++ )
1424 set< double > & params = paramSet[ iDir ];
1425 double range = ( *params.rbegin() - *params.begin() );
1426 double toler = range / 1e6;
1427 tol[ iDir ] = toler;
1428 // double maxSegment = range / params.size() / 2.;
1430 // set< double >::iterator parIt = params.begin();
1431 // double prevPar = *parIt;
1432 // for ( parIt++; parIt != params.end(); parIt++ )
1434 // double segLen = (*parIt) - prevPar;
1435 // if ( segLen < toler )
1436 // ;//params.erase( prevPar ); // unite
1437 // else if ( segLen > maxSegment )
1438 // params.insert( prevPar + 0.5 * segLen ); // split
1439 // prevPar = (*parIt);
1443 // Make nodes of a grid of iso-poly-lines
1445 list < TIsoNode > nodes;
1446 typedef list < TIsoNode *> TIsoLine;
1447 map < double, TIsoLine > isoMap[ 2 ];
1449 set< double > & params0 = paramSet[ 0 ];
1450 set< double >::iterator par0It = params0.begin();
1451 for ( ; par0It != params0.end(); par0It++ )
1453 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1454 set< double > & params1 = paramSet[ 1 ];
1455 set< double >::iterator par1It = params1.begin();
1456 for ( ; par1It != params1.end(); par1It++ )
1458 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1459 isoLine0.push_back( & nodes.back() );
1460 isoMap[1][ *par1It ].push_back( & nodes.back() );
1464 // Compute intersections of boundaries with iso-lines:
1465 // only boundary nodes will have computed UV so far
1468 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1469 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1470 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1472 const list< TPoint* > & bndPoints = * bndIt;
1473 TPoint* prevP = bndPoints.back(); // this is the first point
1474 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1475 // loop on the edge-points
1476 for ( ; pIt != bndPoints.end(); pIt++ )
1478 TPoint* point = *pIt;
1479 for ( iDir = 0; iDir < 2; iDir++ )
1481 const int iCoord = iDir + 1;
1482 const int iOtherCoord = 2 - iDir;
1483 double par1 = prevP->myInitUV.Coord( iCoord );
1484 double par2 = point->myInitUV.Coord( iCoord );
1485 double parDif = par2 - par1;
1486 if ( Abs( parDif ) <= DBL_MIN )
1488 // find iso-lines intersecting a bounadry
1489 double toler = tol[ 1 - iDir ];
1490 double minPar = Min ( par1, par2 );
1491 double maxPar = Max ( par1, par2 );
1492 map < double, TIsoLine >& isos = isoMap[ iDir ];
1493 map < double, TIsoLine >::iterator isoIt = isos.begin();
1494 for ( ; isoIt != isos.end(); isoIt++ )
1496 double isoParam = (*isoIt).first;
1497 if ( isoParam < minPar || isoParam > maxPar )
1499 double r = ( isoParam - par1 ) / parDif;
1500 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1501 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1502 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1503 // find existing node with otherPar or insert a new one
1504 TIsoLine & isoLine = (*isoIt).second;
1506 TIsoLine::iterator nIt = isoLine.begin();
1507 for ( ; nIt != isoLine.end(); nIt++ ) {
1508 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1509 if ( nodePar >= otherPar )
1513 if ( Abs( nodePar - otherPar ) <= toler )
1514 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1516 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1517 node = & nodes.back();
1518 isoLine.insert( nIt, node );
1520 node->SetNotMovable();
1522 uvBnd.Add( gp_Pnt2d( uv ));
1523 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1525 gp_XY tgt( point->myUV - prevP->myUV );
1526 if ( ::IsEqual( r, 1. ))
1527 node->myDir[ 0 ] = tgt;
1528 else if ( ::IsEqual( r, 0. ))
1529 node->myDir[ 1 ] = tgt;
1531 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1532 // keep boundary nodes corresponding to boundary points
1533 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1534 if ( bndNodes.empty() || bndNodes.back() != node )
1535 bndNodes.push_back( node );
1536 } // loop on isolines
1537 } // loop on 2 directions
1539 } // loop on boundary points
1540 } // loop on boundaries
1542 // Define orientation
1544 // find the point with the least X
1545 double leastX = DBL_MAX;
1546 TIsoNode * leftNode;
1547 list < TIsoNode >::iterator nodeIt = nodes.begin();
1548 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1549 TIsoNode & node = *nodeIt;
1550 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1551 leastX = node.myUV.X();
1554 // if ( node.IsUVComputed() ) {
1555 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1556 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1557 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1558 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1561 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1562 //SCRUTE( reversed );
1564 // Prepare internal nodes:
1566 // 2. compute ratios
1567 // 3. find boundary nodes for each node
1568 // 4. remove nodes out of the boundary
1569 for ( iDir = 0; iDir < 2; iDir++ )
1571 const int iCoord = 2 - iDir; // coord changing along an isoline
1572 map < double, TIsoLine >& isos = isoMap[ iDir ];
1573 map < double, TIsoLine >::iterator isoIt = isos.begin();
1574 for ( ; isoIt != isos.end(); isoIt++ )
1576 TIsoLine & isoLine = (*isoIt).second;
1577 bool firstCompNodeFound = false;
1578 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1579 nPrevIt = nIt = nNextIt = isoLine.begin();
1581 nNextIt++; nNextIt++;
1582 while ( nIt != isoLine.end() )
1584 // 1. connect prev - cur
1585 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1586 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1587 firstCompNodeFound = true;
1588 lastCompNodePos = nPrevIt;
1590 if ( firstCompNodeFound ) {
1591 node->SetNext( prevNode, iDir, 0 );
1592 prevNode->SetNext( node, iDir, 1 );
1595 if ( nNextIt != isoLine.end() ) {
1596 double par1 = prevNode->myInitUV.Coord( iCoord );
1597 double par2 = node->myInitUV.Coord( iCoord );
1598 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1599 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1601 // 3. find boundary nodes
1602 if ( node->IsUVComputed() )
1603 lastCompNodePos = nIt;
1604 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1605 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1606 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1607 if ( (*nIt2)->IsUVComputed() )
1609 if ( nIt2 != isoLine.end() ) {
1611 node->SetBoundaryNode( bndNode1, iDir, 0 );
1612 node->SetBoundaryNode( bndNode2, iDir, 1 );
1613 // cout << "--------------------------------------------------"<<endl;
1614 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1615 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1616 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1617 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1618 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1619 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1622 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1623 node->SetBoundaryNode( 0, iDir, 0 );
1624 node->SetBoundaryNode( 0, iDir, 1 );
1628 if ( nNextIt != isoLine.end() ) nNextIt++;
1629 // 4. remove nodes out of the boundary
1630 if ( !firstCompNodeFound )
1631 isoLine.pop_front();
1632 } // loop on isoLine nodes
1634 // remove nodes after the boundary
1635 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1636 // (*nIt)->SetNotMovable();
1637 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1638 } // loop on isolines
1639 } // loop on 2 directions
1641 // Compute local isoline direction for internal nodes
1644 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1645 map < double, TIsoLine >::iterator isoIt = isos.begin();
1646 for ( ; isoIt != isos.end(); isoIt++ )
1648 TIsoLine & isoLine = (*isoIt).second;
1649 TIsoLine::iterator nIt = isoLine.begin();
1650 for ( ; nIt != isoLine.end(); nIt++ )
1652 TIsoNode* node = *nIt;
1653 if ( node->IsUVComputed() || !node->IsMovable() )
1655 gp_Vec2d aTgt[2], aNorm[2];
1658 for ( iDir = 0; iDir < 2; iDir++ )
1660 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1661 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1662 if ( !bndNode1 || !bndNode2 ) {
1666 const int iCoord = 2 - iDir; // coord changing along an isoline
1667 double par1 = bndNode1->myInitUV.Coord( iCoord );
1668 double par2 = node->myInitUV.Coord( iCoord );
1669 double par3 = bndNode2->myInitUV.Coord( iCoord );
1670 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1672 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1673 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1674 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1675 else tgt1.Reverse();
1676 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1678 if ( ratio[ iDir ] < 0.5 )
1679 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1681 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1683 aNorm[ iDir ].Reverse(); // along iDir isoline
1685 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1686 // maybe angle is more than |PI|
1687 if ( Abs( angle ) > PI / 2. ) {
1688 // check direction of the last but one perpendicular isoline
1689 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1690 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1691 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1692 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1693 if ( isoDir * tgt2 < 0 )
1695 double angle2 = tgt1.Angle( isoDir );
1696 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1697 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1698 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1699 //MESSAGE("REVERSE ANGLE");
1702 if ( Abs( angle2 ) > Abs( angle ) ||
1703 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1704 //MESSAGE("Add PI");
1705 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1706 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1707 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1708 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1709 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1710 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1713 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1717 for ( iDir = 0; iDir < 2; iDir++ )
1719 aTgt[iDir].Normalize();
1720 aNorm[1-iDir].Normalize();
1721 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1724 node->myDir[iDir] = //aTgt[iDir];
1725 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1727 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1728 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1729 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1730 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1732 } // loop on iso nodes
1733 } // loop on isolines
1735 // Find nodes to start computing UV from
1737 list< TIsoNode* > startNodes;
1738 list< TIsoNode* >::iterator nIt = bndNodes.end();
1739 TIsoNode* node = *(--nIt);
1740 TIsoNode* prevNode = *(--nIt);
1741 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1743 TIsoNode* nextNode = *nIt;
1744 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1745 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1746 double initAngle = initTgt1.Angle( initTgt2 );
1747 double angle = node->myDir[0].Angle( node->myDir[1] );
1748 if ( reversed ) angle = -angle;
1749 if ( initAngle > angle && initAngle - angle > PI / 2.1 ) {
1750 // find a close internal node
1751 TIsoNode* nClose = 0;
1752 list< TIsoNode* > testNodes;
1753 testNodes.push_back( node );
1754 list< TIsoNode* >::iterator it = testNodes.begin();
1755 for ( ; !nClose && it != testNodes.end(); it++ )
1757 for (int i = 0; i < 4; i++ )
1759 nClose = (*it)->myNext[ i ];
1761 if ( !nClose->IsUVComputed() )
1764 testNodes.push_back( nClose );
1770 startNodes.push_back( nClose );
1771 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1772 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1773 // "initAngle: " << initAngle << " angle: " << angle << endl;
1774 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1775 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1776 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1777 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1783 // Compute starting UV of internal nodes
1785 list < TIsoNode* > internNodes;
1786 bool needIteration = true;
1787 if ( startNodes.empty() ) {
1788 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1789 needIteration = false;
1790 map < double, TIsoLine >& isos = isoMap[ 0 ];
1791 map < double, TIsoLine >::iterator isoIt = isos.begin();
1792 for ( ; isoIt != isos.end(); isoIt++ )
1794 TIsoLine & isoLine = (*isoIt).second;
1795 TIsoLine::iterator nIt = isoLine.begin();
1796 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1798 TIsoNode* node = *nIt;
1799 if ( !node->IsUVComputed() && node->IsMovable() ) {
1800 internNodes.push_back( node );
1802 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1803 node->myUV, needIteration ))
1804 node->myUV = node->myInitUV;
1808 if ( needIteration )
1809 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1811 TIsoNode* node = *nIt, *nClose = 0;
1812 list< TIsoNode* > testNodes;
1813 testNodes.push_back( node );
1814 list< TIsoNode* >::iterator it = testNodes.begin();
1815 for ( ; !nClose && it != testNodes.end(); it++ )
1817 for (int i = 0; i < 4; i++ )
1819 nClose = (*it)->myNext[ i ];
1821 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1824 testNodes.push_back( nClose );
1830 startNodes.push_back( nClose );
1834 double aMin[2], aMax[2], step[2];
1835 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1836 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1837 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1838 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1839 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1841 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1843 TIsoNode* prevN[2], *node = *nIt;
1844 if ( node->IsUVComputed() || !node->IsMovable() )
1846 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1847 int nbComp = 0, nbPrev = 0;
1848 for ( iDir = 0; iDir < 2; iDir++ )
1850 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1851 TIsoNode* n = node->GetNext( iDir, 0 );
1852 if ( n->IsUVComputed() )
1855 startNodes.push_back( n );
1856 n = node->GetNext( iDir, 1 );
1857 if ( n->IsUVComputed() )
1860 startNodes.push_back( n );
1862 prevNode1 = prevNode2;
1865 if ( prevNode1 ) nbPrev++;
1866 if ( prevNode2 ) nbPrev++;
1869 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1870 double par = node->myInitUV.Coord( 2 - iDir );
1871 bool isEnd = ( prevPar > par );
1872 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1873 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1874 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1876 MESSAGE("Why we are here?");
1879 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1880 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1881 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1882 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1883 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1884 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1885 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1886 //" par: " << prevPar << endl;
1887 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1888 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1890 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1891 gp_XY & uv1 = prevNode1->myUV;
1892 gp_XY & uv2 = prevNode2->myUV;
1893 // dir = ( uv2 - uv1 );
1894 // double len = dir.Modulus();
1895 // if ( len > DBL_MIN )
1896 // dir /= len * 0.5;
1897 double r = node->myRatio[ iDir ];
1898 newUV += uv1 * ( 1 - r ) + uv2 * r;
1901 newUV += prevNode1->myUV + dir * step[ iDir ];
1904 prevN[ iDir ] = prevNode1;
1908 if ( !nbComp ) continue;
1911 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1913 // check if a quadrangle is not distorted
1915 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1916 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1917 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1918 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1922 internNodes.push_back( node );
1927 static int maxNbIter = 100;
1928 #ifdef DEB_COMPUVBYELASTICISOLINES
1930 bool useNbMoveNode = 0;
1931 static int maxNbNodeMove = 100;
1934 if ( !useNbMoveNode )
1935 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
1940 if ( !needIteration) break;
1941 #ifdef DEB_COMPUVBYELASTICISOLINES
1942 if ( nbIter >= maxNbIter ) break;
1945 list < TIsoNode* >::iterator nIt = internNodes.begin();
1946 for ( ; nIt != internNodes.end(); nIt++ ) {
1947 #ifdef DEB_COMPUVBYELASTICISOLINES
1949 cout << nbNodeMove <<" =================================================="<<endl;
1951 TIsoNode * node = *nIt;
1955 for ( iDir = 0; iDir < 2; iDir++ )
1957 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
1958 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
1959 double r = node->myRatio[ iDir ];
1960 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
1961 // line[ iDir ].SetLocation( loc[ iDir ] );
1962 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
1965 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
1966 double locR[2] = { 0, 0 };
1967 for ( iDir = 0; iDir < 2; iDir++ )
1969 const int iCoord = 2 - iDir; // coord changing along an isoline
1970 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1971 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1972 if ( !bndNode1 || !bndNode2 ) {
1975 double par1 = bndNode1->myInitUV.Coord( iCoord );
1976 double par2 = node->myInitUV.Coord( iCoord );
1977 double par3 = bndNode2->myInitUV.Coord( iCoord );
1978 double r = ( par2 - par1 ) / ( par3 - par1 );
1979 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
1980 locR[ iDir ] = ( 1 - r * r ) * 0.25;
1982 //locR[0] = locR[1] = 0.25;
1983 // intersect the 2 lines and move a node
1984 //IntAna2d_AnaIntersection inter( line[0], line[1] );
1985 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
1987 // double intR = 1 - locR[0] - locR[1];
1988 // gp_XY newUV = inter.Point(1).Value().XY();
1989 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
1990 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
1992 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
1993 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
1994 // avoid parallel isolines intersection
1995 checkQuads( node, newUV, reversed );
1997 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
1999 } // intersection found
2000 #ifdef DEB_COMPUVBYELASTICISOLINES
2001 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2003 } // loop on internal nodes
2004 #ifdef DEB_COMPUVBYELASTICISOLINES
2005 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2007 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2009 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2011 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2012 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2013 #ifndef DEB_COMPUVBYELASTICISOLINES
2018 // Set computed UV to points
2020 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2021 TPoint* point = *pIt;
2022 //gp_XY oldUV = point->myUV;
2023 double minDist = DBL_MAX;
2024 list < TIsoNode >::iterator nIt = nodes.begin();
2025 for ( ; nIt != nodes.end(); nIt++ ) {
2026 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2027 if ( dist < minDist ) {
2029 point->myUV = (*nIt).myUV;
2039 //=======================================================================
2040 //function : setFirstEdge
2041 //purpose : choose the best first edge of theWire; return the summary distance
2042 // between point UV computed by isolines intersection and
2043 // eventual UV got from edge p-curves
2044 //=======================================================================
2046 //#define DBG_SETFIRSTEDGE
2047 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2049 int iE, nbEdges = theWire.size();
2053 // Transform UVs computed by iso to fit bnd box of a wire
2055 // max nb of points on an edge
2057 int eID = theFirstEdgeID;
2058 for ( iE = 0; iE < nbEdges; iE++ )
2059 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2061 // compute bnd boxes
2062 TopoDS_Face face = TopoDS::Face( myShape );
2063 Bnd_Box2d bndBox, eBndBox;
2064 eID = theFirstEdgeID;
2065 list< TopoDS_Edge >::iterator eIt;
2066 list< TPoint* >::iterator pIt;
2067 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2069 // UV by isos stored in TPoint.myXYZ
2070 list< TPoint* > & ePoints = getShapePoints( eID++ );
2071 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2073 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2075 // UV by an edge p-curve
2077 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2078 double dU = ( l - f ) / ( maxNbPnt - 1 );
2079 for ( int i = 0; i < maxNbPnt; i++ )
2080 eBndBox.Add( C2d->Value( f + i * dU ));
2083 // transform UVs by isos
2084 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2085 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2086 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2087 #ifdef DBG_SETFIRSTEDGE
2088 cout << "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2089 << eMinPar[1] << " - " << eMaxPar[1] << endl;
2091 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2093 double dMin = eMinPar[i] - minPar[i];
2094 double dMax = eMaxPar[i] - maxPar[i];
2095 double dPar = maxPar[i] - minPar[i];
2096 eID = theFirstEdgeID;
2097 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2099 list< TPoint* > & ePoints = getShapePoints( eID++ );
2100 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2102 double par = (*pIt)->myXYZ.Coord( iC );
2103 double r = ( par - minPar[i] ) / dPar;
2104 par += ( 1 - r ) * dMin + r * dMax;
2105 (*pIt)->myXYZ.SetCoord( iC, par );
2111 double minDist = DBL_MAX;
2112 for ( iE = 0 ; iE < nbEdges; iE++ )
2114 #ifdef DBG_SETFIRSTEDGE
2115 cout << " VARIANT " << iE << endl;
2117 // evaluate the distance between UV computed by the 2 methods:
2118 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2120 int eID = theFirstEdgeID;
2121 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2123 list< TPoint* > & ePoints = getShapePoints( eID++ );
2124 computeUVOnEdge( *eIt, ePoints );
2125 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2127 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2128 #ifdef DBG_SETFIRSTEDGE
2129 cout << " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2130 p->myUV.X() << ", " << p->myUV.Y() << ") " << endl;
2134 #ifdef DBG_SETFIRSTEDGE
2135 cout << "dist -- " << dist << endl;
2137 if ( dist < minDist ) {
2139 eBest = theWire.front();
2141 // check variant with another first edge
2142 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2144 // put the best first edge to the theWire front
2145 if ( eBest != theWire.front() ) {
2146 eIt = find ( theWire.begin(), theWire.end(), eBest );
2147 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2153 //=======================================================================
2154 //function : sortSameSizeWires
2155 //purpose : sort wires in theWireList from theFromWire until theToWire,
2156 // the wires are set in the order to correspond to the order
2157 // of boundaries; after sorting, edges in the wires are put
2158 // in a good order, point UVs on edges are computed and points
2159 // are appended to theEdgesPointsList
2160 //=======================================================================
2162 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2163 const TListOfEdgesList::iterator& theFromWire,
2164 const TListOfEdgesList::iterator& theToWire,
2165 const int theFirstEdgeID,
2166 list< list< TPoint* > >& theEdgesPointsList )
2168 TopoDS_Face F = TopoDS::Face( myShape );
2169 int iW, nbWires = 0;
2170 TListOfEdgesList::iterator wlIt = theFromWire;
2171 while ( wlIt++ != theToWire )
2174 // Recompute key-point UVs by isolines intersection,
2175 // compute CG of key-points for each wire and bnd boxes of GCs
2178 gp_XY orig( gp::Origin2d().XY() );
2179 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2180 Bnd_Box2d bndBox, vBndBox;
2181 int eID = theFirstEdgeID;
2182 list< TopoDS_Edge >::iterator eIt;
2183 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2185 list< TopoDS_Edge > & wire = *wlIt;
2186 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2188 list< TPoint* > & ePoints = getShapePoints( eID++ );
2189 TPoint* p = ePoints.front();
2190 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2191 MESSAGE("cant sortSameSizeWires()");
2194 gcVec[iW] += p->myUV;
2195 bndBox.Add( gp_Pnt2d( p->myUV ));
2196 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2197 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2198 vGcVec[iW] += vXY.XY();
2200 // keep the computed UV to compare against by setFirstEdge()
2201 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2203 gcVec[iW] /= nbWires;
2204 vGcVec[iW] /= nbWires;
2205 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2206 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2209 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2211 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2212 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2213 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2214 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2216 double dMin = vMinPar[i] - minPar[i];
2217 double dMax = vMaxPar[i] - maxPar[i];
2218 double dPar = maxPar[i] - minPar[i];
2219 if ( Abs( dPar ) <= DBL_MIN )
2221 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2222 double par = gcVec[iW].Coord( iC );
2223 double r = ( par - minPar[i] ) / dPar;
2224 par += ( 1 - r ) * dMin + r * dMax;
2225 gcVec[iW].SetCoord( iC, par );
2229 // Define boundary - wire correspondence by GC closeness
2231 TListOfEdgesList tmpWList;
2232 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2233 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2234 TIntWirePosMap bndIndWirePosMap;
2235 vector< bool > bndFound( nbWires, false );
2236 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2238 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2239 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2240 double minDist = DBL_MAX;
2241 gp_XY & wGc = vGcVec[ iW ];
2243 for ( int iB = 0; iB < nbWires; iB++ ) {
2244 if ( bndFound[ iB ] ) continue;
2245 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2246 if ( dist < minDist ) {
2251 bndFound[ bIndex ] = true;
2252 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2257 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2258 eID = theFirstEdgeID;
2259 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2261 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2262 list < TopoDS_Edge > & wire = ( *wirePos );
2264 // choose the best first edge of a wire
2265 setFirstEdge( wire, eID );
2267 // compute eventual UV and fill theEdgesPointsList
2268 theEdgesPointsList.push_back( list< TPoint* >() );
2269 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2270 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2272 list< TPoint* > & ePoints = getShapePoints( eID++ );
2273 computeUVOnEdge( *eIt, ePoints );
2274 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2276 // put wire back to theWireList
2278 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2284 //=======================================================================
2286 //purpose : Compute nodes coordinates applying
2287 // the loaded pattern to <theFace>. The first key-point
2288 // will be mapped into <theVertexOnKeyPoint1>
2289 //=======================================================================
2291 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2292 const TopoDS_Vertex& theVertexOnKeyPoint1,
2293 const bool theReverse)
2295 MESSAGE(" ::Apply(face) " );
2296 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2297 if ( !setShapeToMesh( face ))
2300 // find points on edges, it fills myNbKeyPntInBoundary
2301 if ( !findBoundaryPoints() )
2304 // Define the edges order so that the first edge starts at
2305 // theVertexOnKeyPoint1
2307 list< TopoDS_Edge > eList;
2308 list< int > nbVertexInWires;
2309 int nbWires = SMESH_Block::GetOrderedEdges( face, theVertexOnKeyPoint1, eList, nbVertexInWires);
2310 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2312 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2313 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2315 // check nb wires and edges
2316 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2317 l1.sort(); l2.sort();
2320 MESSAGE( "Wrong nb vertices in wires" );
2321 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2324 // here shapes get IDs, for the outer wire IDs are OK
2325 list<TopoDS_Edge>::iterator elIt = eList.begin();
2326 for ( ; elIt != eList.end(); elIt++ ) {
2327 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2328 if ( BRep_Tool::IsClosed( *elIt, theFace ) )
2329 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));
2331 int nbVertices = myShapeIDMap.Extent();
2333 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2334 myShapeIDMap.Add( *elIt );
2336 myShapeIDMap.Add( face );
2338 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent()/* + nbSeamShapes*/ ) {
2339 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2340 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2343 // points on edges to be used for UV computation of in-face points
2344 list< list< TPoint* > > edgesPointsList;
2345 edgesPointsList.push_back( list< TPoint* >() );
2346 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2347 list< TPoint* >::iterator pIt;
2349 // compute UV of points on the outer wire
2350 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2351 for (iE = 0, elIt = eList.begin();
2352 iE < nbEdgesInOuterWire && elIt != eList.end();
2355 list< TPoint* > & ePoints = getShapePoints( *elIt );
2357 computeUVOnEdge( *elIt, ePoints );
2358 // collect on-edge points (excluding the last one)
2359 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2362 // If there are several wires, define the order of edges of inner wires:
2363 // compute UV of inner edge-points using 2 methods: the one for in-face points
2364 // and the one for on-edge points and then choose the best edge order
2365 // by the best correspondance of the 2 results
2368 // compute UV of inner edge-points using the method for in-face points
2369 // and devide eList into a list of separate wires
2371 list< list< TopoDS_Edge > > wireList;
2372 list<TopoDS_Edge>::iterator eIt = elIt;
2373 list<int>::iterator nbEIt = nbVertexInWires.begin();
2374 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2376 int nbEdges = *nbEIt;
2377 wireList.push_back( list< TopoDS_Edge >() );
2378 list< TopoDS_Edge > & wire = wireList.back();
2379 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2381 list< TPoint* > & ePoints = getShapePoints( *eIt );
2382 pIt = ePoints.begin();
2383 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2385 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2386 MESSAGE("cant Apply(face)");
2389 // keep the computed UV to compare against by setFirstEdge()
2390 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2392 wire.push_back( *eIt );
2395 // remove inner edges from eList
2396 eList.erase( elIt, eList.end() );
2398 // sort wireList by nb edges in a wire
2399 sortBySize< TopoDS_Edge > ( wireList );
2401 // an ID of the first edge of a boundary
2402 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2403 // if ( nbSeamShapes > 0 )
2404 // id1 += 2; // 2 vertices more
2406 // find points - edge correspondence for wires of unique size,
2407 // edge order within a wire should be defined only
2409 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2410 while ( wlIt != wireList.end() )
2412 list< TopoDS_Edge >& wire = (*wlIt);
2413 int nbEdges = wire.size();
2415 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2417 // choose the best first edge of a wire
2418 setFirstEdge( wire, id1 );
2420 // compute eventual UV and collect on-edge points
2421 edgesPointsList.push_back( list< TPoint* >() );
2422 edgesPoints = & edgesPointsList.back();
2424 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2426 list< TPoint* > & ePoints = getShapePoints( eID++ );
2427 computeUVOnEdge( *eIt, ePoints );
2428 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2434 // find boundary - wire correspondence for several wires of same size
2436 id1 = nbVertices + nbEdgesInOuterWire + 1;
2437 wlIt = wireList.begin();
2438 while ( wlIt != wireList.end() )
2440 int nbSameSize = 0, nbEdges = (*wlIt).size();
2441 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2443 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2447 if ( nbSameSize > 0 )
2448 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2451 id1 += nbEdges * ( nbSameSize + 1 );
2454 // add well-ordered edges to eList
2456 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2458 list< TopoDS_Edge >& wire = (*wlIt);
2459 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2462 // re-fill myShapeIDMap - all shapes get good IDs
2464 myShapeIDMap.Clear();
2465 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2466 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2467 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2468 myShapeIDMap.Add( *elIt );
2469 myShapeIDMap.Add( face );
2471 } // there are inner wires
2473 // Compute XYZ of on-edge points
2475 TopLoc_Location loc;
2476 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2478 BRepAdaptor_Curve C3d( *elIt );
2479 list< TPoint* > & ePoints = getShapePoints( iE++ );
2480 pIt = ePoints.begin();
2481 for ( pIt++; pIt != ePoints.end(); pIt++ )
2483 TPoint* point = *pIt;
2484 point->myXYZ = C3d.Value( point->myU );
2488 // Compute UV and XYZ of in-face points
2490 // try to use a simple algo
2491 list< TPoint* > & fPoints = getShapePoints( face );
2492 bool isDeformed = false;
2493 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2494 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2495 (*pIt)->myUV, isDeformed )) {
2496 MESSAGE("cant Apply(face)");
2499 // try to use a complex algo if it is a difficult case
2500 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2502 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2503 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2504 (*pIt)->myUV, isDeformed )) {
2505 MESSAGE("cant Apply(face)");
2510 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2511 const gp_Trsf & aTrsf = loc.Transformation();
2512 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2514 TPoint * point = *pIt;
2515 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2516 if ( !loc.IsIdentity() )
2517 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2520 myIsComputed = true;
2522 return setErrorCode( ERR_OK );
2525 //=======================================================================
2527 //purpose : Compute nodes coordinates applying
2528 // the loaded pattern to <theFace>. The first key-point
2529 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2530 //=======================================================================
2532 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2533 const int theNodeIndexOnKeyPoint1,
2534 const bool theReverse)
2536 // MESSAGE(" ::Apply(MeshFace) " );
2538 if ( !IsLoaded() ) {
2539 MESSAGE( "Pattern not loaded" );
2540 return setErrorCode( ERR_APPL_NOT_LOADED );
2543 // check nb of nodes
2544 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2545 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2546 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2549 // find points on edges, it fills myNbKeyPntInBoundary
2550 if ( !findBoundaryPoints() )
2553 // check that there are no holes in a pattern
2554 if (myNbKeyPntInBoundary.size() > 1 ) {
2555 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2558 // Define the nodes order
2560 list< const SMDS_MeshNode* > nodes;
2561 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2562 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2564 while ( noIt->more() ) {
2565 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2566 nodes.push_back( node );
2567 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2570 if ( n != nodes.end() ) {
2572 if ( n != --nodes.end() )
2573 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2576 else if ( n != nodes.begin() )
2577 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2579 list< gp_XYZ > xyzList;
2580 myOrderedNodes.resize( theFace->NbNodes() );
2581 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2582 xyzList.push_back( gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() ));
2583 myOrderedNodes[ iSub++] = *n;
2586 // Define a face plane
2588 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2589 gp_Pnt P ( *xyzIt++ );
2590 gp_Vec Vx( P, *xyzIt++ ), N;
2592 N = Vx ^ gp_Vec( P, *xyzIt++ );
2593 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2594 if ( N.SquareMagnitude() <= DBL_MIN )
2595 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2596 gp_Ax2 pos( P, N, Vx );
2598 // Compute UV of key-points on a plane
2599 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2601 gp_Vec vec ( pos.Location(), *xyzIt );
2602 TPoint* p = getShapePoints( iSub ).front();
2603 p->myUV.SetX( vec * pos.XDirection() );
2604 p->myUV.SetY( vec * pos.YDirection() );
2608 // points on edges to be used for UV computation of in-face points
2609 list< list< TPoint* > > edgesPointsList;
2610 edgesPointsList.push_back( list< TPoint* >() );
2611 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2612 list< TPoint* >::iterator pIt;
2614 // compute UV and XYZ of points on edges
2616 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2618 gp_XYZ& xyz1 = *xyzIt++;
2619 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2621 list< TPoint* > & ePoints = getShapePoints( iSub );
2622 ePoints.back()->myInitU = 1.0;
2623 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2624 while ( *pIt != ePoints.back() )
2627 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2628 gp_Vec vec ( pos.Location(), p->myXYZ );
2629 p->myUV.SetX( vec * pos.XDirection() );
2630 p->myUV.SetY( vec * pos.YDirection() );
2632 // collect on-edge points (excluding the last one)
2633 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2636 // Compute UV and XYZ of in-face points
2638 // try to use a simple algo to compute UV
2639 list< TPoint* > & fPoints = getShapePoints( iSub );
2640 bool isDeformed = false;
2641 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2642 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2643 (*pIt)->myUV, isDeformed )) {
2644 MESSAGE("cant Apply(face)");
2647 // try to use a complex algo if it is a difficult case
2648 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2650 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2651 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2652 (*pIt)->myUV, isDeformed )) {
2653 MESSAGE("cant Apply(face)");
2658 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2660 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2663 myIsComputed = true;
2665 return setErrorCode( ERR_OK );
2668 //=======================================================================
2670 //purpose : Compute nodes coordinates applying
2671 // the loaded pattern to <theFace>. The first key-point
2672 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2673 //=======================================================================
2675 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2676 const SMDS_MeshFace* theFace,
2677 const TopoDS_Shape& theSurface,
2678 const int theNodeIndexOnKeyPoint1,
2679 const bool theReverse)
2681 // MESSAGE(" ::Apply(MeshFace) " );
2682 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2683 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2685 const TopoDS_Face& face = TopoDS::Face( theSurface );
2686 TopLoc_Location loc;
2687 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2688 const gp_Trsf & aTrsf = loc.Transformation();
2690 if ( !IsLoaded() ) {
2691 MESSAGE( "Pattern not loaded" );
2692 return setErrorCode( ERR_APPL_NOT_LOADED );
2695 // check nb of nodes
2696 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2697 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2698 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2701 // find points on edges, it fills myNbKeyPntInBoundary
2702 if ( !findBoundaryPoints() )
2705 // check that there are no holes in a pattern
2706 if (myNbKeyPntInBoundary.size() > 1 ) {
2707 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2710 // Define the nodes order
2712 list< const SMDS_MeshNode* > nodes;
2713 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2714 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2716 while ( noIt->more() ) {
2717 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2718 nodes.push_back( node );
2719 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2722 if ( n != nodes.end() ) {
2724 if ( n != --nodes.end() )
2725 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2728 else if ( n != nodes.begin() )
2729 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2732 // find a node not on a seam edge, if necessary
2733 SMESH_MesherHelper helper( *theMesh );
2734 helper.SetSubShape( theSurface );
2735 const SMDS_MeshNode* inFaceNode = 0;
2736 if ( helper.GetNodeUVneedInFaceNode() )
2738 SMESH_MeshEditor editor( theMesh );
2739 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2740 int shapeID = editor.FindShape( *n );
2742 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2743 if ( !helper.IsSeamShape( shapeID ))
2748 // Set UV of key-points (i.e. of nodes of theFace )
2749 vector< gp_XY > keyUV( theFace->NbNodes() );
2750 myOrderedNodes.resize( theFace->NbNodes() );
2751 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2753 TPoint* p = getShapePoints( iSub ).front();
2754 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2755 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2757 keyUV[ iSub-1 ] = p->myUV;
2758 myOrderedNodes[ iSub-1 ] = *n;
2761 // points on edges to be used for UV computation of in-face points
2762 list< list< TPoint* > > edgesPointsList;
2763 edgesPointsList.push_back( list< TPoint* >() );
2764 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2765 list< TPoint* >::iterator pIt;
2767 // compute UV and XYZ of points on edges
2769 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2771 gp_XY& uv1 = keyUV[ i ];
2772 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2774 list< TPoint* > & ePoints = getShapePoints( iSub );
2775 ePoints.back()->myInitU = 1.0;
2776 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2777 while ( *pIt != ePoints.back() )
2780 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2781 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2782 if ( !loc.IsIdentity() )
2783 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2785 // collect on-edge points (excluding the last one)
2786 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2789 // Compute UV and XYZ of in-face points
2791 // try to use a simple algo to compute UV
2792 list< TPoint* > & fPoints = getShapePoints( iSub );
2793 bool isDeformed = false;
2794 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2795 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2796 (*pIt)->myUV, isDeformed )) {
2797 MESSAGE("cant Apply(face)");
2800 // try to use a complex algo if it is a difficult case
2801 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2803 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2804 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2805 (*pIt)->myUV, isDeformed )) {
2806 MESSAGE("cant Apply(face)");
2811 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2813 TPoint * point = *pIt;
2814 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2815 if ( !loc.IsIdentity() )
2816 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2819 myIsComputed = true;
2821 return setErrorCode( ERR_OK );
2824 //=======================================================================
2825 //function : undefinedXYZ
2827 //=======================================================================
2829 static const gp_XYZ& undefinedXYZ()
2831 static gp_XYZ xyz( 1.e100, 0., 0. );
2835 //=======================================================================
2836 //function : isDefined
2838 //=======================================================================
2840 inline static bool isDefined(const gp_XYZ& theXYZ)
2842 return theXYZ.X() < 1.e100;
2845 //=======================================================================
2847 //purpose : Compute nodes coordinates applying
2848 // the loaded pattern to <theFaces>. The first key-point
2849 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2850 //=======================================================================
2852 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2853 std::set<const SMDS_MeshFace*>& theFaces,
2854 const int theNodeIndexOnKeyPoint1,
2855 const bool theReverse)
2857 MESSAGE(" ::Apply(set<MeshFace>) " );
2859 if ( !IsLoaded() ) {
2860 MESSAGE( "Pattern not loaded" );
2861 return setErrorCode( ERR_APPL_NOT_LOADED );
2864 // find points on edges, it fills myNbKeyPntInBoundary
2865 if ( !findBoundaryPoints() )
2868 // check that there are no holes in a pattern
2869 if (myNbKeyPntInBoundary.size() > 1 ) {
2870 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2875 myElemXYZIDs.clear();
2876 myXYZIdToNodeMap.clear();
2878 myIdsOnBoundary.clear();
2879 myReverseConnectivity.clear();
2881 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2882 myElements.reserve( theFaces.size() );
2884 // to find point index
2885 map< TPoint*, int > pointIndex;
2886 for ( int i = 0; i < myPoints.size(); i++ )
2887 pointIndex.insert( make_pair( & myPoints[ i ], i ));
2889 int ind1 = 0; // lowest point index for a face
2894 // SMESH_MeshEditor editor( theMesh );
2896 // apply to each face in theFaces set
2897 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2898 for ( ; face != theFaces.end(); ++face )
2900 // int curShapeId = editor.FindShape( *face );
2901 // if ( curShapeId != shapeID ) {
2902 // if ( curShapeId )
2903 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2906 // shapeID = curShapeId;
2909 if ( shape.IsNull() )
2910 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2912 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2914 MESSAGE( "Failed on " << *face );
2917 myElements.push_back( *face );
2919 // store computed points belonging to elements
2920 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2921 for ( ; ll != myElemPointIDs.end(); ++ll )
2923 myElemXYZIDs.push_back(TElemDef());
2924 TElemDef& xyzIds = myElemXYZIDs.back();
2925 TElemDef& pIds = *ll;
2926 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
2927 int pIndex = *id + ind1;
2928 xyzIds.push_back( pIndex );
2929 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
2930 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
2933 // put points on links to myIdsOnBoundary,
2934 // they will be used to sew new elements on adjacent refined elements
2935 int nbNodes = (*face)->NbNodes(), eID = nbNodes + 1;
2936 for ( int i = 0; i < nbNodes; i++ )
2938 list< TPoint* > & linkPoints = getShapePoints( eID++ );
2939 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
2940 const SMDS_MeshNode* n2 = myOrderedNodes[ i + 1 == nbNodes ? 0 : i + 1 ];
2941 // make a link and a node set
2942 TNodeSet linkSet, node1Set;
2943 linkSet.insert( n1 );
2944 linkSet.insert( n2 );
2945 node1Set.insert( n1 );
2946 list< TPoint* >::iterator p = linkPoints.begin();
2948 // map the first link point to n1
2949 int nId = pointIndex[ *p ] + ind1;
2950 myXYZIdToNodeMap[ nId ] = n1;
2951 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
2952 groups.push_back(list< int > ());
2953 groups.back().push_back( nId );
2955 // add the linkSet to the map
2956 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
2957 groups.push_back(list< int > ());
2958 list< int >& indList = groups.back();
2959 // add points to the map excluding the end points
2960 for ( p++; *p != linkPoints.back(); p++ )
2961 indList.push_back( pointIndex[ *p ] + ind1 );
2963 ind1 += myPoints.size();
2966 return !myElemXYZIDs.empty();
2969 //=======================================================================
2971 //purpose : Compute nodes coordinates applying
2972 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
2973 // will be mapped into <theNode000Index>-th node. The
2974 // (0,0,1) key-point will be mapped into <theNode000Index>-th
2976 //=======================================================================
2978 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
2979 const int theNode000Index,
2980 const int theNode001Index)
2982 MESSAGE(" ::Apply(set<MeshVolumes>) " );
2984 if ( !IsLoaded() ) {
2985 MESSAGE( "Pattern not loaded" );
2986 return setErrorCode( ERR_APPL_NOT_LOADED );
2989 // bind ID to points
2990 if ( !findBoundaryPoints() )
2993 // check that there are no holes in a pattern
2994 if (myNbKeyPntInBoundary.size() > 1 ) {
2995 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3000 myElemXYZIDs.clear();
3001 myXYZIdToNodeMap.clear();
3003 myIdsOnBoundary.clear();
3004 myReverseConnectivity.clear();
3006 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3007 myElements.reserve( theVolumes.size() );
3009 // to find point index
3010 map< TPoint*, int > pointIndex;
3011 for ( int i = 0; i < myPoints.size(); i++ )
3012 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3014 int ind1 = 0; // lowest point index for an element
3016 // apply to each element in theVolumes set
3017 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3018 for ( ; vol != theVolumes.end(); ++vol )
3020 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3021 MESSAGE( "Failed on " << *vol );
3024 myElements.push_back( *vol );
3026 // store computed points belonging to elements
3027 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3028 for ( ; ll != myElemPointIDs.end(); ++ll )
3030 myElemXYZIDs.push_back(TElemDef());
3031 TElemDef& xyzIds = myElemXYZIDs.back();
3032 TElemDef& pIds = *ll;
3033 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3034 int pIndex = *id + ind1;
3035 xyzIds.push_back( pIndex );
3036 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3037 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3040 // put points on edges and faces to myIdsOnBoundary,
3041 // they will be used to sew new elements on adjacent refined elements
3042 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3044 // make a set of sub-points
3046 vector< int > subIDs;
3047 if ( SMESH_Block::IsVertexID( Id )) {
3048 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3050 else if ( SMESH_Block::IsEdgeID( Id )) {
3051 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3052 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3053 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3056 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3057 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3058 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3059 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3060 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3061 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3062 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3063 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3066 list< TPoint* > & points = getShapePoints( Id );
3067 list< TPoint* >::iterator p = points.begin();
3068 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3069 groups.push_back(list< int > ());
3070 list< int >& indList = groups.back();
3071 for ( ; p != points.end(); p++ )
3072 indList.push_back( pointIndex[ *p ] + ind1 );
3073 if ( subNodes.size() == 1 ) // vertex case
3074 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3076 ind1 += myPoints.size();
3079 return !myElemXYZIDs.empty();
3082 //=======================================================================
3084 //purpose : Create a pattern from the mesh built on <theBlock>
3085 //=======================================================================
3087 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3088 const TopoDS_Shell& theBlock)
3090 MESSAGE(" ::Load(volume) " );
3093 SMESHDS_SubMesh * aSubMesh;
3095 // load shapes in myShapeIDMap
3097 TopoDS_Vertex v1, v2;
3098 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3099 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3102 int nbNodes = 0, shapeID;
3103 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3105 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3106 aSubMesh = getSubmeshWithElements( theMesh, S );
3108 nbNodes += aSubMesh->NbNodes();
3110 myPoints.resize( nbNodes );
3112 // load U of points on edges
3113 TNodePointIDMap nodePointIDMap;
3115 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3117 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3118 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3119 aSubMesh = getSubmeshWithElements( theMesh, S );
3120 if ( ! aSubMesh ) continue;
3121 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3122 if ( !nIt->more() ) continue;
3124 // store a node and a point
3125 while ( nIt->more() ) {
3126 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3127 nodePointIDMap.insert( make_pair( node, iPoint ));
3128 if ( block.IsVertexID( shapeID ))
3129 myKeyPointIDs.push_back( iPoint );
3130 TPoint* p = & myPoints[ iPoint++ ];
3131 shapePoints.push_back( p );
3132 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3133 p->myInitXYZ.SetCoord( 0,0,0 );
3135 list< TPoint* >::iterator pIt = shapePoints.begin();
3138 switch ( S.ShapeType() )
3143 for ( ; pIt != shapePoints.end(); pIt++ ) {
3144 double * coef = block.GetShapeCoef( shapeID );
3145 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3146 if ( coef[ iCoord - 1] > 0 )
3147 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3149 if ( S.ShapeType() == TopAbs_VERTEX )
3152 const TopoDS_Edge& edge = TopoDS::Edge( S );
3154 BRep_Tool::Range( edge, f, l );
3155 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3156 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3157 pIt = shapePoints.begin();
3158 nIt = aSubMesh->GetNodes();
3159 for ( ; nIt->more(); pIt++ )
3161 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3162 const SMDS_EdgePosition* epos =
3163 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
3164 double u = ( epos->GetUParameter() - f ) / ( l - f );
3165 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3170 for ( ; pIt != shapePoints.end(); pIt++ )
3172 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3173 MESSAGE( "!block.ComputeParameters()" );
3174 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3178 } // loop on block sub-shapes
3182 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3185 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3186 while ( elemIt->more() ) {
3187 SMDS_ElemIteratorPtr nIt = elemIt->next()->nodesIterator();
3188 myElemPointIDs.push_back( TElemDef() );
3189 TElemDef& elemPoints = myElemPointIDs.back();
3190 while ( nIt->more() )
3191 elemPoints.push_back( nodePointIDMap[ nIt->next() ]);
3195 myIsBoundaryPointsFound = true;
3197 return setErrorCode( ERR_OK );
3200 //=======================================================================
3201 //function : getSubmeshWithElements
3202 //purpose : return submesh containing elements bound to theBlock in theMesh
3203 //=======================================================================
3205 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3206 const TopoDS_Shape& theShape)
3208 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3209 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3212 if ( theShape.ShapeType() == TopAbs_SHELL )
3214 // look for submesh of VOLUME
3215 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3216 for (; it.More(); it.Next()) {
3217 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3218 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3226 //=======================================================================
3228 //purpose : Compute nodes coordinates applying
3229 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3230 // will be mapped into <theVertex000>. The (0,0,1)
3231 // fifth key-point will be mapped into <theVertex001>.
3232 //=======================================================================
3234 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3235 const TopoDS_Vertex& theVertex000,
3236 const TopoDS_Vertex& theVertex001)
3238 MESSAGE(" ::Apply(volume) " );
3240 if (!findBoundaryPoints() || // bind ID to points
3241 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3244 SMESH_Block block; // bind ID to shape
3245 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3246 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3248 // compute XYZ of points on shapes
3250 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3252 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3253 list< TPoint* >::iterator pIt = shapePoints.begin();
3254 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3255 switch ( S.ShapeType() )
3257 case TopAbs_VERTEX: {
3259 for ( ; pIt != shapePoints.end(); pIt++ )
3260 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3265 for ( ; pIt != shapePoints.end(); pIt++ )
3266 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3271 for ( ; pIt != shapePoints.end(); pIt++ )
3272 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3276 for ( ; pIt != shapePoints.end(); pIt++ )
3277 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3279 } // loop on block sub-shapes
3281 myIsComputed = true;
3283 return setErrorCode( ERR_OK );
3286 //=======================================================================
3288 //purpose : Compute nodes coordinates applying
3289 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3290 // will be mapped into <theNode000Index>-th node. The
3291 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3293 //=======================================================================
3295 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3296 const int theNode000Index,
3297 const int theNode001Index)
3299 //MESSAGE(" ::Apply(MeshVolume) " );
3301 if (!findBoundaryPoints()) // bind ID to points
3304 SMESH_Block block; // bind ID to shape
3305 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3306 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3307 // compute XYZ of points on shapes
3309 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3311 list< TPoint* > & shapePoints = getShapePoints( ID );
3312 list< TPoint* >::iterator pIt = shapePoints.begin();
3314 if ( block.IsVertexID( ID ))
3315 for ( ; pIt != shapePoints.end(); pIt++ ) {
3316 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3318 else if ( block.IsEdgeID( ID ))
3319 for ( ; pIt != shapePoints.end(); pIt++ ) {
3320 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3322 else if ( block.IsFaceID( ID ))
3323 for ( ; pIt != shapePoints.end(); pIt++ ) {
3324 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3327 for ( ; pIt != shapePoints.end(); pIt++ )
3328 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3329 } // loop on block sub-shapes
3331 myIsComputed = true;
3333 return setErrorCode( ERR_OK );
3336 //=======================================================================
3337 //function : mergePoints
3338 //purpose : Merge XYZ on edges and/or faces.
3339 //=======================================================================
3341 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3343 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3344 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3346 list<list< int > >& groups = idListIt->second;
3347 if ( groups.size() < 2 )
3351 const TNodeSet& nodes = idListIt->first;
3352 double tol2 = 1.e-10;
3353 if ( nodes.size() > 1 ) {
3355 TNodeSet::const_iterator n = nodes.begin();
3356 for ( ; n != nodes.end(); ++n )
3357 box.Add( gp_Pnt( (*n)->X(), (*n)->Y(), (*n)->Z() ));
3358 double x, y, z, X, Y, Z;
3359 box.Get( x, y, z, X, Y, Z );
3360 gp_Pnt p( x, y, z ), P( X, Y, Z );
3361 tol2 = 1.e-4 * p.SquareDistance( P );
3364 // to unite groups on link
3365 bool unite = ( uniteGroups && nodes.size() == 2 );
3366 map< double, int > distIndMap;
3367 const SMDS_MeshNode* node = *nodes.begin();
3368 gp_Pnt P( node->X(), node->Y(), node->Z() );
3370 // compare points, replace indices
3372 list< int >::iterator ind1, ind2;
3373 list< list< int > >::iterator grpIt1, grpIt2;
3374 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3376 list< int >& indices1 = *grpIt1;
3378 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3380 list< int >& indices2 = *grpIt2;
3381 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3383 gp_XYZ& p1 = myXYZ[ *ind1 ];
3384 ind2 = indices2.begin();
3385 while ( ind2 != indices2.end() )
3387 gp_XYZ& p2 = myXYZ[ *ind2 ];
3388 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3389 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3391 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3392 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3393 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3394 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3396 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3397 myXYZ[ *ind2 ] = undefinedXYZ();
3398 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3400 ind2 = indices2.erase( ind2 );
3407 if ( unite ) { // sort indices using distIndMap
3408 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3410 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3411 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3412 distIndMap.insert( make_pair( dist, *ind1 ));
3416 if ( unite ) { // put all sorted indices into the first group
3417 list< int >& g = groups.front();
3419 map< double, int >::iterator dist_ind = distIndMap.begin();
3420 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3421 g.push_back( dist_ind->second );
3423 } // loop on myIdsOnBoundary
3426 //=======================================================================
3427 //function : makePolyElements
3428 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3429 //=======================================================================
3431 void SMESH_Pattern::
3432 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3433 const bool toCreatePolygons,
3434 const bool toCreatePolyedrs)
3436 myPolyElemXYZIDs.clear();
3437 myPolyElems.clear();
3438 myPolyElems.reserve( myIdsOnBoundary.size() );
3440 // make a set of refined elements
3441 TIDSortedElemSet avoidSet, elemSet;
3442 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3443 for(; itv!=myElements.end(); itv++) {
3444 const SMDS_MeshElement* el = (*itv);
3445 avoidSet.insert( el );
3447 //avoidSet.insert( myElements.begin(), myElements.end() );
3449 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3451 if ( toCreatePolygons )
3453 int lastFreeId = myXYZ.size();
3455 // loop on links of refined elements
3456 indListIt = myIdsOnBoundary.begin();
3457 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3459 const TNodeSet & linkNodes = indListIt->first;
3460 if ( linkNodes.size() != 2 )
3461 continue; // skip face
3462 const SMDS_MeshNode* n1 = * linkNodes.begin();
3463 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3465 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3466 if ( idGroups.empty() || idGroups.front().empty() )
3469 // find not refined face having n1-n2 link
3473 const SMDS_MeshElement* face =
3474 SMESH_MeshEditor::FindFaceInSet( n1, n2, elemSet, avoidSet );
3477 avoidSet.insert ( face );
3478 myPolyElems.push_back( face );
3480 // some links of <face> are split;
3481 // make list of xyz for <face>
3482 myPolyElemXYZIDs.push_back(TElemDef());
3483 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3484 // loop on links of a <face>
3485 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3486 int i = 0, nbNodes = face->NbNodes();
3487 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3488 while ( nIt->more() )
3489 nodes[ i++ ] = smdsNode( nIt->next() );
3490 nodes[ i ] = nodes[ 0 ];
3491 for ( i = 0; i < nbNodes; ++i )
3493 // look for point mapped on a link
3494 TNodeSet faceLinkNodes;
3495 faceLinkNodes.insert( nodes[ i ] );
3496 faceLinkNodes.insert( nodes[ i + 1 ] );
3497 if ( faceLinkNodes == linkNodes )
3498 nn_IdList = indListIt;
3500 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3501 // add face point ids
3502 faceNodeIds.push_back( ++lastFreeId );
3503 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3504 if ( nn_IdList != myIdsOnBoundary.end() )
3506 // there are points mapped on a link
3507 list< int >& mappedIds = nn_IdList->second.front();
3508 if ( isReversed( nodes[ i ], mappedIds ))
3509 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3511 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3513 } // loop on links of a <face>
3519 if ( myIs2D && idGroups.size() > 1 ) {
3521 // sew new elements on 2 refined elements sharing n1-n2 link
3523 list< int >& idsOnLink = idGroups.front();
3524 // temporarily add ids of link nodes to idsOnLink
3525 bool rev = isReversed( n1, idsOnLink );
3526 for ( int i = 0; i < 2; ++i )
3529 nodeSet.insert( i ? n2 : n1 );
3530 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3531 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3532 int nodeId = groups.front().front();
3534 if ( rev ) append = !append;
3536 idsOnLink.push_back( nodeId );
3538 idsOnLink.push_front( nodeId );
3540 list< int >::iterator id = idsOnLink.begin();
3541 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3543 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3544 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3545 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3547 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3548 // look for <id> in element definition
3549 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3550 ASSERT ( idDef != pIdList->end() );
3551 // look for 2 neighbour ids of <id> in element definition
3552 for ( int prev = 0; prev < 2; ++prev ) {
3553 TElemDef::iterator idDef2 = idDef;
3555 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3557 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3558 // look for idDef2 on a link starting from id
3559 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3560 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3561 // insert ids located on link between <id> and <id2>
3562 // into the element definition between idDef and idDef2
3564 for ( ; id2 != id; --id2 )
3565 pIdList->insert( idDef, *id2 );
3567 list< int >::iterator id1 = id;
3568 for ( ++id1, ++id2; id1 != id2; ++id1 )
3569 pIdList->insert( idDef2, *id1 );
3575 // remove ids of link nodes
3576 idsOnLink.pop_front();
3577 idsOnLink.pop_back();
3579 } // loop on myIdsOnBoundary
3580 } // if ( toCreatePolygons )
3582 if ( toCreatePolyedrs )
3584 // check volumes adjacent to the refined elements
3585 SMDS_VolumeTool volTool;
3586 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3587 for ( ; refinedElem != myElements.end(); ++refinedElem )
3589 // loop on nodes of refinedElem
3590 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3591 while ( nIt->more() ) {
3592 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3593 // loop on inverse elements of node
3594 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3595 while ( eIt->more() )
3597 const SMDS_MeshElement* elem = eIt->next();
3598 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3599 continue; // skip faces or refined elements
3600 // add polyhedron definition
3601 myPolyhedronQuantities.push_back(vector<int> ());
3602 myPolyElemXYZIDs.push_back(TElemDef());
3603 vector<int>& quantity = myPolyhedronQuantities.back();
3604 TElemDef & elemDef = myPolyElemXYZIDs.back();
3605 // get definitions of new elements on volume faces
3606 bool makePoly = false;
3607 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3609 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3610 volTool.NbFaceNodes( iF ),
3611 theNodes, elemDef, quantity))
3615 myPolyElems.push_back( elem );
3617 myPolyhedronQuantities.pop_back();
3618 myPolyElemXYZIDs.pop_back();
3626 //=======================================================================
3627 //function : getFacesDefinition
3628 //purpose : return faces definition for a volume face defined by theBndNodes
3629 //=======================================================================
3631 bool SMESH_Pattern::
3632 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3633 const int theNbBndNodes,
3634 const vector< const SMDS_MeshNode* >& theNodes,
3635 list< int >& theFaceDefs,
3636 vector<int>& theQuantity)
3638 bool makePoly = false;
3639 // cout << "FROM FACE NODES: " <<endl;
3640 // for ( int i = 0; i < theNbBndNodes; ++i )
3641 // cout << theBndNodes[ i ];
3643 set< const SMDS_MeshNode* > bndNodeSet;
3644 for ( int i = 0; i < theNbBndNodes; ++i )
3645 bndNodeSet.insert( theBndNodes[ i ]);
3647 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3649 // make a set of all nodes on a face
3651 if ( !myIs2D ) { // for 2D, merge only edges
3652 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3653 if ( nn_IdList != myIdsOnBoundary.end() ) {
3655 list< int > & faceIds = nn_IdList->second.front();
3656 ids.insert( faceIds.begin(), faceIds.end() );
3659 //bool hasIdsInFace = !ids.empty();
3661 // add ids on links and bnd nodes
3662 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3663 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3664 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3666 // add id of iN-th bnd node
3668 nSet.insert( theBndNodes[ iN ] );
3669 nn_IdList = myIdsOnBoundary.find( nSet );
3670 int bndId = ++lastFreeId;
3671 if ( nn_IdList != myIdsOnBoundary.end() ) {
3672 bndId = nn_IdList->second.front().front();
3673 ids.insert( bndId );
3676 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3677 faceDef.push_back( bndId );
3678 // add ids on a link
3680 linkNodes.insert( theBndNodes[ iN ]);
3681 linkNodes.insert( theBndNodes[ iN + 1 == theNbBndNodes ? 0 : iN + 1 ]);
3682 nn_IdList = myIdsOnBoundary.find( linkNodes );
3683 if ( nn_IdList != myIdsOnBoundary.end() ) {
3685 list< int > & linkIds = nn_IdList->second.front();
3686 ids.insert( linkIds.begin(), linkIds.end() );
3687 if ( isReversed( theBndNodes[ iN ], linkIds ))
3688 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3690 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3694 // find faces definition of new volumes
3696 bool defsAdded = false;
3697 if ( !myIs2D ) { // for 2D, merge only edges
3698 SMDS_VolumeTool vol;
3699 set< TElemDef* > checkedVolDefs;
3700 set< int >::iterator id = ids.begin();
3701 for ( ; id != ids.end(); ++id )
3703 // definitions of volumes sharing id
3704 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3705 ASSERT( !defList.empty() );
3706 // loop on volume definitions
3707 list< TElemDef* >::iterator pIdList = defList.begin();
3708 for ( ; pIdList != defList.end(); ++pIdList)
3710 if ( !checkedVolDefs.insert( *pIdList ).second )
3711 continue; // skip already checked volume definition
3712 vector< int > idVec;
3713 idVec.reserve( (*pIdList)->size() );
3714 idVec.insert( idVec.begin(), (*pIdList)->begin(), (*pIdList)->end() );
3715 // loop on face defs of a volume
3716 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3717 if ( volType == SMDS_VolumeTool::UNKNOWN )
3719 int nbFaces = vol.NbFaces( volType );
3720 for ( int iF = 0; iF < nbFaces; ++iF )
3722 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3723 int iN, nbN = vol.NbFaceNodes( volType, iF );
3724 // check if all nodes of a faces are in <ids>
3726 for ( iN = 0; iN < nbN && all; ++iN ) {
3727 int nodeId = idVec[ nodeInds[ iN ]];
3728 all = ( ids.find( nodeId ) != ids.end() );
3731 // store a face definition
3732 for ( iN = 0; iN < nbN; ++iN ) {
3733 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3735 theQuantity.push_back( nbN );
3743 theQuantity.push_back( faceDef.size() );
3744 theFaceDefs.splice( theFaceDefs.end(), faceDef, faceDef.begin(), faceDef.end() );
3750 //=======================================================================
3751 //function : clearSubMesh
3753 //=======================================================================
3755 static bool clearSubMesh( SMESH_Mesh* theMesh,
3756 const TopoDS_Shape& theShape)
3758 bool removed = false;
3759 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3761 if ( aSubMesh->GetSubMeshDS() ) {
3763 aSubMesh->GetSubMeshDS()->NbElements() || aSubMesh->GetSubMeshDS()->NbNodes();
3764 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3768 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3769 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3771 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3772 removed = eIt->more();
3773 while ( eIt->more() )
3774 aMeshDS->RemoveElement( eIt->next() );
3775 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3776 removed = removed || nIt->more();
3777 while ( nIt->more() )
3778 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3784 //=======================================================================
3785 //function : clearMesh
3786 //purpose : clear mesh elements existing on myShape in theMesh
3787 //=======================================================================
3789 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3792 if ( !myShape.IsNull() )
3794 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3795 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3796 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3798 clearSubMesh( theMesh, it.Value() );
3804 //=======================================================================
3805 //function : MakeMesh
3806 //purpose : Create nodes and elements in <theMesh> using nodes
3807 // coordinates computed by either of Apply...() methods
3808 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3809 // it does not care of nodes and elements already existing on
3810 // subshapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3811 //=======================================================================
3813 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3814 const bool toCreatePolygons,
3815 const bool toCreatePolyedrs)
3817 MESSAGE(" ::MakeMesh() " );
3818 if ( !myIsComputed )
3819 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3821 mergePoints( toCreatePolygons );
3823 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3825 // clear elements and nodes existing on myShape
3828 bool onMeshElements = ( !myElements.empty() );
3830 // Create missing nodes
3832 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3833 if ( onMeshElements )
3835 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3836 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3837 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3838 nodesVector[ i_node->first ] = i_node->second;
3840 for ( int i = 0; i < myXYZ.size(); ++i ) {
3841 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3842 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3849 nodesVector.resize( myPoints.size(), 0 );
3851 // to find point index
3852 map< TPoint*, int > pointIndex;
3853 for ( int i = 0; i < myPoints.size(); i++ )
3854 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3856 // loop on sub-shapes of myShape: create nodes
3857 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3858 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3861 //SMESHDS_SubMesh * subMeshDS = 0;
3862 if ( !myShapeIDMap.IsEmpty() ) {
3863 S = myShapeIDMap( idPointIt->first );
3864 //subMeshDS = aMeshDS->MeshElements( S );
3866 list< TPoint* > & points = idPointIt->second;
3867 list< TPoint* >::iterator pIt = points.begin();
3868 for ( ; pIt != points.end(); pIt++ )
3870 TPoint* point = *pIt;
3871 int pIndex = pointIndex[ point ];
3872 if ( nodesVector [ pIndex ] )
3874 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
3877 nodesVector [ pIndex ] = node;
3879 if ( true /*subMeshDS*/ ) {
3880 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
3881 switch ( S.ShapeType() ) {
3882 case TopAbs_VERTEX: {
3883 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
3886 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
3889 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
3890 point->myUV.X(), point->myUV.Y() ); break;
3893 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
3902 if ( onMeshElements )
3904 // prepare data to create poly elements
3905 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
3908 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
3909 // sew old and new elements
3910 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
3914 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
3917 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
3918 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
3919 // for ( ; i_sm != sm.end(); i_sm++ )
3921 // cout << " SM " << i_sm->first << " ";
3922 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
3923 // //SMDS_ElemIteratorPtr GetElements();
3924 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
3925 // while ( nit->more() )
3926 // cout << nit->next()->GetID() << " ";
3929 return setErrorCode( ERR_OK );
3932 //=======================================================================
3933 //function : createElements
3934 //purpose : add elements to the mesh
3935 //=======================================================================
3937 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
3938 const vector<const SMDS_MeshNode* >& theNodesVector,
3939 const list< TElemDef > & theElemNodeIDs,
3940 const vector<const SMDS_MeshElement*>& theElements)
3942 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3943 SMESH_MeshEditor editor( theMesh );
3945 bool onMeshElements = !theElements.empty();
3947 // shapes and groups theElements are on
3948 vector< int > shapeIDs;
3949 vector< list< SMESHDS_Group* > > groups;
3950 set< const SMDS_MeshNode* > shellNodes;
3951 if ( onMeshElements )
3953 shapeIDs.resize( theElements.size() );
3954 groups.resize( theElements.size() );
3955 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
3956 set<SMESHDS_GroupBase*>::const_iterator grIt;
3957 for ( int i = 0; i < theElements.size(); i++ )
3959 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
3960 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
3961 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
3962 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
3963 groups[ i ].push_back( group );
3966 // get all nodes bound to shells because their SpacePosition is not set
3967 // by SMESHDS_Mesh::SetNodeInVolume()
3968 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
3969 if ( !aMainShape.IsNull() ) {
3970 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
3971 for ( ; shellExp.More(); shellExp.Next() )
3973 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
3975 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
3976 while ( nIt->more() )
3977 shellNodes.insert( nIt->next() );
3982 // nb new elements per a refined element
3983 int nbNewElemsPerOld = 1;
3984 if ( onMeshElements )
3985 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
3989 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
3990 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
3991 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
3993 const TElemDef & elemNodeInd = *enIt;
3995 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
3996 TElemDef::const_iterator id = elemNodeInd.begin();
3998 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
3999 if ( *id < theNodesVector.size() )
4000 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4002 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4004 // dim of refined elem
4005 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4006 if ( onMeshElements ) {
4007 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4010 const SMDS_MeshElement* elem = 0;
4012 switch ( nbNodes ) {
4014 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4016 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4018 if ( !onMeshElements ) {// create a quadratic face
4019 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4020 nodes[4], nodes[5] ); break;
4021 } // else do not break but create a polygon
4023 if ( !onMeshElements ) {// create a quadratic face
4024 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4025 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4026 } // else do not break but create a polygon
4028 elem = aMeshDS->AddPolygonalFace( nodes );
4032 switch ( nbNodes ) {
4034 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4036 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4039 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4040 nodes[4], nodes[5] ); break;
4042 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4043 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4045 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4048 // set element on a shape
4049 if ( elem && onMeshElements ) // applied to mesh elements
4051 int shapeID = shapeIDs[ elemIndex ];
4052 if ( shapeID > 0 ) {
4053 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4054 // set nodes on a shape
4055 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4056 if ( S.ShapeType() == TopAbs_SOLID ) {
4057 TopoDS_Iterator shellIt( S );
4058 if ( shellIt.More() )
4059 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4061 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4062 while ( noIt->more() ) {
4063 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4064 if (!node->GetPosition()->GetShapeId() &&
4065 shellNodes.find( node ) == shellNodes.end() ) {
4066 if ( S.ShapeType() == TopAbs_FACE )
4067 aMeshDS->SetNodeOnFace( node, shapeID );
4069 aMeshDS->SetNodeInVolume( node, shapeID );
4070 shellNodes.insert( node );
4075 // add elem in groups
4076 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4077 for ( ; g != groups[ elemIndex ].end(); ++g )
4078 (*g)->SMDSGroup().Add( elem );
4080 if ( elem && !myShape.IsNull() ) // applied to shape
4081 aMeshDS->SetMeshElementOnShape( elem, myShape );
4084 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4085 // so that operations with hypotheses will erase the mesh being built
4087 SMESH_subMesh * subMesh;
4088 if ( !myShape.IsNull() ) {
4089 subMesh = theMesh->GetSubMesh( myShape );
4091 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4093 if ( onMeshElements ) {
4094 list< int > elemIDs;
4095 for ( int i = 0; i < theElements.size(); i++ )
4097 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4099 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4101 elemIDs.push_back( theElements[ i ]->GetID() );
4103 // remove refined elements
4104 editor.Remove( elemIDs, false );
4108 //=======================================================================
4109 //function : isReversed
4110 //purpose : check xyz ids order in theIdsList taking into account
4111 // theFirstNode on a link
4112 //=======================================================================
4114 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4115 const list< int >& theIdsList) const
4117 if ( theIdsList.size() < 2 )
4120 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4122 list<int>::const_iterator id = theIdsList.begin();
4123 for ( int i = 0; i < 2; ++i, ++id ) {
4124 if ( *id < myXYZ.size() )
4125 P[ i ] = myXYZ[ *id ];
4127 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4128 i_n = myXYZIdToNodeMap.find( *id );
4129 ASSERT( i_n != myXYZIdToNodeMap.end() );
4130 const SMDS_MeshNode* n = i_n->second;
4131 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4134 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4138 //=======================================================================
4139 //function : arrangeBoundaries
4140 //purpose : if there are several wires, arrange boundaryPoints so that
4141 // the outer wire goes first and fix inner wires orientation
4142 // update myKeyPointIDs to correspond to the order of key-points
4143 // in boundaries; sort internal boundaries by the nb of key-points
4144 //=======================================================================
4146 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4148 typedef list< list< TPoint* > >::iterator TListOfListIt;
4149 TListOfListIt bndIt;
4150 list< TPoint* >::iterator pIt;
4152 int nbBoundaries = boundaryList.size();
4153 if ( nbBoundaries > 1 )
4155 // sort boundaries by nb of key-points
4156 if ( nbBoundaries > 2 )
4158 // move boundaries in tmp list
4159 list< list< TPoint* > > tmpList;
4160 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4161 // make a map nb-key-points to boundary-position-in-tmpList,
4162 // boundary-positions get ordered in it
4163 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4164 TNbKpBndPosMap nbKpBndPosMap;
4165 bndIt = tmpList.begin();
4166 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4167 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4168 int nb = *nbKpIt * nbBoundaries;
4169 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4171 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4173 // move boundaries back to boundaryList
4174 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4175 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4176 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4177 TListOfListIt bndPos1 = bndPos2++;
4178 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4182 // Look for the outer boundary: the one with the point with the least X
4183 double leastX = DBL_MAX;
4184 TListOfListIt outerBndPos;
4185 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4187 list< TPoint* >& boundary = (*bndIt);
4188 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4190 TPoint* point = *pIt;
4191 if ( point->myInitXYZ.X() < leastX ) {
4192 leastX = point->myInitXYZ.X();
4193 outerBndPos = bndIt;
4198 if ( outerBndPos != boundaryList.begin() )
4199 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4201 } // if nbBoundaries > 1
4203 // Check boundaries orientation and re-fill myKeyPointIDs
4205 set< TPoint* > keyPointSet;
4206 list< int >::iterator kpIt = myKeyPointIDs.begin();
4207 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4208 keyPointSet.insert( & myPoints[ *kpIt ]);
4209 myKeyPointIDs.clear();
4211 // update myNbKeyPntInBoundary also
4212 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4214 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4216 // find the point with the least X
4217 double leastX = DBL_MAX;
4218 list< TPoint* >::iterator xpIt;
4219 list< TPoint* >& boundary = (*bndIt);
4220 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4222 TPoint* point = *pIt;
4223 if ( point->myInitXYZ.X() < leastX ) {
4224 leastX = point->myInitXYZ.X();
4228 // find points next to the point with the least X
4229 TPoint* p = *xpIt, *pPrev, *pNext;
4230 if ( p == boundary.front() )
4231 pPrev = *(++boundary.rbegin());
4237 if ( p == boundary.back() )
4238 pNext = *(++boundary.begin());
4243 // vectors of boundary direction near <p>
4244 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4245 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4246 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4247 double yPrev = v1.Y() / sqrt( sqMag1 );
4248 double yNext = v2.Y() / sqrt( sqMag2 );
4249 double sumY = yPrev + yNext;
4251 if ( bndIt == boundaryList.begin() ) // outer boundary
4259 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4260 (*nbKpIt) = 0; // count nb of key-points again
4261 pIt = boundary.begin();
4262 for ( ; pIt != boundary.end(); pIt++)
4264 TPoint* point = *pIt;
4265 if ( keyPointSet.find( point ) == keyPointSet.end() )
4267 // find an index of a keypoint
4269 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4270 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4271 if ( &(*pVecIt) == point )
4273 myKeyPointIDs.push_back( index );
4276 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4279 } // loop on a list of boundaries
4281 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4284 //=======================================================================
4285 //function : findBoundaryPoints
4286 //purpose : if loaded from file, find points to map on edges and faces and
4287 // compute their parameters
4288 //=======================================================================
4290 bool SMESH_Pattern::findBoundaryPoints()
4292 if ( myIsBoundaryPointsFound ) return true;
4294 MESSAGE(" findBoundaryPoints() ");
4296 myNbKeyPntInBoundary.clear();
4300 set< TPoint* > pointsInElems;
4302 // Find free links of elements:
4303 // put links of all elements in a set and remove links encountered twice
4305 typedef pair< TPoint*, TPoint*> TLink;
4306 set< TLink > linkSet;
4307 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4308 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4310 TElemDef & elemPoints = *epIt;
4311 TElemDef::iterator pIt = elemPoints.begin();
4312 int prevP = elemPoints.back();
4313 for ( ; pIt != elemPoints.end(); pIt++ ) {
4314 TPoint* p1 = & myPoints[ prevP ];
4315 TPoint* p2 = & myPoints[ *pIt ];
4316 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4317 ASSERT( link.first != link.second );
4318 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4319 if ( !itUniq.second )
4320 linkSet.erase( itUniq.first );
4323 pointsInElems.insert( p1 );
4326 // Now linkSet contains only free links,
4327 // find the points order that they have in boundaries
4329 // 1. make a map of key-points
4330 set< TPoint* > keyPointSet;
4331 list< int >::iterator kpIt = myKeyPointIDs.begin();
4332 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4333 keyPointSet.insert( & myPoints[ *kpIt ]);
4335 // 2. chain up boundary points
4336 list< list< TPoint* > > boundaryList;
4337 boundaryList.push_back( list< TPoint* >() );
4338 list< TPoint* > * boundary = & boundaryList.back();
4340 TPoint *point1, *point2, *keypoint1;
4341 kpIt = myKeyPointIDs.begin();
4342 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4343 // loop on free links: look for the next point
4345 set< TLink >::iterator lIt = linkSet.begin();
4346 while ( lIt != linkSet.end() )
4348 if ( (*lIt).first == point1 )
4349 point2 = (*lIt).second;
4350 else if ( (*lIt).second == point1 )
4351 point2 = (*lIt).first;
4356 linkSet.erase( lIt );
4357 lIt = linkSet.begin();
4359 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4361 boundary->push_back( point2 );
4363 else // a key-point found
4365 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4367 if ( point2 != keypoint1 ) // its not the boundary end
4369 boundary->push_back( point2 );
4371 else // the boundary end reached
4373 boundary->push_front( keypoint1 );
4374 boundary->push_back( keypoint1 );
4375 myNbKeyPntInBoundary.push_back( iKeyPoint );
4376 if ( keyPointSet.empty() )
4377 break; // all boundaries containing key-points are found
4379 // prepare to search for the next boundary
4380 boundaryList.push_back( list< TPoint* >() );
4381 boundary = & boundaryList.back();
4382 point2 = keypoint1 = (*keyPointSet.begin());
4386 } // loop on the free links set
4388 if ( boundary->empty() ) {
4389 MESSAGE(" a separate key-point");
4390 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4393 // if there are several wires, arrange boundaryPoints so that
4394 // the outer wire goes first and fix inner wires orientation;
4395 // sort myKeyPointIDs to correspond to the order of key-points
4397 arrangeBoundaries( boundaryList );
4399 // Find correspondence shape ID - points,
4400 // compute points parameter on edge
4402 keyPointSet.clear();
4403 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4404 keyPointSet.insert( & myPoints[ *kpIt ]);
4406 set< TPoint* > edgePointSet; // to find in-face points
4407 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4408 int edgeID = myKeyPointIDs.size() + 1;
4410 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4411 for ( ; bndIt != boundaryList.end(); bndIt++ )
4413 boundary = & (*bndIt);
4414 double edgeLength = 0;
4415 list< TPoint* >::iterator pIt = boundary->begin();
4416 getShapePoints( edgeID ).push_back( *pIt );
4417 getShapePoints( vertexID++ ).push_back( *pIt );
4418 for ( pIt++; pIt != boundary->end(); pIt++)
4420 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4421 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4422 TPoint* point = *pIt;
4423 edgePointSet.insert( point );
4424 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4426 edgePoints.push_back( point );
4427 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4428 point->myInitU = edgeLength;
4432 // treat points on the edge which ends up: compute U [0,1]
4433 edgePoints.push_back( point );
4434 if ( edgePoints.size() > 2 ) {
4435 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4436 list< TPoint* >::iterator epIt = edgePoints.begin();
4437 for ( ; epIt != edgePoints.end(); epIt++ )
4438 (*epIt)->myInitU /= edgeLength;
4440 // begin the next edge treatment
4443 if ( point != boundary->front() ) { // not the first key-point again
4444 getShapePoints( edgeID ).push_back( point );
4445 getShapePoints( vertexID++ ).push_back( point );
4451 // find in-face points
4452 list< TPoint* > & facePoints = getShapePoints( edgeID );
4453 vector< TPoint >::iterator pVecIt = myPoints.begin();
4454 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4455 TPoint* point = &(*pVecIt);
4456 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4457 pointsInElems.find( point ) != pointsInElems.end())
4458 facePoints.push_back( point );
4465 // bind points to shapes according to point parameters
4466 vector< TPoint >::iterator pVecIt = myPoints.begin();
4467 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4468 TPoint* point = &(*pVecIt);
4469 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4470 getShapePoints( shapeID ).push_back( point );
4471 // detect key-points
4472 if ( SMESH_Block::IsVertexID( shapeID ))
4473 myKeyPointIDs.push_back( i );
4477 myIsBoundaryPointsFound = true;
4478 return myIsBoundaryPointsFound;
4481 //=======================================================================
4483 //purpose : clear fields
4484 //=======================================================================
4486 void SMESH_Pattern::Clear()
4488 myIsComputed = myIsBoundaryPointsFound = false;
4491 myKeyPointIDs.clear();
4492 myElemPointIDs.clear();
4493 myShapeIDToPointsMap.clear();
4494 myShapeIDMap.Clear();
4496 myNbKeyPntInBoundary.clear();
4499 //=======================================================================
4500 //function : setShapeToMesh
4501 //purpose : set a shape to be meshed. Return True if meshing is possible
4502 //=======================================================================
4504 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4506 if ( !IsLoaded() ) {
4507 MESSAGE( "Pattern not loaded" );
4508 return setErrorCode( ERR_APPL_NOT_LOADED );
4511 TopAbs_ShapeEnum aType = theShape.ShapeType();
4512 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4514 MESSAGE( "Pattern dimention mismatch" );
4515 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4518 // check if a face is closed
4519 int nbNodeOnSeamEdge = 0;
4521 TopoDS_Face face = TopoDS::Face( theShape );
4522 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4523 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() )
4524 if ( BRep_Tool::IsClosed( TopoDS::Edge( eExp.Current() ), face ))
4525 nbNodeOnSeamEdge = 2;
4528 // check nb of vertices
4529 TopTools_IndexedMapOfShape vMap;
4530 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4531 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4532 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4533 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4536 myElements.clear(); // not refine elements
4537 myElemXYZIDs.clear();
4539 myShapeIDMap.Clear();
4544 //=======================================================================
4545 //function : GetMappedPoints
4546 //purpose : Return nodes coordinates computed by Apply() method
4547 //=======================================================================
4549 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4552 if ( !myIsComputed )
4555 if ( myElements.empty() ) { // applied to shape
4556 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4557 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4558 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4560 else { // applied to mesh elements
4561 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4562 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4563 for ( ; xyz != myXYZ.end(); ++xyz )
4564 if ( !isDefined( *xyz ))
4565 thePoints.push_back( definedXYZ );
4567 thePoints.push_back( & (*xyz) );
4569 return !thePoints.empty();
4573 //=======================================================================
4574 //function : GetPoints
4575 //purpose : Return nodes coordinates of the pattern
4576 //=======================================================================
4578 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4585 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4586 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4587 thePoints.push_back( & (*pVecIt).myInitXYZ );
4589 return ( thePoints.size() > 0 );
4592 //=======================================================================
4593 //function : getShapePoints
4594 //purpose : return list of points located on theShape
4595 //=======================================================================
4597 list< SMESH_Pattern::TPoint* > &
4598 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4601 if ( !myShapeIDMap.Contains( theShape ))
4602 aShapeID = myShapeIDMap.Add( theShape );
4604 aShapeID = myShapeIDMap.FindIndex( theShape );
4606 return myShapeIDToPointsMap[ aShapeID ];
4609 //=======================================================================
4610 //function : getShapePoints
4611 //purpose : return list of points located on the shape
4612 //=======================================================================
4614 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4616 return myShapeIDToPointsMap[ theShapeID ];
4619 //=======================================================================
4620 //function : DumpPoints
4622 //=======================================================================
4624 void SMESH_Pattern::DumpPoints() const
4627 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4628 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4629 cout << i << ": " << *pVecIt;
4633 //=======================================================================
4634 //function : TPoint()
4636 //=======================================================================
4638 SMESH_Pattern::TPoint::TPoint()
4641 myInitXYZ.SetCoord(0,0,0);
4642 myInitUV.SetCoord(0.,0.);
4644 myXYZ.SetCoord(0,0,0);
4645 myUV.SetCoord(0.,0.);
4650 //=======================================================================
4651 //function : operator <<
4653 //=======================================================================
4655 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4657 gp_XYZ xyz = p.myInitXYZ;
4658 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4659 gp_XY xy = p.myInitUV;
4660 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4661 double u = p.myInitU;
4662 OS << " u( " << u << " )) " << &p << endl;
4663 xyz = p.myXYZ.XYZ();
4664 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4666 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4668 OS << " u( " << u << " ))" << endl;