1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_Pattern.hxx
24 // Created : Mon Aug 2 10:30:00 2004
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_Pattern.hxx"
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshFace.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESHDS_SubMesh.hxx"
38 #include "SMESH_Block.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_subMesh.hxx"
44 #include <BRepAdaptor_Curve.hxx>
45 #include <BRepTools.hxx>
46 #include <BRepTools_WireExplorer.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_Box.hxx>
49 #include <Bnd_Box2d.hxx>
51 #include <Extrema_ExtPC.hxx>
52 #include <Extrema_GenExtPS.hxx>
53 #include <Extrema_POnSurf.hxx>
54 #include <Geom2d_Curve.hxx>
55 #include <GeomAdaptor_Surface.hxx>
56 #include <Geom_Curve.hxx>
57 #include <Geom_Surface.hxx>
58 #include <Precision.hxx>
59 #include <TopAbs_ShapeEnum.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <TopLoc_Location.hxx>
63 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopoDS_Edge.hxx>
66 #include <TopoDS_Face.hxx>
67 #include <TopoDS_Iterator.hxx>
68 #include <TopoDS_Shell.hxx>
69 #include <TopoDS_Vertex.hxx>
70 #include <TopoDS_Wire.hxx>
72 #include <gp_Lin2d.hxx>
73 #include <gp_Pnt2d.hxx>
74 #include <gp_Trsf.hxx>
78 #include <Basics_OCCTVersion.hxx>
80 #include <Basics_Utils.hxx>
81 #include "utilities.h"
85 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
87 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
89 //=======================================================================
90 //function : SMESH_Pattern
92 //=======================================================================
94 SMESH_Pattern::SMESH_Pattern ()
97 //=======================================================================
100 //=======================================================================
102 static inline int getInt( const char * theSring )
104 if ( *theSring < '0' || *theSring > '9' )
108 int val = strtol( theSring, &ptr, 10 );
109 if ( ptr == theSring ||
110 // there must not be neither '.' nor ',' nor 'E' ...
111 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
117 //=======================================================================
118 //function : getDouble
120 //=======================================================================
122 static inline double getDouble( const char * theSring )
125 return strtod( theSring, &ptr );
128 //=======================================================================
129 //function : readLine
130 //purpose : Put token starting positions in theFields until '\n' or '\0'
131 // Return the number of the found tokens
132 //=======================================================================
134 static int readLine (list <const char*> & theFields,
135 const char* & theLineBeg,
136 const bool theClearFields )
138 if ( theClearFields )
143 /* switch ( symbol ) { */
144 /* case white-space: */
145 /* look for a non-space symbol; */
146 /* case string-end: */
149 /* case comment beginning: */
150 /* skip all till a line-end; */
152 /* put its position in theFields, skip till a white-space;*/
158 bool stopReading = false;
161 bool isNumber = false;
162 switch ( *theLineBeg )
164 case ' ': // white space
169 case '\n': // a line ends
170 stopReading = ( nbRead > 0 );
175 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
179 case '\0': // file ends
182 case '-': // real number
187 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
189 theFields.push_back( theLineBeg );
192 while (*theLineBeg != ' ' &&
193 *theLineBeg != '\n' &&
194 *theLineBeg != '\0');
198 return 0; // incorrect file format
204 } while ( !stopReading );
209 //=======================================================================
211 //purpose : Load a pattern from <theFile>
212 //=======================================================================
214 bool SMESH_Pattern::Load (const char* theFileContents)
216 MESSAGE("Load( file ) ");
218 Kernel_Utils::Localizer loc;
222 // ! This is a comment
223 // NB_POINTS ! 1 integer - the number of points in the pattern.
224 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
225 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
227 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
228 // ! elements description goes after all
229 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
234 const char* lineBeg = theFileContents;
235 list <const char*> fields;
236 const bool clearFields = true;
238 // NB_POINTS ! 1 integer - the number of points in the pattern.
240 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
241 MESSAGE("Error reading NB_POINTS");
242 return setErrorCode( ERR_READ_NB_POINTS );
244 int nbPoints = getInt( fields.front() );
246 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
248 // read the first point coordinates to define pattern dimention
249 int dim = readLine( fields, lineBeg, clearFields );
255 MESSAGE("Error reading points: wrong nb of coordinates");
256 return setErrorCode( ERR_READ_POINT_COORDS );
258 if ( nbPoints <= dim ) {
259 MESSAGE(" Too few points ");
260 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
263 // read the rest points
265 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
266 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
267 MESSAGE("Error reading points : wrong nb of coordinates ");
268 return setErrorCode( ERR_READ_POINT_COORDS );
270 // store point coordinates
271 myPoints.resize( nbPoints );
272 list <const char*>::iterator fIt = fields.begin();
273 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
275 TPoint & p = myPoints[ iPoint ];
276 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
278 double coord = getDouble( *fIt );
279 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
280 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
282 return setErrorCode( ERR_READ_3D_COORD );
284 p.myInitXYZ.SetCoord( iCoord, coord );
286 p.myInitUV.SetCoord( iCoord, coord );
290 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
293 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
294 MESSAGE("Error: missing key-points");
296 return setErrorCode( ERR_READ_NO_KEYPOINT );
299 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
301 int pointIndex = getInt( *fIt );
302 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
303 MESSAGE("Error: invalid point index " << pointIndex );
305 return setErrorCode( ERR_READ_BAD_INDEX );
307 if ( idSet.insert( pointIndex ).second ) // unique?
308 myKeyPointIDs.push_back( pointIndex );
312 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
314 while ( readLine( fields, lineBeg, clearFields ))
316 myElemPointIDs.push_back( TElemDef() );
317 TElemDef& elemPoints = myElemPointIDs.back();
318 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
320 int pointIndex = getInt( *fIt );
321 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
322 MESSAGE("Error: invalid point index " << pointIndex );
324 return setErrorCode( ERR_READ_BAD_INDEX );
326 elemPoints.push_back( pointIndex );
328 // check the nb of nodes in element
330 switch ( elemPoints.size() ) {
331 case 3: if ( !myIs2D ) Ok = false; break;
335 case 8: if ( myIs2D ) Ok = false; break;
339 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
341 return setErrorCode( ERR_READ_ELEM_POINTS );
344 if ( myElemPointIDs.empty() ) {
345 MESSAGE("Error: no elements");
347 return setErrorCode( ERR_READ_NO_ELEMS );
350 findBoundaryPoints(); // sort key-points
352 return setErrorCode( ERR_OK );
355 //=======================================================================
357 //purpose : Save the loaded pattern into the file <theFileName>
358 //=======================================================================
360 bool SMESH_Pattern::Save (ostream& theFile)
362 MESSAGE(" ::Save(file) " );
364 Kernel_Utils::Localizer loc;
367 MESSAGE(" Pattern not loaded ");
368 return setErrorCode( ERR_SAVE_NOT_LOADED );
371 theFile << "!!! SALOME Mesh Pattern file" << endl;
372 theFile << "!!!" << endl;
373 theFile << "!!! Nb of points:" << endl;
374 theFile << myPoints.size() << endl;
378 // theFile.width( 8 );
379 // theFile.setf(ios::fixed);// use 123.45 floating notation
380 // theFile.setf(ios::right);
381 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
382 // theFile.setf(ios::showpoint); // do not show trailing zeros
383 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
384 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
385 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
386 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
387 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
388 theFile << " !- " << i << endl; // point id to ease reading by a human being
392 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
393 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
394 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
395 theFile << " " << *kpIt;
396 if ( !myKeyPointIDs.empty() )
400 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
401 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
402 for ( ; epIt != myElemPointIDs.end(); epIt++ )
404 const TElemDef & elemPoints = *epIt;
405 TElemDef::const_iterator iIt = elemPoints.begin();
406 for ( ; iIt != elemPoints.end(); iIt++ )
407 theFile << " " << *iIt;
413 return setErrorCode( ERR_OK );
416 //=======================================================================
417 //function : sortBySize
418 //purpose : sort theListOfList by size
419 //=======================================================================
421 template<typename T> struct TSizeCmp {
422 bool operator ()( const list < T > & l1, const list < T > & l2 )
423 const { return l1.size() < l2.size(); }
426 template<typename T> void sortBySize( list< list < T > > & theListOfList )
428 if ( theListOfList.size() > 2 ) {
429 TSizeCmp< T > SizeCmp;
430 theListOfList.sort( SizeCmp );
434 //=======================================================================
437 //=======================================================================
439 static gp_XY project (const SMDS_MeshNode* theNode,
440 Extrema_GenExtPS & theProjectorPS)
442 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
443 theProjectorPS.Perform( P );
444 if ( !theProjectorPS.IsDone() ) {
445 MESSAGE( "SMESH_Pattern: point projection FAILED");
448 double u, v, minVal = DBL_MAX;
449 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
450 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
451 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
452 minVal = theProjectorPS.SquareDistance( i );
454 if ( theProjectorPS.Value( i ) < minVal ) {
455 minVal = theProjectorPS.Value( i );
457 theProjectorPS.Point( i ).Parameter( u, v );
459 return gp_XY( u, v );
462 //=======================================================================
463 //function : areNodesBound
464 //purpose : true if all nodes of faces are bound to shapes
465 //=======================================================================
467 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
469 while ( faceItr->more() )
471 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
472 while ( nIt->more() )
474 const SMDS_MeshNode* node = smdsNode( nIt->next() );
475 if (node->getshapeId() <1) {
483 //=======================================================================
484 //function : isMeshBoundToShape
485 //purpose : return true if all 2d elements are bound to shape
486 // if aFaceSubmesh != NULL, then check faces bound to it
487 // else check all faces in aMeshDS
488 //=======================================================================
490 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
491 SMESHDS_SubMesh * aFaceSubmesh,
492 const bool isMainShape)
495 // check that all faces are bound to aFaceSubmesh
496 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
500 // check face nodes binding
501 if ( aFaceSubmesh ) {
502 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
503 return areNodesBound( fIt );
505 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
506 return areNodesBound( fIt );
509 //=======================================================================
511 //purpose : Create a pattern from the mesh built on <theFace>.
512 // <theProject>==true makes override nodes positions
513 // on <theFace> computed by mesher
514 //=======================================================================
516 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
517 const TopoDS_Face& theFace,
519 TopoDS_Vertex the1stVertex)
521 MESSAGE(" ::Load(face) " );
525 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
526 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
527 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
528 SMESH_MesherHelper helper( *theMesh );
529 helper.SetSubShape( theFace );
531 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
532 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
533 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
535 MESSAGE( "No elements bound to the face");
536 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
539 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
541 // check if face is closed
542 bool isClosed = helper.HasSeam();
543 list<TopoDS_Edge> eList;
544 list<TopoDS_Edge>::iterator elIt;
545 SMESH_Block::GetOrderedEdges( face, eList, myNbKeyPntInBoundary, the1stVertex );
547 // check that requested or needed projection is possible
548 bool isMainShape = theMesh->IsMainShape( face );
549 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
550 bool canProject = ( nbElems ? true : isMainShape );
552 canProject = false; // so far
554 if ( ( theProject || needProject ) && !canProject )
555 return setErrorCode( ERR_LOADF_CANT_PROJECT );
557 Extrema_GenExtPS projector;
558 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
559 if ( theProject || needProject )
560 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
563 TNodePointIDMap nodePointIDMap;
564 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
568 MESSAGE("Project the submesh");
569 // ---------------------------------------------------------------
570 // The case where the submesh is projected to theFace
571 // ---------------------------------------------------------------
574 list< const SMDS_MeshElement* > faces;
576 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
577 while ( fIt->more() ) {
578 const SMDS_MeshElement* f = fIt->next();
579 if ( f && f->GetType() == SMDSAbs_Face )
580 faces.push_back( f );
584 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
585 while ( fIt->more() )
586 faces.push_back( fIt->next() );
589 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
590 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
591 for ( ; fIt != faces.end(); ++fIt )
593 myElemPointIDs.push_back( TElemDef() );
594 TElemDef& elemPoints = myElemPointIDs.back();
595 int nbNodes = (*fIt)->NbCornerNodes();
596 for ( int i = 0;i < nbNodes; ++i )
598 const SMDS_MeshElement* node = (*fIt)->GetNode( i );
599 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
600 if ( nIdIt->second == -1 )
602 elemPoints.push_back( iPoint );
603 nIdIt->second = iPoint++;
606 elemPoints.push_back( (*nIdIt).second );
609 myPoints.resize( iPoint );
611 // project all nodes of 2d elements to theFace
612 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
613 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
615 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
616 TPoint * p = & myPoints[ (*nIdIt).second ];
617 p->myInitUV = project( node, projector );
618 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
620 // find key-points: the points most close to UV of vertices
621 TopExp_Explorer vExp( face, TopAbs_VERTEX );
622 set<int> foundIndices;
623 for ( ; vExp.More(); vExp.Next() ) {
624 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
625 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
626 double minDist = DBL_MAX;
628 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
629 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
630 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
631 if ( dist < minDist ) {
636 if ( foundIndices.insert( index ).second ) // unique?
637 myKeyPointIDs.push_back( index );
639 myIsBoundaryPointsFound = false;
644 // ---------------------------------------------------------------------
645 // The case where a pattern is being made from the mesh built by mesher
646 // ---------------------------------------------------------------------
648 // Load shapes in the consequent order and count nb of points
651 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ ) {
652 int nbV = myShapeIDMap.Extent();
653 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
654 bool added = ( nbV < myShapeIDMap.Extent() );
655 if ( !added ) { // vertex encountered twice
656 // a seam vertex have two corresponding key points
657 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ).Reversed());
660 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
661 nbNodes += eSubMesh->NbNodes() + 1;
664 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
665 myShapeIDMap.Add( *elIt );
667 myShapeIDMap.Add( face );
669 myPoints.resize( nbNodes );
671 // Load U of points on edges
673 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
675 TopoDS_Edge & edge = *elIt;
676 list< TPoint* > & ePoints = getShapePoints( edge );
678 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
679 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
681 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
682 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
683 // to make adjacent edges share key-point, we make v2 FORWARD too
684 // (as we have different points for same shape with different orienation)
687 // on closed face we must have REVERSED some of seam vertices
689 if ( helper.IsSeamShape( edge ) ) {
690 if ( helper.IsRealSeam( edge ) && !isForward ) {
691 // reverse on reversed SEAM edge
696 else { // on CLOSED edge (i.e. having one vertex with different orienations)
697 for ( int is2 = 0; is2 < 2; ++is2 ) {
698 TopoDS_Shape & v = is2 ? v2 : v1;
699 if ( helper.IsRealSeam( v ) ) {
700 // reverse or not depending on orientation of adjacent seam
702 list<TopoDS_Edge>::iterator eIt2 = elIt;
704 seam = ( ++eIt2 == eList.end() ? eList.front() : *eIt2 );
706 seam = ( eIt2 == eList.begin() ? eList.back() : *(--eIt2) );
707 if ( seam.Orientation() == TopAbs_REVERSED )
714 // the forward key-point
715 list< TPoint* > * vPoint = & getShapePoints( v1 );
716 if ( vPoint->empty() )
718 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
719 if ( vSubMesh && vSubMesh->NbNodes() ) {
720 myKeyPointIDs.push_back( iPoint );
721 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
722 const SMDS_MeshNode* node = nIt->next();
723 if ( v1.Orientation() == TopAbs_REVERSED )
724 closeNodePointIDMap.insert( make_pair( node, iPoint ));
726 nodePointIDMap.insert( make_pair( node, iPoint ));
728 TPoint* keyPoint = &myPoints[ iPoint++ ];
729 vPoint->push_back( keyPoint );
731 keyPoint->myInitUV = project( node, projector );
733 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
734 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
737 if ( !vPoint->empty() )
738 ePoints.push_back( vPoint->front() );
741 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
742 if ( eSubMesh && eSubMesh->NbNodes() )
744 // loop on nodes of an edge: sort them by param on edge
745 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
746 TParamNodeMap paramNodeMap;
747 int nbMeduimNodes = 0;
748 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
749 while ( nIt->more() )
751 const SMDS_MeshNode* node = nIt->next();
752 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
756 const SMDS_EdgePosition* epos =
757 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
758 double u = epos->GetUParameter();
759 paramNodeMap.insert( make_pair( u, node ));
761 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
762 // wrong U on edge, project
764 BRepAdaptor_Curve aCurve( edge );
765 proj.Initialize( aCurve, f, l );
766 paramNodeMap.clear();
767 nIt = eSubMesh->GetNodes();
768 for ( int iNode = 0; nIt->more(); ++iNode ) {
769 const SMDS_MeshNode* node = nIt->next();
770 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
772 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
774 if ( proj.IsDone() ) {
775 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
776 if ( proj.IsMin( i )) {
777 u = proj.Point( i ).Parameter();
781 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
783 paramNodeMap.insert( make_pair( u, node ));
786 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
787 if ( paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
788 return setErrorCode(ERR_UNEXPECTED);
791 // put U in [0,1] so that the first key-point has U==0
792 bool isSeam = helper.IsRealSeam( edge );
794 TParamNodeMap::iterator unIt = paramNodeMap.begin();
795 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
796 while ( unIt != paramNodeMap.end() )
798 TPoint* p = & myPoints[ iPoint ];
799 ePoints.push_back( p );
800 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
801 if ( isSeam && !isForward )
802 closeNodePointIDMap.insert( make_pair( node, iPoint ));
804 nodePointIDMap.insert ( make_pair( node, iPoint ));
807 p->myInitUV = project( node, projector );
809 double u = isForward ? (*unIt).first : (*unRIt).first;
810 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
811 p->myInitUV = C2d->Value( u ).XY();
813 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
818 // the reverse key-point
819 vPoint = & getShapePoints( v2 );
820 if ( vPoint->empty() )
822 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
823 if ( vSubMesh && vSubMesh->NbNodes() ) {
824 myKeyPointIDs.push_back( iPoint );
825 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
826 const SMDS_MeshNode* node = nIt->next();
827 if ( v2.Orientation() == TopAbs_REVERSED )
828 closeNodePointIDMap.insert( make_pair( node, iPoint ));
830 nodePointIDMap.insert( make_pair( node, iPoint ));
832 TPoint* keyPoint = &myPoints[ iPoint++ ];
833 vPoint->push_back( keyPoint );
835 keyPoint->myInitUV = project( node, projector );
837 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
838 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
841 if ( !vPoint->empty() )
842 ePoints.push_back( vPoint->front() );
844 // compute U of edge-points
847 double totalDist = 0;
848 list< TPoint* >::iterator pIt = ePoints.begin();
849 TPoint* prevP = *pIt;
850 prevP->myInitU = totalDist;
851 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
853 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
854 p->myInitU = totalDist;
857 if ( totalDist > DBL_MIN)
858 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
860 p->myInitU /= totalDist;
863 } // loop on edges of a wire
865 // Load in-face points and elements
867 if ( fSubMesh && fSubMesh->NbElements() )
869 list< TPoint* > & fPoints = getShapePoints( face );
870 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
871 while ( nIt->more() )
873 const SMDS_MeshNode* node = nIt->next();
874 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
876 nodePointIDMap.insert( make_pair( node, iPoint ));
877 TPoint* p = &myPoints[ iPoint++ ];
878 fPoints.push_back( p );
880 p->myInitUV = project( node, projector );
882 const SMDS_FacePosition* pos =
883 static_cast<const SMDS_FacePosition*>(node->GetPosition());
884 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
886 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
889 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
890 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
891 while ( elemIt->more() )
893 const SMDS_MeshElement* elem = elemIt->next();
894 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
895 myElemPointIDs.push_back( TElemDef() );
896 TElemDef& elemPoints = myElemPointIDs.back();
897 // find point indices corresponding to element nodes
898 while ( nIt->more() )
900 const SMDS_MeshNode* node = smdsNode( nIt->next() );
901 n_id = nodePointIDMap.find( node );
902 if ( n_id == nodePointIDMap.end() )
903 continue; // medium node
904 iPoint = n_id->second; // point index of interest
905 // for a node on a seam edge there are two points
906 if ( helper.IsRealSeam( node->getshapeId() ) &&
907 ( n_id = closeNodePointIDMap.find( node )) != not_found )
909 TPoint & p1 = myPoints[ iPoint ];
910 TPoint & p2 = myPoints[ n_id->second ];
911 // Select point closest to the rest nodes of element in UV space
912 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
913 const SMDS_MeshNode* notSeamNode = 0;
914 // find node not on a seam edge
915 while ( nIt2->more() && !notSeamNode ) {
916 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
917 if ( !helper.IsSeamShape( n->getshapeId() ))
920 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
921 double dist1 = uv.SquareDistance( p1.myInitUV );
922 double dist2 = uv.SquareDistance( p2.myInitUV );
924 iPoint = n_id->second;
926 elemPoints.push_back( iPoint );
930 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
932 myIsBoundaryPointsFound = true;
935 // Assure that U range is proportional to V range
938 vector< TPoint >::iterator pVecIt = myPoints.begin();
939 for ( ; pVecIt != myPoints.end(); pVecIt++ )
940 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
941 double minU, minV, maxU, maxV;
942 bndBox.Get( minU, minV, maxU, maxV );
943 double dU = maxU - minU, dV = maxV - minV;
944 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
947 // define where is the problem, in the face or in the mesh
948 TopExp_Explorer vExp( face, TopAbs_VERTEX );
949 for ( ; vExp.More(); vExp.Next() ) {
950 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
953 bndBox.Get( minU, minV, maxU, maxV );
954 dU = maxU - minU, dV = maxV - minV;
955 if ( dU <= DBL_MIN || dV <= DBL_MIN )
957 return setErrorCode( ERR_LOADF_NARROW_FACE );
959 // mesh is projected onto a line, e.g.
960 return setErrorCode( ERR_LOADF_CANT_PROJECT );
962 double ratio = dU / dV, maxratio = 3, scale;
964 if ( ratio > maxratio ) {
965 scale = ratio / maxratio;
968 else if ( ratio < 1./maxratio ) {
969 scale = maxratio / ratio;
974 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
975 TPoint & p = *pVecIt;
976 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
977 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
980 if ( myElemPointIDs.empty() ) {
981 MESSAGE( "No elements bound to the face");
982 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
985 return setErrorCode( ERR_OK );
988 //=======================================================================
989 //function : computeUVOnEdge
990 //purpose : compute coordinates of points on theEdge
991 //=======================================================================
993 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
994 const list< TPoint* > & ePoints )
996 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
998 Handle(Geom2d_Curve) C2d =
999 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1001 ePoints.back()->myInitU = 1.0;
1002 list< TPoint* >::const_iterator pIt = ePoints.begin();
1003 for ( pIt++; pIt != ePoints.end(); pIt++ )
1005 TPoint* point = *pIt;
1007 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1008 point->myU = ( f * ( 1 - du ) + l * du );
1010 point->myUV = C2d->Value( point->myU ).XY();
1014 //=======================================================================
1015 //function : intersectIsolines
1017 //=======================================================================
1019 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1020 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1024 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1025 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1026 resUV = 0.5 * ( loc1 + loc2 );
1027 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1028 // SKL 26.07.2007 for NPAL16567
1029 double d1 = (uv11-uv12).Modulus();
1030 double d2 = (uv21-uv22).Modulus();
1031 // double delta = d1*d2*1e-6; PAL17233
1032 double delta = min( d1, d2 ) / 10.;
1033 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1035 // double len1 = ( uv11 - uv12 ).Modulus();
1036 // double len2 = ( uv21 - uv22 ).Modulus();
1037 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1041 // gp_Lin2d line1( uv11, uv12 - uv11 );
1042 // gp_Lin2d line2( uv21, uv22 - uv21 );
1043 // double angle = Abs( line1.Angle( line2 ) );
1045 // IntAna2d_AnaIntersection inter;
1046 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1047 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1049 // gp_Pnt2d interUV = inter.Point(1).Value();
1050 // resUV += interUV.XY();
1051 // inter.Perform( line1, line2 );
1052 // interUV = inter.Point(1).Value();
1053 // resUV += interUV.XY();
1058 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1059 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1064 //=======================================================================
1065 //function : compUVByIsoIntersection
1067 //=======================================================================
1069 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1070 const gp_XY& theInitUV,
1072 bool & theIsDeformed )
1074 // compute UV by intersection of 2 iso lines
1075 //gp_Lin2d isoLine[2];
1076 gp_XY uv1[2], uv2[2];
1078 const double zero = DBL_MIN;
1079 for ( int iIso = 0; iIso < 2; iIso++ )
1081 // to build an iso line:
1082 // find 2 pairs of consequent edge-points such that the range of their
1083 // initial parameters encloses the in-face point initial parameter
1084 gp_XY UV[2], initUV[2];
1085 int nbUV = 0, iCoord = iIso + 1;
1086 double initParam = theInitUV.Coord( iCoord );
1088 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1089 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1091 const list< TPoint* > & bndPoints = * bndIt;
1092 TPoint* prevP = bndPoints.back(); // this is the first point
1093 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1094 bool coincPrev = false;
1095 // loop on the edge-points
1096 for ( ; pIt != bndPoints.end(); pIt++ )
1098 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1099 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1100 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1101 if (!coincPrev && // ignore if initParam coincides with prev point param
1102 sumOfDiff > zero && // ignore if both points coincide with initParam
1103 prevParamDiff * paramDiff <= zero )
1105 // find UV in parametric space of theFace
1106 double r = Abs(prevParamDiff) / sumOfDiff;
1107 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1110 // throw away uv most distant from <theInitUV>
1111 gp_XY vec0 = initUV[0] - theInitUV;
1112 gp_XY vec1 = initUV[1] - theInitUV;
1113 gp_XY vec = uvInit - theInitUV;
1114 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1115 double dist0 = vec0.SquareModulus();
1116 double dist1 = vec1.SquareModulus();
1117 double dist = vec .SquareModulus();
1118 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1119 i = ( dist0 < dist1 ? 1 : 0 );
1120 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1121 i = 3; // theInitUV must remain between
1125 initUV[ i ] = uvInit;
1126 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1128 coincPrev = ( Abs(paramDiff) <= zero );
1135 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1136 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1137 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1138 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1140 // an iso line should be normal to UV[0] - UV[1] direction
1141 // and be located at the same relative distance as from initial ends
1142 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1144 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1145 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1146 //isoLine[ iIso ] = iso.Normal( isoLoc );
1147 uv1[ iIso ] = UV[0];
1148 uv2[ iIso ] = UV[1];
1151 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1152 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1153 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1154 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1161 // ==========================================================
1162 // structure representing a node of a grid of iso-poly-lines
1163 // ==========================================================
1170 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1171 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1172 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1173 TIsoNode(double initU, double initV):
1174 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1175 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1176 bool IsUVComputed() const
1177 { return myUV.X() != 1e100; }
1178 bool IsMovable() const
1179 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1180 void SetNotMovable()
1181 { myIsMovable = false; }
1182 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1183 { myBndNodes[ iDir + i * 2 ] = node; }
1184 TIsoNode* GetBoundaryNode(int iDir, int i)
1185 { return myBndNodes[ iDir + i * 2 ]; }
1186 void SetNext(TIsoNode* node, int iDir, int isForward)
1187 { myNext[ iDir + isForward * 2 ] = node; }
1188 TIsoNode* GetNext(int iDir, int isForward)
1189 { return myNext[ iDir + isForward * 2 ]; }
1192 //=======================================================================
1193 //function : getNextNode
1195 //=======================================================================
1197 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1199 TIsoNode* n = node->myNext[ dir ];
1200 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1201 n = 0;//node->myBndNodes[ dir ];
1202 // MESSAGE("getNextNode: use bnd for node "<<
1203 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1207 //=======================================================================
1208 //function : checkQuads
1209 //purpose : check if newUV destortes quadrangles around node,
1210 // and if ( crit == FIX_OLD ) fix newUV in this case
1211 //=======================================================================
1213 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1215 static bool checkQuads (const TIsoNode* node,
1217 const bool reversed,
1218 const int crit = FIX_OLD,
1219 double fixSize = 0.)
1221 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1222 int nbOldFix = 0, nbOldImpr = 0;
1223 double newBadRate = 0, oldBadRate = 0;
1224 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1225 int i, dir1 = 0, dir2 = 3;
1226 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1228 if ( dir2 > 3 ) dir2 = 0;
1230 // walking counterclockwise around a quad,
1231 // nodes are in the order: node, n[0], n[1], n[2]
1232 n[0] = getNextNode( node, dir1 );
1233 n[2] = getNextNode( node, dir2 );
1234 if ( !n[0] || !n[2] ) continue;
1235 n[1] = getNextNode( n[0], dir2 );
1236 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1237 bool isTriangle = ( !n[1] );
1239 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1241 // if ( fixSize != 0 ) {
1242 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1243 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1244 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1245 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1247 // check if a quadrangle is degenerated
1249 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1250 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1253 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1256 // find min size of the diagonal node-n[1]
1257 double minDiag = fixSize;
1258 if ( minDiag == 0. ) {
1259 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1260 if ( !isTriangle ) {
1261 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1262 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1264 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1265 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1268 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1269 // ( behind means "to the right of")
1271 // 1. newUV is not behind 01 and 12 dirs
1272 // 2. or newUV is not behind 02 dir and n[2] is convex
1273 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1274 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1275 gp_Vec2d moveVec[3], outVec[3];
1276 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1278 bool isDiag = ( i == 2 );
1279 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1283 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1285 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1287 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1289 gp_Vec2d newDir( n[i]->myUV, newUV );
1290 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1292 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1293 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1294 if ( crit == FIX_OLD ) {
1295 wasIn[i] = ( outDir * oldDir < 0 );
1296 wasOk[i] = ( outDir * oldDir < -minDiag );
1298 newBadRate += outDir * newDir;
1300 oldBadRate += outDir * oldDir;
1303 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1304 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1305 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1306 moveVec[i] = ( oldDist - minDiag ) * outDir;
1311 // check if n[2] is convex
1314 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1316 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1317 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1318 newIsOk = ( newIsOk && isNewOk );
1319 newIsIn = ( newIsIn && isNewIn );
1321 if ( crit != FIX_OLD ) {
1322 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1323 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1327 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1328 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1329 oldIsIn = ( oldIsIn && isOldIn );
1330 oldIsOk = ( oldIsOk && isOldIn );
1333 if ( !isOldIn ) { // node is outside a quadrangle
1334 // move newUV inside a quadrangle
1335 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1336 // node and newUV are outside: push newUV inside
1338 if ( convex || isTriangle ) {
1339 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1342 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1343 double outSize = out.Magnitude();
1344 if ( outSize > DBL_MIN )
1347 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1348 uv = n[1]->myUV - minDiag * out.XY();
1350 oldUVFixed[ nbOldFix++ ] = uv;
1351 //node->myUV = newUV;
1353 else if ( !isOldOk ) {
1354 // try to fix old UV: move node inside as less as possible
1355 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1356 gp_XY uv1, uv2 = node->myUV;
1357 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1359 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1360 while ( !isOldOk ) {
1361 // find the least moveVec
1363 double minMove2 = 1e100;
1364 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1366 if ( moveVec[i].Coord(1) < 1e100 ) {
1367 double move2 = moveVec[i].SquareMagnitude();
1368 if ( move2 < minMove2 ) {
1377 // move node to newUV
1378 uv1 = node->myUV + moveVec[ iMin ].XY();
1379 uv2 += moveVec[ iMin ].XY();
1380 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1381 // check if uv1 is ok
1382 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1383 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1384 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1386 oldUVImpr[ nbOldImpr++ ] = uv1;
1388 // check if uv2 is ok
1389 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1390 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1391 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1393 oldUVImpr[ nbOldImpr++ ] = uv2;
1398 } // loop on 4 quadrangles around <node>
1400 if ( crit == CHECK_NEW_OK )
1402 if ( crit == CHECK_NEW_IN )
1411 if ( oldIsIn && nbOldImpr ) {
1412 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1413 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1414 gp_XY uv = oldUVImpr[ 0 ];
1415 for ( int i = 1; i < nbOldImpr; i++ )
1416 uv += oldUVImpr[ i ];
1418 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1423 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1426 if ( !oldIsIn && nbOldFix ) {
1427 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1428 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1429 gp_XY uv = oldUVFixed[ 0 ];
1430 for ( int i = 1; i < nbOldFix; i++ )
1431 uv += oldUVFixed[ i ];
1433 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1438 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1441 if ( newIsIn && oldIsIn )
1442 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1443 else if ( !newIsIn )
1450 //=======================================================================
1451 //function : compUVByElasticIsolines
1452 //purpose : compute UV as nodes of iso-poly-lines consisting of
1453 // segments keeping relative size as in the pattern
1454 //=======================================================================
1455 //#define DEB_COMPUVBYELASTICISOLINES
1456 bool SMESH_Pattern::
1457 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1458 const list< TPoint* >& thePntToCompute)
1460 return false; // PAL17233
1461 //cout << "============================== KEY POINTS =============================="<<endl;
1462 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1463 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1464 // TPoint& p = myPoints[ *kpIt ];
1465 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1466 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1468 //cout << "=============================="<<endl;
1470 // Define parameters of iso-grid nodes in U and V dir
1472 set< double > paramSet[ 2 ];
1473 list< list< TPoint* > >::const_iterator pListIt;
1474 list< TPoint* >::const_iterator pIt;
1475 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1476 const list< TPoint* > & pList = * pListIt;
1477 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1478 paramSet[0].insert( (*pIt)->myInitUV.X() );
1479 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1482 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1483 paramSet[0].insert( (*pIt)->myInitUV.X() );
1484 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1486 // unite close parameters and split too long segments
1489 for ( iDir = 0; iDir < 2; iDir++ )
1491 set< double > & params = paramSet[ iDir ];
1492 double range = ( *params.rbegin() - *params.begin() );
1493 double toler = range / 1e6;
1494 tol[ iDir ] = toler;
1495 // double maxSegment = range / params.size() / 2.;
1497 // set< double >::iterator parIt = params.begin();
1498 // double prevPar = *parIt;
1499 // for ( parIt++; parIt != params.end(); parIt++ )
1501 // double segLen = (*parIt) - prevPar;
1502 // if ( segLen < toler )
1503 // ;//params.erase( prevPar ); // unite
1504 // else if ( segLen > maxSegment )
1505 // params.insert( prevPar + 0.5 * segLen ); // split
1506 // prevPar = (*parIt);
1510 // Make nodes of a grid of iso-poly-lines
1512 list < TIsoNode > nodes;
1513 typedef list < TIsoNode *> TIsoLine;
1514 map < double, TIsoLine > isoMap[ 2 ];
1516 set< double > & params0 = paramSet[ 0 ];
1517 set< double >::iterator par0It = params0.begin();
1518 for ( ; par0It != params0.end(); par0It++ )
1520 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1521 set< double > & params1 = paramSet[ 1 ];
1522 set< double >::iterator par1It = params1.begin();
1523 for ( ; par1It != params1.end(); par1It++ )
1525 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1526 isoLine0.push_back( & nodes.back() );
1527 isoMap[1][ *par1It ].push_back( & nodes.back() );
1531 // Compute intersections of boundaries with iso-lines:
1532 // only boundary nodes will have computed UV so far
1535 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1536 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1537 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1539 const list< TPoint* > & bndPoints = * bndIt;
1540 TPoint* prevP = bndPoints.back(); // this is the first point
1541 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1542 // loop on the edge-points
1543 for ( ; pIt != bndPoints.end(); pIt++ )
1545 TPoint* point = *pIt;
1546 for ( iDir = 0; iDir < 2; iDir++ )
1548 const int iCoord = iDir + 1;
1549 const int iOtherCoord = 2 - iDir;
1550 double par1 = prevP->myInitUV.Coord( iCoord );
1551 double par2 = point->myInitUV.Coord( iCoord );
1552 double parDif = par2 - par1;
1553 if ( Abs( parDif ) <= DBL_MIN )
1555 // find iso-lines intersecting a bounadry
1556 double toler = tol[ 1 - iDir ];
1557 double minPar = Min ( par1, par2 );
1558 double maxPar = Max ( par1, par2 );
1559 map < double, TIsoLine >& isos = isoMap[ iDir ];
1560 map < double, TIsoLine >::iterator isoIt = isos.begin();
1561 for ( ; isoIt != isos.end(); isoIt++ )
1563 double isoParam = (*isoIt).first;
1564 if ( isoParam < minPar || isoParam > maxPar )
1566 double r = ( isoParam - par1 ) / parDif;
1567 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1568 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1569 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1570 // find existing node with otherPar or insert a new one
1571 TIsoLine & isoLine = (*isoIt).second;
1573 TIsoLine::iterator nIt = isoLine.begin();
1574 for ( ; nIt != isoLine.end(); nIt++ ) {
1575 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1576 if ( nodePar >= otherPar )
1580 if ( Abs( nodePar - otherPar ) <= toler )
1581 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1583 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1584 node = & nodes.back();
1585 isoLine.insert( nIt, node );
1587 node->SetNotMovable();
1589 uvBnd.Add( gp_Pnt2d( uv ));
1590 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1592 gp_XY tgt( point->myUV - prevP->myUV );
1593 if ( ::IsEqual( r, 1. ))
1594 node->myDir[ 0 ] = tgt;
1595 else if ( ::IsEqual( r, 0. ))
1596 node->myDir[ 1 ] = tgt;
1598 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1599 // keep boundary nodes corresponding to boundary points
1600 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1601 if ( bndNodes.empty() || bndNodes.back() != node )
1602 bndNodes.push_back( node );
1603 } // loop on isolines
1604 } // loop on 2 directions
1606 } // loop on boundary points
1607 } // loop on boundaries
1609 // Define orientation
1611 // find the point with the least X
1612 double leastX = DBL_MAX;
1613 TIsoNode * leftNode;
1614 list < TIsoNode >::iterator nodeIt = nodes.begin();
1615 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1616 TIsoNode & node = *nodeIt;
1617 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1618 leastX = node.myUV.X();
1621 // if ( node.IsUVComputed() ) {
1622 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1623 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1624 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1625 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1628 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1629 //SCRUTE( reversed );
1631 // Prepare internal nodes:
1633 // 2. compute ratios
1634 // 3. find boundary nodes for each node
1635 // 4. remove nodes out of the boundary
1636 for ( iDir = 0; iDir < 2; iDir++ )
1638 const int iCoord = 2 - iDir; // coord changing along an isoline
1639 map < double, TIsoLine >& isos = isoMap[ iDir ];
1640 map < double, TIsoLine >::iterator isoIt = isos.begin();
1641 for ( ; isoIt != isos.end(); isoIt++ )
1643 TIsoLine & isoLine = (*isoIt).second;
1644 bool firstCompNodeFound = false;
1645 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1646 nPrevIt = nIt = nNextIt = isoLine.begin();
1648 nNextIt++; nNextIt++;
1649 while ( nIt != isoLine.end() )
1651 // 1. connect prev - cur
1652 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1653 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1654 firstCompNodeFound = true;
1655 lastCompNodePos = nPrevIt;
1657 if ( firstCompNodeFound ) {
1658 node->SetNext( prevNode, iDir, 0 );
1659 prevNode->SetNext( node, iDir, 1 );
1662 if ( nNextIt != isoLine.end() ) {
1663 double par1 = prevNode->myInitUV.Coord( iCoord );
1664 double par2 = node->myInitUV.Coord( iCoord );
1665 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1666 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1668 // 3. find boundary nodes
1669 if ( node->IsUVComputed() )
1670 lastCompNodePos = nIt;
1671 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1672 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1673 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1674 if ( (*nIt2)->IsUVComputed() )
1676 if ( nIt2 != isoLine.end() ) {
1678 node->SetBoundaryNode( bndNode1, iDir, 0 );
1679 node->SetBoundaryNode( bndNode2, iDir, 1 );
1680 // cout << "--------------------------------------------------"<<endl;
1681 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1682 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1683 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1684 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1685 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1686 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1689 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1690 node->SetBoundaryNode( 0, iDir, 0 );
1691 node->SetBoundaryNode( 0, iDir, 1 );
1695 if ( nNextIt != isoLine.end() ) nNextIt++;
1696 // 4. remove nodes out of the boundary
1697 if ( !firstCompNodeFound )
1698 isoLine.pop_front();
1699 } // loop on isoLine nodes
1701 // remove nodes after the boundary
1702 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1703 // (*nIt)->SetNotMovable();
1704 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1705 } // loop on isolines
1706 } // loop on 2 directions
1708 // Compute local isoline direction for internal nodes
1711 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1712 map < double, TIsoLine >::iterator isoIt = isos.begin();
1713 for ( ; isoIt != isos.end(); isoIt++ )
1715 TIsoLine & isoLine = (*isoIt).second;
1716 TIsoLine::iterator nIt = isoLine.begin();
1717 for ( ; nIt != isoLine.end(); nIt++ )
1719 TIsoNode* node = *nIt;
1720 if ( node->IsUVComputed() || !node->IsMovable() )
1722 gp_Vec2d aTgt[2], aNorm[2];
1725 for ( iDir = 0; iDir < 2; iDir++ )
1727 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1728 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1729 if ( !bndNode1 || !bndNode2 ) {
1733 const int iCoord = 2 - iDir; // coord changing along an isoline
1734 double par1 = bndNode1->myInitUV.Coord( iCoord );
1735 double par2 = node->myInitUV.Coord( iCoord );
1736 double par3 = bndNode2->myInitUV.Coord( iCoord );
1737 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1739 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1740 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1741 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1742 else tgt1.Reverse();
1743 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1745 if ( ratio[ iDir ] < 0.5 )
1746 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1748 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1750 aNorm[ iDir ].Reverse(); // along iDir isoline
1752 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1753 // maybe angle is more than |PI|
1754 if ( Abs( angle ) > PI / 2. ) {
1755 // check direction of the last but one perpendicular isoline
1756 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1757 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1758 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1759 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1760 if ( isoDir * tgt2 < 0 )
1762 double angle2 = tgt1.Angle( isoDir );
1763 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1764 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1765 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1766 //MESSAGE("REVERSE ANGLE");
1769 if ( Abs( angle2 ) > Abs( angle ) ||
1770 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1771 //MESSAGE("Add PI");
1772 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1773 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1774 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1775 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1776 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1777 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1780 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1784 for ( iDir = 0; iDir < 2; iDir++ )
1786 aTgt[iDir].Normalize();
1787 aNorm[1-iDir].Normalize();
1788 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1791 node->myDir[iDir] = //aTgt[iDir];
1792 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1794 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1795 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1796 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1797 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1799 } // loop on iso nodes
1800 } // loop on isolines
1802 // Find nodes to start computing UV from
1804 list< TIsoNode* > startNodes;
1805 list< TIsoNode* >::iterator nIt = bndNodes.end();
1806 TIsoNode* node = *(--nIt);
1807 TIsoNode* prevNode = *(--nIt);
1808 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1810 TIsoNode* nextNode = *nIt;
1811 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1812 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1813 double initAngle = initTgt1.Angle( initTgt2 );
1814 double angle = node->myDir[0].Angle( node->myDir[1] );
1815 if ( reversed ) angle = -angle;
1816 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1817 // find a close internal node
1818 TIsoNode* nClose = 0;
1819 list< TIsoNode* > testNodes;
1820 testNodes.push_back( node );
1821 list< TIsoNode* >::iterator it = testNodes.begin();
1822 for ( ; !nClose && it != testNodes.end(); it++ )
1824 for (int i = 0; i < 4; i++ )
1826 nClose = (*it)->myNext[ i ];
1828 if ( !nClose->IsUVComputed() )
1831 testNodes.push_back( nClose );
1837 startNodes.push_back( nClose );
1838 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1839 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1840 // "initAngle: " << initAngle << " angle: " << angle << endl;
1841 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1842 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1843 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1844 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1850 // Compute starting UV of internal nodes
1852 list < TIsoNode* > internNodes;
1853 bool needIteration = true;
1854 if ( startNodes.empty() ) {
1855 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1856 needIteration = false;
1857 map < double, TIsoLine >& isos = isoMap[ 0 ];
1858 map < double, TIsoLine >::iterator isoIt = isos.begin();
1859 for ( ; isoIt != isos.end(); isoIt++ )
1861 TIsoLine & isoLine = (*isoIt).second;
1862 TIsoLine::iterator nIt = isoLine.begin();
1863 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1865 TIsoNode* node = *nIt;
1866 if ( !node->IsUVComputed() && node->IsMovable() ) {
1867 internNodes.push_back( node );
1869 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1870 node->myUV, needIteration ))
1871 node->myUV = node->myInitUV;
1875 if ( needIteration )
1876 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1878 TIsoNode* node = *nIt, *nClose = 0;
1879 list< TIsoNode* > testNodes;
1880 testNodes.push_back( node );
1881 list< TIsoNode* >::iterator it = testNodes.begin();
1882 for ( ; !nClose && it != testNodes.end(); it++ )
1884 for (int i = 0; i < 4; i++ )
1886 nClose = (*it)->myNext[ i ];
1888 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1891 testNodes.push_back( nClose );
1897 startNodes.push_back( nClose );
1901 double aMin[2], aMax[2], step[2];
1902 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1903 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1904 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1905 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1906 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1908 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1910 TIsoNode *node = *nIt;
1911 if ( node->IsUVComputed() || !node->IsMovable() )
1913 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1914 int nbComp = 0, nbPrev = 0;
1915 for ( iDir = 0; iDir < 2; iDir++ )
1917 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1918 TIsoNode* n = node->GetNext( iDir, 0 );
1919 if ( n->IsUVComputed() )
1922 startNodes.push_back( n );
1923 n = node->GetNext( iDir, 1 );
1924 if ( n->IsUVComputed() )
1927 startNodes.push_back( n );
1929 prevNode1 = prevNode2;
1932 if ( prevNode1 ) nbPrev++;
1933 if ( prevNode2 ) nbPrev++;
1936 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1937 double par = node->myInitUV.Coord( 2 - iDir );
1938 bool isEnd = ( prevPar > par );
1939 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1940 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1941 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1943 MESSAGE("Why we are here?");
1946 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1947 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1948 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1949 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1950 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1951 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1952 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1953 //" par: " << prevPar << endl;
1954 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1955 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
1957 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1958 gp_XY & uv1 = prevNode1->myUV;
1959 gp_XY & uv2 = prevNode2->myUV;
1960 // dir = ( uv2 - uv1 );
1961 // double len = dir.Modulus();
1962 // if ( len > DBL_MIN )
1963 // dir /= len * 0.5;
1964 double r = node->myRatio[ iDir ];
1965 newUV += uv1 * ( 1 - r ) + uv2 * r;
1968 newUV += prevNode1->myUV + dir * step[ iDir ];
1974 if ( !nbComp ) continue;
1977 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1979 // check if a quadrangle is not distorted
1981 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
1982 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
1983 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
1984 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
1988 internNodes.push_back( node );
1993 static int maxNbIter = 100;
1994 #ifdef DEB_COMPUVBYELASTICISOLINES
1996 bool useNbMoveNode = 0;
1997 static int maxNbNodeMove = 100;
2000 if ( !useNbMoveNode )
2001 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2006 if ( !needIteration) break;
2007 #ifdef DEB_COMPUVBYELASTICISOLINES
2008 if ( nbIter >= maxNbIter ) break;
2011 list < TIsoNode* >::iterator nIt = internNodes.begin();
2012 for ( ; nIt != internNodes.end(); nIt++ ) {
2013 #ifdef DEB_COMPUVBYELASTICISOLINES
2015 cout << nbNodeMove <<" =================================================="<<endl;
2017 TIsoNode * node = *nIt;
2021 for ( iDir = 0; iDir < 2; iDir++ )
2023 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2024 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2025 double r = node->myRatio[ iDir ];
2026 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2027 // line[ iDir ].SetLocation( loc[ iDir ] );
2028 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2031 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2032 // double locR[2] = { 0, 0 };
2033 for ( iDir = 0; iDir < 2; iDir++ )
2035 const int iCoord = 2 - iDir; // coord changing along an isoline
2036 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2037 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2038 if ( !bndNode1 || !bndNode2 ) {
2041 double par1 = bndNode1->myInitUV.Coord( iCoord );
2042 double par2 = node->myInitUV.Coord( iCoord );
2043 double par3 = bndNode2->myInitUV.Coord( iCoord );
2044 double r = ( par2 - par1 ) / ( par3 - par1 );
2045 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2046 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2048 //locR[0] = locR[1] = 0.25;
2049 // intersect the 2 lines and move a node
2050 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2051 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2053 // double intR = 1 - locR[0] - locR[1];
2054 // gp_XY newUV = inter.Point(1).Value().XY();
2055 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2056 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2058 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2059 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2060 // avoid parallel isolines intersection
2061 checkQuads( node, newUV, reversed );
2063 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2065 } // intersection found
2066 #ifdef DEB_COMPUVBYELASTICISOLINES
2067 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2069 } // loop on internal nodes
2070 #ifdef DEB_COMPUVBYELASTICISOLINES
2071 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2073 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2075 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2077 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2078 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2079 #ifndef DEB_COMPUVBYELASTICISOLINES
2084 // Set computed UV to points
2086 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2087 TPoint* point = *pIt;
2088 //gp_XY oldUV = point->myUV;
2089 double minDist = DBL_MAX;
2090 list < TIsoNode >::iterator nIt = nodes.begin();
2091 for ( ; nIt != nodes.end(); nIt++ ) {
2092 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2093 if ( dist < minDist ) {
2095 point->myUV = (*nIt).myUV;
2104 //=======================================================================
2105 //function : setFirstEdge
2106 //purpose : choose the best first edge of theWire; return the summary distance
2107 // between point UV computed by isolines intersection and
2108 // eventual UV got from edge p-curves
2109 //=======================================================================
2111 //#define DBG_SETFIRSTEDGE
2112 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2114 int iE, nbEdges = theWire.size();
2118 // Transform UVs computed by iso to fit bnd box of a wire
2120 // max nb of points on an edge
2122 int eID = theFirstEdgeID;
2123 for ( iE = 0; iE < nbEdges; iE++ )
2124 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2126 // compute bnd boxes
2127 TopoDS_Face face = TopoDS::Face( myShape );
2128 Bnd_Box2d bndBox, eBndBox;
2129 eID = theFirstEdgeID;
2130 list< TopoDS_Edge >::iterator eIt;
2131 list< TPoint* >::iterator pIt;
2132 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2134 // UV by isos stored in TPoint.myXYZ
2135 list< TPoint* > & ePoints = getShapePoints( eID++ );
2136 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2138 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2140 // UV by an edge p-curve
2142 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2143 double dU = ( l - f ) / ( maxNbPnt - 1 );
2144 for ( int i = 0; i < maxNbPnt; i++ )
2145 eBndBox.Add( C2d->Value( f + i * dU ));
2148 // transform UVs by isos
2149 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2150 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2151 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2152 #ifdef DBG_SETFIRSTEDGE
2153 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2154 << eMinPar[1] << " - " << eMaxPar[1] );
2156 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2158 double dMin = eMinPar[i] - minPar[i];
2159 double dMax = eMaxPar[i] - maxPar[i];
2160 double dPar = maxPar[i] - minPar[i];
2161 eID = theFirstEdgeID;
2162 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2164 list< TPoint* > & ePoints = getShapePoints( eID++ );
2165 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2167 double par = (*pIt)->myXYZ.Coord( iC );
2168 double r = ( par - minPar[i] ) / dPar;
2169 par += ( 1 - r ) * dMin + r * dMax;
2170 (*pIt)->myXYZ.SetCoord( iC, par );
2176 double minDist = DBL_MAX;
2177 for ( iE = 0 ; iE < nbEdges; iE++ )
2179 #ifdef DBG_SETFIRSTEDGE
2180 MESSAGE ( " VARIANT " << iE );
2182 // evaluate the distance between UV computed by the 2 methods:
2183 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2185 int eID = theFirstEdgeID;
2186 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2188 list< TPoint* > & ePoints = getShapePoints( eID++ );
2189 computeUVOnEdge( *eIt, ePoints );
2190 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2192 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2193 #ifdef DBG_SETFIRSTEDGE
2194 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2195 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2199 #ifdef DBG_SETFIRSTEDGE
2200 MESSAGE ( "dist -- " << dist );
2202 if ( dist < minDist ) {
2204 eBest = theWire.front();
2206 // check variant with another first edge
2207 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2209 // put the best first edge to the theWire front
2210 if ( eBest != theWire.front() ) {
2211 eIt = find ( theWire.begin(), theWire.end(), eBest );
2212 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2218 //=======================================================================
2219 //function : sortSameSizeWires
2220 //purpose : sort wires in theWireList from theFromWire until theToWire,
2221 // the wires are set in the order to correspond to the order
2222 // of boundaries; after sorting, edges in the wires are put
2223 // in a good order, point UVs on edges are computed and points
2224 // are appended to theEdgesPointsList
2225 //=======================================================================
2227 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2228 const TListOfEdgesList::iterator& theFromWire,
2229 const TListOfEdgesList::iterator& theToWire,
2230 const int theFirstEdgeID,
2231 list< list< TPoint* > >& theEdgesPointsList )
2233 TopoDS_Face F = TopoDS::Face( myShape );
2234 int iW, nbWires = 0;
2235 TListOfEdgesList::iterator wlIt = theFromWire;
2236 while ( wlIt++ != theToWire )
2239 // Recompute key-point UVs by isolines intersection,
2240 // compute CG of key-points for each wire and bnd boxes of GCs
2243 gp_XY orig( gp::Origin2d().XY() );
2244 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2245 Bnd_Box2d bndBox, vBndBox;
2246 int eID = theFirstEdgeID;
2247 list< TopoDS_Edge >::iterator eIt;
2248 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2250 list< TopoDS_Edge > & wire = *wlIt;
2251 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2253 list< TPoint* > & ePoints = getShapePoints( eID++ );
2254 TPoint* p = ePoints.front();
2255 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2256 MESSAGE("cant sortSameSizeWires()");
2259 gcVec[iW] += p->myUV;
2260 bndBox.Add( gp_Pnt2d( p->myUV ));
2261 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2262 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2263 vGcVec[iW] += vXY.XY();
2265 // keep the computed UV to compare against by setFirstEdge()
2266 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2268 gcVec[iW] /= nbWires;
2269 vGcVec[iW] /= nbWires;
2270 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2271 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2274 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2276 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2277 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2278 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2279 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2281 double dMin = vMinPar[i] - minPar[i];
2282 double dMax = vMaxPar[i] - maxPar[i];
2283 double dPar = maxPar[i] - minPar[i];
2284 if ( Abs( dPar ) <= DBL_MIN )
2286 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2287 double par = gcVec[iW].Coord( iC );
2288 double r = ( par - minPar[i] ) / dPar;
2289 par += ( 1 - r ) * dMin + r * dMax;
2290 gcVec[iW].SetCoord( iC, par );
2294 // Define boundary - wire correspondence by GC closeness
2296 TListOfEdgesList tmpWList;
2297 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2298 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2299 TIntWirePosMap bndIndWirePosMap;
2300 vector< bool > bndFound( nbWires, false );
2301 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2303 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2304 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2305 double minDist = DBL_MAX;
2306 gp_XY & wGc = vGcVec[ iW ];
2308 for ( int iB = 0; iB < nbWires; iB++ ) {
2309 if ( bndFound[ iB ] ) continue;
2310 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2311 if ( dist < minDist ) {
2316 bndFound[ bIndex ] = true;
2317 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2322 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2323 eID = theFirstEdgeID;
2324 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2326 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2327 list < TopoDS_Edge > & wire = ( *wirePos );
2329 // choose the best first edge of a wire
2330 setFirstEdge( wire, eID );
2332 // compute eventual UV and fill theEdgesPointsList
2333 theEdgesPointsList.push_back( list< TPoint* >() );
2334 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2335 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2337 list< TPoint* > & ePoints = getShapePoints( eID++ );
2338 computeUVOnEdge( *eIt, ePoints );
2339 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2341 // put wire back to theWireList
2343 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2349 //=======================================================================
2351 //purpose : Compute nodes coordinates applying
2352 // the loaded pattern to <theFace>. The first key-point
2353 // will be mapped into <theVertexOnKeyPoint1>
2354 //=======================================================================
2356 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2357 const TopoDS_Vertex& theVertexOnKeyPoint1,
2358 const bool theReverse)
2360 MESSAGE(" ::Apply(face) " );
2361 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2362 if ( !setShapeToMesh( face ))
2365 // find points on edges, it fills myNbKeyPntInBoundary
2366 if ( !findBoundaryPoints() )
2369 // Define the edges order so that the first edge starts at
2370 // theVertexOnKeyPoint1
2372 list< TopoDS_Edge > eList;
2373 list< int > nbVertexInWires;
2374 int nbWires = SMESH_Block::GetOrderedEdges( face, eList, nbVertexInWires, theVertexOnKeyPoint1);
2375 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2377 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2378 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2380 // check nb wires and edges
2381 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2382 l1.sort(); l2.sort();
2385 MESSAGE( "Wrong nb vertices in wires" );
2386 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2389 // here shapes get IDs, for the outer wire IDs are OK
2390 list<TopoDS_Edge>::iterator elIt = eList.begin();
2391 for ( ; elIt != eList.end(); elIt++ ) {
2392 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2393 bool isClosed1 = BRep_Tool::IsClosed( *elIt, theFace );
2394 // BEGIN: jfa for bug 0019943
2397 for (TopExp_Explorer expw (theFace, TopAbs_WIRE); expw.More() && !isClosed1; expw.Next()) {
2398 const TopoDS_Wire& wire = TopoDS::Wire(expw.Current());
2400 for (BRepTools_WireExplorer we (wire, theFace); we.More() && !isClosed1; we.Next()) {
2401 if (we.Current().IsSame(*elIt)) {
2403 if (nbe == 2) isClosed1 = true;
2408 // END: jfa for bug 0019943
2410 myShapeIDMap.Add( TopExp::LastVertex( *elIt, true ));// vertex orienation is REVERSED
2412 int nbVertices = myShapeIDMap.Extent();
2414 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2415 myShapeIDMap.Add( *elIt );
2417 myShapeIDMap.Add( face );
2419 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2420 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2421 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2424 // points on edges to be used for UV computation of in-face points
2425 list< list< TPoint* > > edgesPointsList;
2426 edgesPointsList.push_back( list< TPoint* >() );
2427 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2428 list< TPoint* >::iterator pIt;
2430 // compute UV of points on the outer wire
2431 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2432 for (iE = 0, elIt = eList.begin();
2433 iE < nbEdgesInOuterWire && elIt != eList.end();
2436 list< TPoint* > & ePoints = getShapePoints( *elIt );
2438 computeUVOnEdge( *elIt, ePoints );
2439 // collect on-edge points (excluding the last one)
2440 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2443 // If there are several wires, define the order of edges of inner wires:
2444 // compute UV of inner edge-points using 2 methods: the one for in-face points
2445 // and the one for on-edge points and then choose the best edge order
2446 // by the best correspondance of the 2 results
2449 // compute UV of inner edge-points using the method for in-face points
2450 // and devide eList into a list of separate wires
2452 list< list< TopoDS_Edge > > wireList;
2453 list<TopoDS_Edge>::iterator eIt = elIt;
2454 list<int>::iterator nbEIt = nbVertexInWires.begin();
2455 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2457 int nbEdges = *nbEIt;
2458 wireList.push_back( list< TopoDS_Edge >() );
2459 list< TopoDS_Edge > & wire = wireList.back();
2460 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2462 list< TPoint* > & ePoints = getShapePoints( *eIt );
2463 pIt = ePoints.begin();
2464 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2466 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2467 MESSAGE("cant Apply(face)");
2470 // keep the computed UV to compare against by setFirstEdge()
2471 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2473 wire.push_back( *eIt );
2476 // remove inner edges from eList
2477 eList.erase( elIt, eList.end() );
2479 // sort wireList by nb edges in a wire
2480 sortBySize< TopoDS_Edge > ( wireList );
2482 // an ID of the first edge of a boundary
2483 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2484 // if ( nbSeamShapes > 0 )
2485 // id1 += 2; // 2 vertices more
2487 // find points - edge correspondence for wires of unique size,
2488 // edge order within a wire should be defined only
2490 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2491 while ( wlIt != wireList.end() )
2493 list< TopoDS_Edge >& wire = (*wlIt);
2494 int nbEdges = wire.size();
2496 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2498 // choose the best first edge of a wire
2499 setFirstEdge( wire, id1 );
2501 // compute eventual UV and collect on-edge points
2502 edgesPointsList.push_back( list< TPoint* >() );
2503 edgesPoints = & edgesPointsList.back();
2505 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2507 list< TPoint* > & ePoints = getShapePoints( eID++ );
2508 computeUVOnEdge( *eIt, ePoints );
2509 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2515 // find boundary - wire correspondence for several wires of same size
2517 id1 = nbVertices + nbEdgesInOuterWire + 1;
2518 wlIt = wireList.begin();
2519 while ( wlIt != wireList.end() )
2521 int nbSameSize = 0, nbEdges = (*wlIt).size();
2522 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2524 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2528 if ( nbSameSize > 0 )
2529 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2532 id1 += nbEdges * ( nbSameSize + 1 );
2535 // add well-ordered edges to eList
2537 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2539 list< TopoDS_Edge >& wire = (*wlIt);
2540 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2543 // re-fill myShapeIDMap - all shapes get good IDs
2545 myShapeIDMap.Clear();
2546 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2547 myShapeIDMap.Add( TopExp::FirstVertex( *elIt, true ));
2548 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
2549 myShapeIDMap.Add( *elIt );
2550 myShapeIDMap.Add( face );
2552 } // there are inner wires
2554 // Compute XYZ of on-edge points
2556 TopLoc_Location loc;
2557 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2559 BRepAdaptor_Curve C3d( *elIt );
2560 list< TPoint* > & ePoints = getShapePoints( iE++ );
2561 pIt = ePoints.begin();
2562 for ( pIt++; pIt != ePoints.end(); pIt++ )
2564 TPoint* point = *pIt;
2565 point->myXYZ = C3d.Value( point->myU );
2569 // Compute UV and XYZ of in-face points
2571 // try to use a simple algo
2572 list< TPoint* > & fPoints = getShapePoints( face );
2573 bool isDeformed = false;
2574 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2575 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2576 (*pIt)->myUV, isDeformed )) {
2577 MESSAGE("cant Apply(face)");
2580 // try to use a complex algo if it is a difficult case
2581 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2583 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2584 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2585 (*pIt)->myUV, isDeformed )) {
2586 MESSAGE("cant Apply(face)");
2591 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2592 const gp_Trsf & aTrsf = loc.Transformation();
2593 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2595 TPoint * point = *pIt;
2596 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2597 if ( !loc.IsIdentity() )
2598 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2601 myIsComputed = true;
2603 return setErrorCode( ERR_OK );
2606 //=======================================================================
2608 //purpose : Compute nodes coordinates applying
2609 // the loaded pattern to <theFace>. The first key-point
2610 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2611 //=======================================================================
2613 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2614 const int theNodeIndexOnKeyPoint1,
2615 const bool theReverse)
2617 // MESSAGE(" ::Apply(MeshFace) " );
2619 if ( !IsLoaded() ) {
2620 MESSAGE( "Pattern not loaded" );
2621 return setErrorCode( ERR_APPL_NOT_LOADED );
2624 // check nb of nodes
2625 const int nbFaceNodes = theFace->NbCornerNodes();
2626 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2627 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2628 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2631 // find points on edges, it fills myNbKeyPntInBoundary
2632 if ( !findBoundaryPoints() )
2635 // check that there are no holes in a pattern
2636 if (myNbKeyPntInBoundary.size() > 1 ) {
2637 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2640 // Define the nodes order
2642 list< const SMDS_MeshNode* > nodes;
2643 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2644 SMDS_NodeIteratorPtr noIt = theFace->nodeIterator();
2646 while ( noIt->more() && iSub < nbFaceNodes ) {
2647 const SMDS_MeshNode* node = noIt->next();
2648 nodes.push_back( node );
2649 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2652 if ( n != nodes.end() ) {
2654 if ( n != --nodes.end() )
2655 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2658 else if ( n != nodes.begin() )
2659 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2661 list< gp_XYZ > xyzList;
2662 myOrderedNodes.resize( nbFaceNodes );
2663 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2664 xyzList.push_back( SMESH_TNodeXYZ( *n ));
2665 myOrderedNodes[ iSub++] = *n;
2668 // Define a face plane
2670 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2671 gp_Pnt P ( *xyzIt++ );
2672 gp_Vec Vx( P, *xyzIt++ ), N;
2674 N = Vx ^ gp_Vec( P, *xyzIt++ );
2675 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2676 if ( N.SquareMagnitude() <= DBL_MIN )
2677 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2678 gp_Ax2 pos( P, N, Vx );
2680 // Compute UV of key-points on a plane
2681 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2683 gp_Vec vec ( pos.Location(), *xyzIt );
2684 TPoint* p = getShapePoints( iSub ).front();
2685 p->myUV.SetX( vec * pos.XDirection() );
2686 p->myUV.SetY( vec * pos.YDirection() );
2690 // points on edges to be used for UV computation of in-face points
2691 list< list< TPoint* > > edgesPointsList;
2692 edgesPointsList.push_back( list< TPoint* >() );
2693 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2694 list< TPoint* >::iterator pIt;
2696 // compute UV and XYZ of points on edges
2698 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2700 gp_XYZ& xyz1 = *xyzIt++;
2701 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2703 list< TPoint* > & ePoints = getShapePoints( iSub );
2704 ePoints.back()->myInitU = 1.0;
2705 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2706 while ( *pIt != ePoints.back() )
2709 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2710 gp_Vec vec ( pos.Location(), p->myXYZ );
2711 p->myUV.SetX( vec * pos.XDirection() );
2712 p->myUV.SetY( vec * pos.YDirection() );
2714 // collect on-edge points (excluding the last one)
2715 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2718 // Compute UV and XYZ of in-face points
2720 // try to use a simple algo to compute UV
2721 list< TPoint* > & fPoints = getShapePoints( iSub );
2722 bool isDeformed = false;
2723 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2724 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2725 (*pIt)->myUV, isDeformed )) {
2726 MESSAGE("cant Apply(face)");
2729 // try to use a complex algo if it is a difficult case
2730 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2732 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2733 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2734 (*pIt)->myUV, isDeformed )) {
2735 MESSAGE("cant Apply(face)");
2740 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2742 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2745 myIsComputed = true;
2747 return setErrorCode( ERR_OK );
2750 //=======================================================================
2752 //purpose : Compute nodes coordinates applying
2753 // the loaded pattern to <theFace>. The first key-point
2754 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2755 //=======================================================================
2757 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2758 const SMDS_MeshFace* theFace,
2759 const TopoDS_Shape& theSurface,
2760 const int theNodeIndexOnKeyPoint1,
2761 const bool theReverse)
2763 // MESSAGE(" ::Apply(MeshFace) " );
2764 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2765 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2767 const TopoDS_Face& face = TopoDS::Face( theSurface );
2768 TopLoc_Location loc;
2769 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2770 const gp_Trsf & aTrsf = loc.Transformation();
2772 if ( !IsLoaded() ) {
2773 MESSAGE( "Pattern not loaded" );
2774 return setErrorCode( ERR_APPL_NOT_LOADED );
2777 // check nb of nodes
2778 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2779 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2780 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2783 // find points on edges, it fills myNbKeyPntInBoundary
2784 if ( !findBoundaryPoints() )
2787 // check that there are no holes in a pattern
2788 if (myNbKeyPntInBoundary.size() > 1 ) {
2789 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2792 // Define the nodes order
2794 list< const SMDS_MeshNode* > nodes;
2795 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2796 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2798 while ( noIt->more() ) {
2799 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2800 nodes.push_back( node );
2801 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2804 if ( n != nodes.end() ) {
2806 if ( n != --nodes.end() )
2807 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2810 else if ( n != nodes.begin() )
2811 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2814 // find a node not on a seam edge, if necessary
2815 SMESH_MesherHelper helper( *theMesh );
2816 helper.SetSubShape( theSurface );
2817 const SMDS_MeshNode* inFaceNode = 0;
2818 if ( helper.GetNodeUVneedInFaceNode() )
2820 SMESH_MeshEditor editor( theMesh );
2821 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2822 int shapeID = editor.FindShape( *n );
2824 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2825 if ( !helper.IsSeamShape( shapeID ))
2830 // Set UV of key-points (i.e. of nodes of theFace )
2831 vector< gp_XY > keyUV( theFace->NbNodes() );
2832 myOrderedNodes.resize( theFace->NbNodes() );
2833 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2835 TPoint* p = getShapePoints( iSub ).front();
2836 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2837 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2839 keyUV[ iSub-1 ] = p->myUV;
2840 myOrderedNodes[ iSub-1 ] = *n;
2843 // points on edges to be used for UV computation of in-face points
2844 list< list< TPoint* > > edgesPointsList;
2845 edgesPointsList.push_back( list< TPoint* >() );
2846 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2847 list< TPoint* >::iterator pIt;
2849 // compute UV and XYZ of points on edges
2851 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2853 gp_XY& uv1 = keyUV[ i ];
2854 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2856 list< TPoint* > & ePoints = getShapePoints( iSub );
2857 ePoints.back()->myInitU = 1.0;
2858 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2859 while ( *pIt != ePoints.back() )
2862 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2863 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2864 if ( !loc.IsIdentity() )
2865 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2867 // collect on-edge points (excluding the last one)
2868 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2871 // Compute UV and XYZ of in-face points
2873 // try to use a simple algo to compute UV
2874 list< TPoint* > & fPoints = getShapePoints( iSub );
2875 bool isDeformed = false;
2876 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2877 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2878 (*pIt)->myUV, isDeformed )) {
2879 MESSAGE("cant Apply(face)");
2882 // try to use a complex algo if it is a difficult case
2883 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2885 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2886 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2887 (*pIt)->myUV, isDeformed )) {
2888 MESSAGE("cant Apply(face)");
2893 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2895 TPoint * point = *pIt;
2896 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2897 if ( !loc.IsIdentity() )
2898 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2901 myIsComputed = true;
2903 return setErrorCode( ERR_OK );
2906 //=======================================================================
2907 //function : undefinedXYZ
2909 //=======================================================================
2911 static const gp_XYZ& undefinedXYZ()
2913 static gp_XYZ xyz( 1.e100, 0., 0. );
2917 //=======================================================================
2918 //function : isDefined
2920 //=======================================================================
2922 inline static bool isDefined(const gp_XYZ& theXYZ)
2924 return theXYZ.X() < 1.e100;
2927 //=======================================================================
2929 //purpose : Compute nodes coordinates applying
2930 // the loaded pattern to <theFaces>. The first key-point
2931 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2932 //=======================================================================
2934 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2935 std::set<const SMDS_MeshFace*>& theFaces,
2936 const int theNodeIndexOnKeyPoint1,
2937 const bool theReverse)
2939 MESSAGE(" ::Apply(set<MeshFace>) " );
2941 if ( !IsLoaded() ) {
2942 MESSAGE( "Pattern not loaded" );
2943 return setErrorCode( ERR_APPL_NOT_LOADED );
2946 // find points on edges, it fills myNbKeyPntInBoundary
2947 if ( !findBoundaryPoints() )
2950 // check that there are no holes in a pattern
2951 if (myNbKeyPntInBoundary.size() > 1 ) {
2952 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2957 myElemXYZIDs.clear();
2958 myXYZIdToNodeMap.clear();
2960 myIdsOnBoundary.clear();
2961 myReverseConnectivity.clear();
2963 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2964 myElements.reserve( theFaces.size() );
2966 int ind1 = 0; // lowest point index for a face
2971 // SMESH_MeshEditor editor( theMesh );
2973 // apply to each face in theFaces set
2974 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
2975 for ( ; face != theFaces.end(); ++face )
2977 // int curShapeId = editor.FindShape( *face );
2978 // if ( curShapeId != shapeID ) {
2979 // if ( curShapeId )
2980 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
2983 // shapeID = curShapeId;
2986 if ( shape.IsNull() )
2987 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
2989 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
2991 MESSAGE( "Failed on " << *face );
2994 myElements.push_back( *face );
2996 // store computed points belonging to elements
2997 list< TElemDef >::iterator ll = myElemPointIDs.begin();
2998 for ( ; ll != myElemPointIDs.end(); ++ll )
3000 myElemXYZIDs.push_back(TElemDef());
3001 TElemDef& xyzIds = myElemXYZIDs.back();
3002 TElemDef& pIds = *ll;
3003 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3004 int pIndex = *id + ind1;
3005 xyzIds.push_back( pIndex );
3006 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3007 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3010 // put points on links to myIdsOnBoundary,
3011 // they will be used to sew new elements on adjacent refined elements
3012 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3013 for ( int i = 0; i < nbNodes; i++ )
3015 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3016 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3017 const SMDS_MeshNode* n2 = myOrderedNodes[( i+1 ) % nbNodes ];
3018 // make a link and a node set
3019 TNodeSet linkSet, node1Set;
3020 linkSet.insert( n1 );
3021 linkSet.insert( n2 );
3022 node1Set.insert( n1 );
3023 list< TPoint* >::iterator p = linkPoints.begin();
3025 // map the first link point to n1
3026 int nId = ( *p - &myPoints[0] ) + ind1;
3027 myXYZIdToNodeMap[ nId ] = n1;
3028 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3029 groups.push_back(list< int > ());
3030 groups.back().push_back( nId );
3032 // add the linkSet to the map
3033 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3034 groups.push_back(list< int > ());
3035 list< int >& indList = groups.back();
3036 // add points to the map excluding the end points
3037 for ( p++; *p != linkPoints.back(); p++ )
3038 indList.push_back( ( *p - &myPoints[0] ) + ind1 );
3040 ind1 += myPoints.size();
3043 return !myElemXYZIDs.empty();
3046 //=======================================================================
3048 //purpose : Compute nodes coordinates applying
3049 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3050 // will be mapped into <theNode000Index>-th node. The
3051 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3053 //=======================================================================
3055 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3056 const int theNode000Index,
3057 const int theNode001Index)
3059 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3061 if ( !IsLoaded() ) {
3062 MESSAGE( "Pattern not loaded" );
3063 return setErrorCode( ERR_APPL_NOT_LOADED );
3066 // bind ID to points
3067 if ( !findBoundaryPoints() )
3070 // check that there are no holes in a pattern
3071 if (myNbKeyPntInBoundary.size() > 1 ) {
3072 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3077 myElemXYZIDs.clear();
3078 myXYZIdToNodeMap.clear();
3080 myIdsOnBoundary.clear();
3081 myReverseConnectivity.clear();
3083 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3084 myElements.reserve( theVolumes.size() );
3086 // to find point index
3087 map< TPoint*, int > pointIndex;
3088 for ( int i = 0; i < myPoints.size(); i++ )
3089 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3091 int ind1 = 0; // lowest point index for an element
3093 // apply to each element in theVolumes set
3094 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3095 for ( ; vol != theVolumes.end(); ++vol )
3097 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3098 MESSAGE( "Failed on " << *vol );
3101 myElements.push_back( *vol );
3103 // store computed points belonging to elements
3104 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3105 for ( ; ll != myElemPointIDs.end(); ++ll )
3107 myElemXYZIDs.push_back(TElemDef());
3108 TElemDef& xyzIds = myElemXYZIDs.back();
3109 TElemDef& pIds = *ll;
3110 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3111 int pIndex = *id + ind1;
3112 xyzIds.push_back( pIndex );
3113 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3114 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3117 // put points on edges and faces to myIdsOnBoundary,
3118 // they will be used to sew new elements on adjacent refined elements
3119 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3121 // make a set of sub-points
3123 vector< int > subIDs;
3124 if ( SMESH_Block::IsVertexID( Id )) {
3125 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3127 else if ( SMESH_Block::IsEdgeID( Id )) {
3128 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3129 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3130 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3133 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3134 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3135 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3136 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3137 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3138 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3139 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3140 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3143 list< TPoint* > & points = getShapePoints( Id );
3144 list< TPoint* >::iterator p = points.begin();
3145 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3146 groups.push_back(list< int > ());
3147 list< int >& indList = groups.back();
3148 for ( ; p != points.end(); p++ )
3149 indList.push_back( pointIndex[ *p ] + ind1 );
3150 if ( subNodes.size() == 1 ) // vertex case
3151 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3153 ind1 += myPoints.size();
3156 return !myElemXYZIDs.empty();
3159 //=======================================================================
3161 //purpose : Create a pattern from the mesh built on <theBlock>
3162 //=======================================================================
3164 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3165 const TopoDS_Shell& theBlock)
3167 MESSAGE(" ::Load(volume) " );
3170 SMESHDS_SubMesh * aSubMesh;
3172 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3174 // load shapes in myShapeIDMap
3176 TopoDS_Vertex v1, v2;
3177 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3178 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3181 int nbNodes = 0, shapeID;
3182 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3184 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3185 aSubMesh = getSubmeshWithElements( theMesh, S );
3187 nbNodes += aSubMesh->NbNodes();
3189 myPoints.resize( nbNodes );
3191 // load U of points on edges
3192 TNodePointIDMap nodePointIDMap;
3194 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3196 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3197 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3198 aSubMesh = getSubmeshWithElements( theMesh, S );
3199 if ( ! aSubMesh ) continue;
3200 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3201 if ( !nIt->more() ) continue;
3203 // store a node and a point
3204 while ( nIt->more() ) {
3205 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3206 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3208 nodePointIDMap.insert( make_pair( node, iPoint ));
3209 if ( block.IsVertexID( shapeID ))
3210 myKeyPointIDs.push_back( iPoint );
3211 TPoint* p = & myPoints[ iPoint++ ];
3212 shapePoints.push_back( p );
3213 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3214 p->myInitXYZ.SetCoord( 0,0,0 );
3216 list< TPoint* >::iterator pIt = shapePoints.begin();
3219 switch ( S.ShapeType() )
3224 for ( ; pIt != shapePoints.end(); pIt++ ) {
3225 double * coef = block.GetShapeCoef( shapeID );
3226 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3227 if ( coef[ iCoord - 1] > 0 )
3228 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3230 if ( S.ShapeType() == TopAbs_VERTEX )
3233 const TopoDS_Edge& edge = TopoDS::Edge( S );
3235 BRep_Tool::Range( edge, f, l );
3236 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3237 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3238 pIt = shapePoints.begin();
3239 nIt = aSubMesh->GetNodes();
3240 for ( ; nIt->more(); pIt++ )
3242 const SMDS_MeshNode* node = nIt->next();
3243 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3245 const SMDS_EdgePosition* epos =
3246 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3247 double u = ( epos->GetUParameter() - f ) / ( l - f );
3248 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3253 for ( ; pIt != shapePoints.end(); pIt++ )
3255 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3256 MESSAGE( "!block.ComputeParameters()" );
3257 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3261 } // loop on block sub-shapes
3265 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3268 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3269 while ( elemIt->more() ) {
3270 const SMDS_MeshElement* elem = elemIt->next();
3271 myElemPointIDs.push_back( TElemDef() );
3272 TElemDef& elemPoints = myElemPointIDs.back();
3273 int nbNodes = elem->NbCornerNodes();
3274 for ( int i = 0;i < nbNodes; ++i )
3275 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3279 myIsBoundaryPointsFound = true;
3281 return setErrorCode( ERR_OK );
3284 //=======================================================================
3285 //function : getSubmeshWithElements
3286 //purpose : return submesh containing elements bound to theBlock in theMesh
3287 //=======================================================================
3289 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3290 const TopoDS_Shape& theShape)
3292 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3293 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3296 if ( theShape.ShapeType() == TopAbs_SHELL )
3298 // look for submesh of VOLUME
3299 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3300 for (; it.More(); it.Next()) {
3301 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3302 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3310 //=======================================================================
3312 //purpose : Compute nodes coordinates applying
3313 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3314 // will be mapped into <theVertex000>. The (0,0,1)
3315 // fifth key-point will be mapped into <theVertex001>.
3316 //=======================================================================
3318 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3319 const TopoDS_Vertex& theVertex000,
3320 const TopoDS_Vertex& theVertex001)
3322 MESSAGE(" ::Apply(volume) " );
3324 if (!findBoundaryPoints() || // bind ID to points
3325 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3328 SMESH_Block block; // bind ID to shape
3329 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3330 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3332 // compute XYZ of points on shapes
3334 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3336 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3337 list< TPoint* >::iterator pIt = shapePoints.begin();
3338 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3339 switch ( S.ShapeType() )
3341 case TopAbs_VERTEX: {
3343 for ( ; pIt != shapePoints.end(); pIt++ )
3344 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3349 for ( ; pIt != shapePoints.end(); pIt++ )
3350 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3355 for ( ; pIt != shapePoints.end(); pIt++ )
3356 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3360 for ( ; pIt != shapePoints.end(); pIt++ )
3361 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3363 } // loop on block sub-shapes
3365 myIsComputed = true;
3367 return setErrorCode( ERR_OK );
3370 //=======================================================================
3372 //purpose : Compute nodes coordinates applying
3373 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3374 // will be mapped into <theNode000Index>-th node. The
3375 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3377 //=======================================================================
3379 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3380 const int theNode000Index,
3381 const int theNode001Index)
3383 //MESSAGE(" ::Apply(MeshVolume) " );
3385 if (!findBoundaryPoints()) // bind ID to points
3388 SMESH_Block block; // bind ID to shape
3389 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3390 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3391 // compute XYZ of points on shapes
3393 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3395 list< TPoint* > & shapePoints = getShapePoints( ID );
3396 list< TPoint* >::iterator pIt = shapePoints.begin();
3398 if ( block.IsVertexID( ID ))
3399 for ( ; pIt != shapePoints.end(); pIt++ ) {
3400 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3402 else if ( block.IsEdgeID( ID ))
3403 for ( ; pIt != shapePoints.end(); pIt++ ) {
3404 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3406 else if ( block.IsFaceID( ID ))
3407 for ( ; pIt != shapePoints.end(); pIt++ ) {
3408 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3411 for ( ; pIt != shapePoints.end(); pIt++ )
3412 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3413 } // loop on block sub-shapes
3415 myIsComputed = true;
3417 return setErrorCode( ERR_OK );
3420 //=======================================================================
3421 //function : mergePoints
3422 //purpose : Merge XYZ on edges and/or faces.
3423 //=======================================================================
3425 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3427 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3428 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3430 list<list< int > >& groups = idListIt->second;
3431 if ( groups.size() < 2 )
3435 const TNodeSet& nodes = idListIt->first;
3436 double tol2 = 1.e-10;
3437 if ( nodes.size() > 1 ) {
3439 TNodeSet::const_iterator n = nodes.begin();
3440 for ( ; n != nodes.end(); ++n )
3441 box.Add( gp_Pnt( SMESH_TNodeXYZ( *n )));
3442 double x, y, z, X, Y, Z;
3443 box.Get( x, y, z, X, Y, Z );
3444 gp_Pnt p( x, y, z ), P( X, Y, Z );
3445 tol2 = 1.e-4 * p.SquareDistance( P );
3448 // to unite groups on link
3449 bool unite = ( uniteGroups && nodes.size() == 2 );
3450 map< double, int > distIndMap;
3451 const SMDS_MeshNode* node = *nodes.begin();
3452 gp_Pnt P = SMESH_TNodeXYZ( node );
3454 // compare points, replace indices
3456 list< int >::iterator ind1, ind2;
3457 list< list< int > >::iterator grpIt1, grpIt2;
3458 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3460 list< int >& indices1 = *grpIt1;
3462 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3464 list< int >& indices2 = *grpIt2;
3465 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3467 gp_XYZ& p1 = myXYZ[ *ind1 ];
3468 ind2 = indices2.begin();
3469 while ( ind2 != indices2.end() )
3471 gp_XYZ& p2 = myXYZ[ *ind2 ];
3472 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3473 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3475 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3476 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3477 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3478 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3480 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3481 myXYZ[ *ind2 ] = undefinedXYZ();
3482 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3484 ind2 = indices2.erase( ind2 );
3491 if ( unite ) { // sort indices using distIndMap
3492 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3494 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3495 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3496 distIndMap.insert( make_pair( dist, *ind1 ));
3500 if ( unite ) { // put all sorted indices into the first group
3501 list< int >& g = groups.front();
3503 map< double, int >::iterator dist_ind = distIndMap.begin();
3504 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3505 g.push_back( dist_ind->second );
3507 } // loop on myIdsOnBoundary
3510 //=======================================================================
3511 //function : makePolyElements
3512 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3513 //=======================================================================
3515 void SMESH_Pattern::
3516 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3517 const bool toCreatePolygons,
3518 const bool toCreatePolyedrs)
3520 myPolyElemXYZIDs.clear();
3521 myPolyElems.clear();
3522 myPolyElems.reserve( myIdsOnBoundary.size() );
3524 // make a set of refined elements
3525 TIDSortedElemSet avoidSet, elemSet;
3526 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3527 for(; itv!=myElements.end(); itv++) {
3528 const SMDS_MeshElement* el = (*itv);
3529 avoidSet.insert( el );
3531 //avoidSet.insert( myElements.begin(), myElements.end() );
3533 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3535 if ( toCreatePolygons )
3537 int lastFreeId = myXYZ.size();
3539 // loop on links of refined elements
3540 indListIt = myIdsOnBoundary.begin();
3541 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3543 const TNodeSet & linkNodes = indListIt->first;
3544 if ( linkNodes.size() != 2 )
3545 continue; // skip face
3546 const SMDS_MeshNode* n1 = * linkNodes.begin();
3547 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3549 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3550 if ( idGroups.empty() || idGroups.front().empty() )
3553 // find not refined face having n1-n2 link
3557 const SMDS_MeshElement* face =
3558 SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3561 avoidSet.insert ( face );
3562 myPolyElems.push_back( face );
3564 // some links of <face> are split;
3565 // make list of xyz for <face>
3566 myPolyElemXYZIDs.push_back(TElemDef());
3567 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3568 // loop on links of a <face>
3569 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3570 int i = 0, nbNodes = face->NbNodes();
3571 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3572 while ( nIt->more() )
3573 nodes[ i++ ] = smdsNode( nIt->next() );
3574 nodes[ i ] = nodes[ 0 ];
3575 for ( i = 0; i < nbNodes; ++i )
3577 // look for point mapped on a link
3578 TNodeSet faceLinkNodes;
3579 faceLinkNodes.insert( nodes[ i ] );
3580 faceLinkNodes.insert( nodes[ i + 1 ] );
3581 if ( faceLinkNodes == linkNodes )
3582 nn_IdList = indListIt;
3584 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3585 // add face point ids
3586 faceNodeIds.push_back( ++lastFreeId );
3587 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3588 if ( nn_IdList != myIdsOnBoundary.end() )
3590 // there are points mapped on a link
3591 list< int >& mappedIds = nn_IdList->second.front();
3592 if ( isReversed( nodes[ i ], mappedIds ))
3593 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3595 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3597 } // loop on links of a <face>
3603 if ( myIs2D && idGroups.size() > 1 ) {
3605 // sew new elements on 2 refined elements sharing n1-n2 link
3607 list< int >& idsOnLink = idGroups.front();
3608 // temporarily add ids of link nodes to idsOnLink
3609 bool rev = isReversed( n1, idsOnLink );
3610 for ( int i = 0; i < 2; ++i )
3613 nodeSet.insert( i ? n2 : n1 );
3614 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3615 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3616 int nodeId = groups.front().front();
3618 if ( rev ) append = !append;
3620 idsOnLink.push_back( nodeId );
3622 idsOnLink.push_front( nodeId );
3624 list< int >::iterator id = idsOnLink.begin();
3625 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3627 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3628 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3629 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3631 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3632 // look for <id> in element definition
3633 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3634 ASSERT ( idDef != pIdList->end() );
3635 // look for 2 neighbour ids of <id> in element definition
3636 for ( int prev = 0; prev < 2; ++prev ) {
3637 TElemDef::iterator idDef2 = idDef;
3639 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3641 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3642 // look for idDef2 on a link starting from id
3643 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3644 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3645 // insert ids located on link between <id> and <id2>
3646 // into the element definition between idDef and idDef2
3648 for ( ; id2 != id; --id2 )
3649 pIdList->insert( idDef, *id2 );
3651 list< int >::iterator id1 = id;
3652 for ( ++id1, ++id2; id1 != id2; ++id1 )
3653 pIdList->insert( idDef2, *id1 );
3659 // remove ids of link nodes
3660 idsOnLink.pop_front();
3661 idsOnLink.pop_back();
3663 } // loop on myIdsOnBoundary
3664 } // if ( toCreatePolygons )
3666 if ( toCreatePolyedrs )
3668 // check volumes adjacent to the refined elements
3669 SMDS_VolumeTool volTool;
3670 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3671 for ( ; refinedElem != myElements.end(); ++refinedElem )
3673 // loop on nodes of refinedElem
3674 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3675 while ( nIt->more() ) {
3676 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3677 // loop on inverse elements of node
3678 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3679 while ( eIt->more() )
3681 const SMDS_MeshElement* elem = eIt->next();
3682 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3683 continue; // skip faces or refined elements
3684 // add polyhedron definition
3685 myPolyhedronQuantities.push_back(vector<int> ());
3686 myPolyElemXYZIDs.push_back(TElemDef());
3687 vector<int>& quantity = myPolyhedronQuantities.back();
3688 TElemDef & elemDef = myPolyElemXYZIDs.back();
3689 // get definitions of new elements on volume faces
3690 bool makePoly = false;
3691 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3693 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3694 volTool.NbFaceNodes( iF ),
3695 theNodes, elemDef, quantity))
3699 myPolyElems.push_back( elem );
3701 myPolyhedronQuantities.pop_back();
3702 myPolyElemXYZIDs.pop_back();
3710 //=======================================================================
3711 //function : getFacesDefinition
3712 //purpose : return faces definition for a volume face defined by theBndNodes
3713 //=======================================================================
3715 bool SMESH_Pattern::
3716 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3717 const int theNbBndNodes,
3718 const vector< const SMDS_MeshNode* >& theNodes,
3719 list< int >& theFaceDefs,
3720 vector<int>& theQuantity)
3722 bool makePoly = false;
3724 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3726 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3728 // make a set of all nodes on a face
3730 if ( !myIs2D ) { // for 2D, merge only edges
3731 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3732 if ( nn_IdList != myIdsOnBoundary.end() ) {
3733 list< int > & faceIds = nn_IdList->second.front();
3734 if ( !faceIds.empty() ) {
3736 ids.insert( faceIds.begin(), faceIds.end() );
3741 // add ids on links and bnd nodes
3742 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3743 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3744 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3746 // add id of iN-th bnd node
3748 nSet.insert( theBndNodes[ iN ] );
3749 nn_IdList = myIdsOnBoundary.find( nSet );
3750 int bndId = ++lastFreeId;
3751 if ( nn_IdList != myIdsOnBoundary.end() ) {
3752 bndId = nn_IdList->second.front().front();
3753 ids.insert( bndId );
3756 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3758 faceDef.push_back( bndId );
3759 // add ids on a link
3761 linkNodes.insert( theBndNodes[ iN ]);
3762 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3763 nn_IdList = myIdsOnBoundary.find( linkNodes );
3764 if ( nn_IdList != myIdsOnBoundary.end() ) {
3765 list< int > & linkIds = nn_IdList->second.front();
3766 if ( !linkIds.empty() )
3769 ids.insert( linkIds.begin(), linkIds.end() );
3770 if ( isReversed( theBndNodes[ iN ], linkIds ))
3771 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3773 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3778 // find faces definition of new volumes
3780 bool defsAdded = false;
3781 if ( !myIs2D ) { // for 2D, merge only edges
3782 SMDS_VolumeTool vol;
3783 set< TElemDef* > checkedVolDefs;
3784 set< int >::iterator id = ids.begin();
3785 for ( ; id != ids.end(); ++id )
3787 // definitions of volumes sharing id
3788 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3789 ASSERT( !defList.empty() );
3790 // loop on volume definitions
3791 list< TElemDef* >::iterator pIdList = defList.begin();
3792 for ( ; pIdList != defList.end(); ++pIdList)
3794 if ( !checkedVolDefs.insert( *pIdList ).second )
3795 continue; // skip already checked volume definition
3796 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3797 // loop on face defs of a volume
3798 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3799 if ( volType == SMDS_VolumeTool::UNKNOWN )
3801 int nbFaces = vol.NbFaces( volType );
3802 for ( int iF = 0; iF < nbFaces; ++iF )
3804 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3805 int iN, nbN = vol.NbFaceNodes( volType, iF );
3806 // check if all nodes of a faces are in <ids>
3808 for ( iN = 0; iN < nbN && all; ++iN ) {
3809 int nodeId = idVec[ nodeInds[ iN ]];
3810 all = ( ids.find( nodeId ) != ids.end() );
3813 // store a face definition
3814 for ( iN = 0; iN < nbN; ++iN ) {
3815 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3817 theQuantity.push_back( nbN );
3825 theQuantity.push_back( faceDef.size() );
3826 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3832 //=======================================================================
3833 //function : clearSubMesh
3835 //=======================================================================
3837 static bool clearSubMesh( SMESH_Mesh* theMesh,
3838 const TopoDS_Shape& theShape)
3840 bool removed = false;
3841 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3843 removed = !aSubMesh->IsEmpty();
3845 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3848 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3849 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3851 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3852 removed = eIt->more();
3853 while ( eIt->more() )
3854 aMeshDS->RemoveElement( eIt->next() );
3855 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3856 removed = removed || nIt->more();
3857 while ( nIt->more() )
3858 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3864 //=======================================================================
3865 //function : clearMesh
3866 //purpose : clear mesh elements existing on myShape in theMesh
3867 //=======================================================================
3869 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3872 if ( !myShape.IsNull() )
3874 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3875 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3876 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3878 clearSubMesh( theMesh, it.Value() );
3884 //=======================================================================
3885 //function : MakeMesh
3886 //purpose : Create nodes and elements in <theMesh> using nodes
3887 // coordinates computed by either of Apply...() methods
3888 // WARNING : StdMeshers_Projection_... relies on MakeMesh() behavior: that
3889 // it does not care of nodes and elements already existing on
3890 // sub-shapes. DO NOT MERGE them or modify also StdMeshers_Projection_..
3891 //=======================================================================
3893 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
3894 const bool toCreatePolygons,
3895 const bool toCreatePolyedrs)
3897 MESSAGE(" ::MakeMesh() " );
3898 if ( !myIsComputed )
3899 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
3901 mergePoints( toCreatePolygons );
3903 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3905 // clear elements and nodes existing on myShape
3908 bool onMeshElements = ( !myElements.empty() );
3910 // Create missing nodes
3912 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
3913 if ( onMeshElements )
3915 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
3916 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
3917 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
3918 nodesVector[ i_node->first ] = i_node->second;
3920 for ( int i = 0; i < myXYZ.size(); ++i ) {
3921 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
3922 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
3926 if ( theMesh->HasShapeToMesh() )
3928 // set nodes on EDGEs (IMP 22368)
3929 SMESH_MesherHelper helper( *theMesh );
3930 helper.ToFixNodeParameters( true );
3931 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3932 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3934 list<list< int > >& groups = idListIt->second;
3935 const TNodeSet& nodes = idListIt->first;
3936 if ( nodes.size() != 2 )
3937 continue; // not a link
3938 const SMDS_MeshNode* n1 = *nodes.begin();
3939 const SMDS_MeshNode* n2 = *nodes.rbegin();
3940 TopoDS_Shape S1 = helper.GetSubShapeByNode( n1, aMeshDS );
3941 TopoDS_Shape S2 = helper.GetSubShapeByNode( n2, aMeshDS );
3942 if ( S1.IsNull() || S1.ShapeType() < TopAbs_EDGE ||
3943 S2.IsNull() || S2.ShapeType() < TopAbs_EDGE )
3946 if ( S1.ShapeType() == TopAbs_EDGE )
3948 if ( S1 == S2 || helper.IsSubShape( S2, S1 ))
3951 else if ( S2.ShapeType() == TopAbs_EDGE )
3953 if ( helper.IsSubShape( S1, S2 ))
3958 S = helper.GetCommonAncestor( S1, S2, *theMesh, TopAbs_EDGE );
3962 const TopoDS_Edge & E = TopoDS::Edge( S );
3963 helper.SetSubShape( E );
3964 list<list< int > >::iterator g = groups.begin();
3965 for ( ; g != groups.end(); ++g )
3967 list< int >& ids = *g;
3968 list< int >::iterator id = ids.begin();
3969 for ( ; id != ids.end(); ++id )
3970 if ( nodesVector[ *id ] && nodesVector[ *id ]->getshapeId() < 1 )
3973 aMeshDS->SetNodeOnEdge( nodesVector[ *id ], E, u );
3974 helper.CheckNodeU( E, nodesVector[ *id ], u, 1e-7, true );
3979 } // if ( onMeshElements )
3983 nodesVector.resize( myPoints.size(), 0 );
3985 // find existing nodes on EDGEs and VERTEXes (IMP 22368)
3986 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
3987 if ( !myShapeIDMap.IsEmpty() && aMeshDS->NbNodes() > 0 )
3989 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
3991 const TopoDS_Shape& S = myShapeIDMap( idPointIt->first );
3992 list< TPoint* > & points = idPointIt->second;
3993 if ( points.empty() )
3996 switch ( S.ShapeType() )
4000 int pIndex = points.back() - &myPoints[0];
4001 if ( !nodesVector[ pIndex ] )
4002 nodesVector[ pIndex ] = SMESH_Algo::VertexNode( TopoDS::Vertex( S ), aMeshDS );
4007 const TopoDS_Edge& edge = TopoDS::Edge( S );
4008 map< double, const SMDS_MeshNode* > paramsOfNodes;
4009 if ( !SMESH_Algo::GetSortedNodesOnEdge( aMeshDS, edge,
4010 /*ignoreMediumNodes=*/false,
4012 || paramsOfNodes.size() < 3 )
4014 // points on VERTEXes are included with wrong myU
4015 list< TPoint* >::reverse_iterator pItR = ++points.rbegin();
4016 list< TPoint* >::iterator pItF = ++points.begin();
4017 const bool isForward = ( (*pItF)->myU < (*pItR)->myU );
4018 map< double, const SMDS_MeshNode* >::iterator u2n = ++paramsOfNodes.begin();
4019 map< double, const SMDS_MeshNode* >::iterator u2nEnd = --paramsOfNodes.end();
4021 while ( u2n != u2nEnd && pItF != points.end() )
4023 const double u = u2n->first;
4024 const SMDS_MeshNode* n = u2n->second;
4025 const double tol = ( (++u2n)->first - u ) / 20;
4028 p = ( isForward ? *pItF : *pItR );
4029 if ( Abs( u - p->myU ) < tol )
4031 int pIndex = p - &myPoints[0];
4032 if ( !nodesVector [ pIndex ] )
4033 nodesVector [ pIndex ] = n;
4039 while ( p->myU < u && ( ++pItF, ++pItR != points.rend() ));
4045 } // end of "find existing nodes on EDGEs and VERTEXes"
4047 // loop on sub-shapes of myShape: create nodes
4048 idPointIt = myShapeIDToPointsMap.begin();
4049 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
4052 if ( !myShapeIDMap.IsEmpty() ) {
4053 S = myShapeIDMap( idPointIt->first );
4055 list< TPoint* > & points = idPointIt->second;
4056 list< TPoint* >::iterator pIt = points.begin();
4057 for ( ; pIt != points.end(); pIt++ )
4059 TPoint* point = *pIt;
4060 //int pIndex = pointIndex[ point ];
4061 int pIndex = point - &myPoints[0];
4062 if ( nodesVector [ pIndex ] )
4064 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
4067 nodesVector [ pIndex ] = node;
4069 if ( !S.IsNull() /*subMeshDS*/ ) {
4070 // !!!!! do not merge new nodes with ones existing on submeshes (see method comment)
4071 switch ( S.ShapeType() ) {
4072 case TopAbs_VERTEX: {
4073 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
4076 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
4079 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
4080 point->myUV.X(), point->myUV.Y() ); break;
4083 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
4092 if ( onMeshElements )
4094 // prepare data to create poly elements
4095 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
4098 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
4099 // sew old and new elements
4100 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
4104 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4107 aMeshDS->compactMesh();
4109 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4110 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4111 // for ( ; i_sm != sm.end(); i_sm++ )
4113 // cout << " SM " << i_sm->first << " ";
4114 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4115 // //SMDS_ElemIteratorPtr GetElements();
4116 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4117 // while ( nit->more() )
4118 // cout << nit->next()->GetID() << " ";
4121 return setErrorCode( ERR_OK );
4124 //=======================================================================
4125 //function : createElements
4126 //purpose : add elements to the mesh
4127 //=======================================================================
4129 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4130 const vector<const SMDS_MeshNode* >& theNodesVector,
4131 const list< TElemDef > & theElemNodeIDs,
4132 const vector<const SMDS_MeshElement*>& theElements)
4134 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4135 SMESH_MeshEditor editor( theMesh );
4137 bool onMeshElements = !theElements.empty();
4139 // shapes and groups theElements are on
4140 vector< int > shapeIDs;
4141 vector< list< SMESHDS_Group* > > groups;
4142 set< const SMDS_MeshNode* > shellNodes;
4143 if ( onMeshElements )
4145 shapeIDs.resize( theElements.size() );
4146 groups.resize( theElements.size() );
4147 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4148 set<SMESHDS_GroupBase*>::const_iterator grIt;
4149 for ( int i = 0; i < theElements.size(); i++ )
4151 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4152 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4153 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4154 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4155 groups[ i ].push_back( group );
4158 // get all nodes bound to shells because their SpacePosition is not set
4159 // by SMESHDS_Mesh::SetNodeInVolume()
4160 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4161 if ( !aMainShape.IsNull() ) {
4162 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4163 for ( ; shellExp.More(); shellExp.Next() )
4165 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4167 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4168 while ( nIt->more() )
4169 shellNodes.insert( nIt->next() );
4174 // nb new elements per a refined element
4175 int nbNewElemsPerOld = 1;
4176 if ( onMeshElements )
4177 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4181 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4182 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4183 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4185 const TElemDef & elemNodeInd = *enIt;
4187 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4188 TElemDef::const_iterator id = elemNodeInd.begin();
4190 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4191 if ( *id < theNodesVector.size() )
4192 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4194 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4196 // dim of refined elem
4197 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4198 if ( onMeshElements ) {
4199 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4202 const SMDS_MeshElement* elem = 0;
4204 switch ( nbNodes ) {
4206 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4208 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4210 if ( !onMeshElements ) {// create a quadratic face
4211 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4212 nodes[4], nodes[5] ); break;
4213 } // else do not break but create a polygon
4215 if ( !onMeshElements ) {// create a quadratic face
4216 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4217 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4218 } // else do not break but create a polygon
4220 elem = aMeshDS->AddPolygonalFace( nodes );
4224 switch ( nbNodes ) {
4226 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4228 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4231 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4232 nodes[4], nodes[5] ); break;
4234 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4235 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4237 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4240 // set element on a shape
4241 if ( elem && onMeshElements ) // applied to mesh elements
4243 int shapeID = shapeIDs[ elemIndex ];
4244 if ( shapeID > 0 ) {
4245 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4246 // set nodes on a shape
4247 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4248 if ( S.ShapeType() == TopAbs_SOLID ) {
4249 TopoDS_Iterator shellIt( S );
4250 if ( shellIt.More() )
4251 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4253 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4254 while ( noIt->more() ) {
4255 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4256 if ( node->getshapeId() < 1 &&
4257 shellNodes.find( node ) == shellNodes.end() )
4259 if ( S.ShapeType() == TopAbs_FACE )
4260 aMeshDS->SetNodeOnFace( node, shapeID,
4261 Precision::Infinite(),// <- it's a sign that UV is not set
4262 Precision::Infinite());
4264 aMeshDS->SetNodeInVolume( node, shapeID );
4265 shellNodes.insert( node );
4270 // add elem in groups
4271 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4272 for ( ; g != groups[ elemIndex ].end(); ++g )
4273 (*g)->SMDSGroup().Add( elem );
4275 if ( elem && !myShape.IsNull() ) // applied to shape
4276 aMeshDS->SetMeshElementOnShape( elem, myShape );
4279 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4280 // so that operations with hypotheses will erase the mesh being built
4282 SMESH_subMesh * subMesh;
4283 if ( !myShape.IsNull() ) {
4284 subMesh = theMesh->GetSubMesh( myShape );
4286 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4288 if ( onMeshElements ) {
4289 list< int > elemIDs;
4290 for ( int i = 0; i < theElements.size(); i++ )
4292 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4294 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4296 elemIDs.push_back( theElements[ i ]->GetID() );
4298 // remove refined elements
4299 editor.Remove( elemIDs, false );
4303 //=======================================================================
4304 //function : isReversed
4305 //purpose : check xyz ids order in theIdsList taking into account
4306 // theFirstNode on a link
4307 //=======================================================================
4309 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4310 const list< int >& theIdsList) const
4312 if ( theIdsList.size() < 2 )
4315 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4317 list<int>::const_iterator id = theIdsList.begin();
4318 for ( int i = 0; i < 2; ++i, ++id ) {
4319 if ( *id < myXYZ.size() )
4320 P[ i ] = myXYZ[ *id ];
4322 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4323 i_n = myXYZIdToNodeMap.find( *id );
4324 ASSERT( i_n != myXYZIdToNodeMap.end() );
4325 const SMDS_MeshNode* n = i_n->second;
4326 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4329 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4333 //=======================================================================
4334 //function : arrangeBoundaries
4335 //purpose : if there are several wires, arrange boundaryPoints so that
4336 // the outer wire goes first and fix inner wires orientation
4337 // update myKeyPointIDs to correspond to the order of key-points
4338 // in boundaries; sort internal boundaries by the nb of key-points
4339 //=======================================================================
4341 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4343 typedef list< list< TPoint* > >::iterator TListOfListIt;
4344 TListOfListIt bndIt;
4345 list< TPoint* >::iterator pIt;
4347 int nbBoundaries = boundaryList.size();
4348 if ( nbBoundaries > 1 )
4350 // sort boundaries by nb of key-points
4351 if ( nbBoundaries > 2 )
4353 // move boundaries in tmp list
4354 list< list< TPoint* > > tmpList;
4355 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4356 // make a map nb-key-points to boundary-position-in-tmpList,
4357 // boundary-positions get ordered in it
4358 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4359 TNbKpBndPosMap nbKpBndPosMap;
4360 bndIt = tmpList.begin();
4361 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4362 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4363 int nb = *nbKpIt * nbBoundaries;
4364 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4366 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4368 // move boundaries back to boundaryList
4369 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4370 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4371 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4372 TListOfListIt bndPos1 = bndPos2++;
4373 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4377 // Look for the outer boundary: the one with the point with the least X
4378 double leastX = DBL_MAX;
4379 TListOfListIt outerBndPos;
4380 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4382 list< TPoint* >& boundary = (*bndIt);
4383 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4385 TPoint* point = *pIt;
4386 if ( point->myInitXYZ.X() < leastX ) {
4387 leastX = point->myInitXYZ.X();
4388 outerBndPos = bndIt;
4393 if ( outerBndPos != boundaryList.begin() )
4394 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4396 } // if nbBoundaries > 1
4398 // Check boundaries orientation and re-fill myKeyPointIDs
4400 set< TPoint* > keyPointSet;
4401 list< int >::iterator kpIt = myKeyPointIDs.begin();
4402 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4403 keyPointSet.insert( & myPoints[ *kpIt ]);
4404 myKeyPointIDs.clear();
4406 // update myNbKeyPntInBoundary also
4407 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4409 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4411 // find the point with the least X
4412 double leastX = DBL_MAX;
4413 list< TPoint* >::iterator xpIt;
4414 list< TPoint* >& boundary = (*bndIt);
4415 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4417 TPoint* point = *pIt;
4418 if ( point->myInitXYZ.X() < leastX ) {
4419 leastX = point->myInitXYZ.X();
4423 // find points next to the point with the least X
4424 TPoint* p = *xpIt, *pPrev, *pNext;
4425 if ( p == boundary.front() )
4426 pPrev = *(++boundary.rbegin());
4432 if ( p == boundary.back() )
4433 pNext = *(++boundary.begin());
4438 // vectors of boundary direction near <p>
4439 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4440 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4441 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4442 double yPrev = v1.Y() / sqrt( sqMag1 );
4443 double yNext = v2.Y() / sqrt( sqMag2 );
4444 double sumY = yPrev + yNext;
4446 if ( bndIt == boundaryList.begin() ) // outer boundary
4454 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4455 (*nbKpIt) = 0; // count nb of key-points again
4456 pIt = boundary.begin();
4457 for ( ; pIt != boundary.end(); pIt++)
4459 TPoint* point = *pIt;
4460 if ( keyPointSet.find( point ) == keyPointSet.end() )
4462 // find an index of a keypoint
4464 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4465 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4466 if ( &(*pVecIt) == point )
4468 myKeyPointIDs.push_back( index );
4471 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4474 } // loop on a list of boundaries
4476 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4479 //=======================================================================
4480 //function : findBoundaryPoints
4481 //purpose : if loaded from file, find points to map on edges and faces and
4482 // compute their parameters
4483 //=======================================================================
4485 bool SMESH_Pattern::findBoundaryPoints()
4487 if ( myIsBoundaryPointsFound ) return true;
4489 MESSAGE(" findBoundaryPoints() ");
4491 myNbKeyPntInBoundary.clear();
4495 set< TPoint* > pointsInElems;
4497 // Find free links of elements:
4498 // put links of all elements in a set and remove links encountered twice
4500 typedef pair< TPoint*, TPoint*> TLink;
4501 set< TLink > linkSet;
4502 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4503 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4505 TElemDef & elemPoints = *epIt;
4506 TElemDef::iterator pIt = elemPoints.begin();
4507 int prevP = elemPoints.back();
4508 for ( ; pIt != elemPoints.end(); pIt++ ) {
4509 TPoint* p1 = & myPoints[ prevP ];
4510 TPoint* p2 = & myPoints[ *pIt ];
4511 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4512 ASSERT( link.first != link.second );
4513 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4514 if ( !itUniq.second )
4515 linkSet.erase( itUniq.first );
4518 pointsInElems.insert( p1 );
4521 // Now linkSet contains only free links,
4522 // find the points order that they have in boundaries
4524 // 1. make a map of key-points
4525 set< TPoint* > keyPointSet;
4526 list< int >::iterator kpIt = myKeyPointIDs.begin();
4527 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4528 keyPointSet.insert( & myPoints[ *kpIt ]);
4530 // 2. chain up boundary points
4531 list< list< TPoint* > > boundaryList;
4532 boundaryList.push_back( list< TPoint* >() );
4533 list< TPoint* > * boundary = & boundaryList.back();
4535 TPoint *point1, *point2, *keypoint1;
4536 kpIt = myKeyPointIDs.begin();
4537 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4538 // loop on free links: look for the next point
4540 set< TLink >::iterator lIt = linkSet.begin();
4541 while ( lIt != linkSet.end() )
4543 if ( (*lIt).first == point1 )
4544 point2 = (*lIt).second;
4545 else if ( (*lIt).second == point1 )
4546 point2 = (*lIt).first;
4551 linkSet.erase( lIt );
4552 lIt = linkSet.begin();
4554 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4556 boundary->push_back( point2 );
4558 else // a key-point found
4560 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4562 if ( point2 != keypoint1 ) // its not the boundary end
4564 boundary->push_back( point2 );
4566 else // the boundary end reached
4568 boundary->push_front( keypoint1 );
4569 boundary->push_back( keypoint1 );
4570 myNbKeyPntInBoundary.push_back( iKeyPoint );
4571 if ( keyPointSet.empty() )
4572 break; // all boundaries containing key-points are found
4574 // prepare to search for the next boundary
4575 boundaryList.push_back( list< TPoint* >() );
4576 boundary = & boundaryList.back();
4577 point2 = keypoint1 = (*keyPointSet.begin());
4581 } // loop on the free links set
4583 if ( boundary->empty() ) {
4584 MESSAGE(" a separate key-point");
4585 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4588 // if there are several wires, arrange boundaryPoints so that
4589 // the outer wire goes first and fix inner wires orientation;
4590 // sort myKeyPointIDs to correspond to the order of key-points
4592 arrangeBoundaries( boundaryList );
4594 // Find correspondence shape ID - points,
4595 // compute points parameter on edge
4597 keyPointSet.clear();
4598 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4599 keyPointSet.insert( & myPoints[ *kpIt ]);
4601 set< TPoint* > edgePointSet; // to find in-face points
4602 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4603 int edgeID = myKeyPointIDs.size() + 1;
4605 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4606 for ( ; bndIt != boundaryList.end(); bndIt++ )
4608 boundary = & (*bndIt);
4609 double edgeLength = 0;
4610 list< TPoint* >::iterator pIt = boundary->begin();
4611 getShapePoints( edgeID ).push_back( *pIt );
4612 getShapePoints( vertexID++ ).push_back( *pIt );
4613 for ( pIt++; pIt != boundary->end(); pIt++)
4615 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4616 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4617 TPoint* point = *pIt;
4618 edgePointSet.insert( point );
4619 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4621 edgePoints.push_back( point );
4622 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4623 point->myInitU = edgeLength;
4627 // treat points on the edge which ends up: compute U [0,1]
4628 edgePoints.push_back( point );
4629 if ( edgePoints.size() > 2 ) {
4630 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4631 list< TPoint* >::iterator epIt = edgePoints.begin();
4632 for ( ; epIt != edgePoints.end(); epIt++ )
4633 (*epIt)->myInitU /= edgeLength;
4635 // begin the next edge treatment
4638 if ( point != boundary->front() ) { // not the first key-point again
4639 getShapePoints( edgeID ).push_back( point );
4640 getShapePoints( vertexID++ ).push_back( point );
4646 // find in-face points
4647 list< TPoint* > & facePoints = getShapePoints( edgeID );
4648 vector< TPoint >::iterator pVecIt = myPoints.begin();
4649 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4650 TPoint* point = &(*pVecIt);
4651 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4652 pointsInElems.find( point ) != pointsInElems.end())
4653 facePoints.push_back( point );
4660 // bind points to shapes according to point parameters
4661 vector< TPoint >::iterator pVecIt = myPoints.begin();
4662 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4663 TPoint* point = &(*pVecIt);
4664 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4665 getShapePoints( shapeID ).push_back( point );
4666 // detect key-points
4667 if ( SMESH_Block::IsVertexID( shapeID ))
4668 myKeyPointIDs.push_back( i );
4672 myIsBoundaryPointsFound = true;
4673 return myIsBoundaryPointsFound;
4676 //=======================================================================
4678 //purpose : clear fields
4679 //=======================================================================
4681 void SMESH_Pattern::Clear()
4683 myIsComputed = myIsBoundaryPointsFound = false;
4686 myKeyPointIDs.clear();
4687 myElemPointIDs.clear();
4688 myShapeIDToPointsMap.clear();
4689 myShapeIDMap.Clear();
4691 myNbKeyPntInBoundary.clear();
4694 myElemXYZIDs.clear();
4695 myXYZIdToNodeMap.clear();
4697 myOrderedNodes.clear();
4698 myPolyElems.clear();
4699 myPolyElemXYZIDs.clear();
4700 myPolyhedronQuantities.clear();
4701 myIdsOnBoundary.clear();
4702 myReverseConnectivity.clear();
4705 //================================================================================
4707 * \brief set ErrorCode and return true if it is Ok
4709 //================================================================================
4711 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4713 myErrorCode = theErrorCode;
4714 return myErrorCode == ERR_OK;
4717 //=======================================================================
4718 //function : setShapeToMesh
4719 //purpose : set a shape to be meshed. Return True if meshing is possible
4720 //=======================================================================
4722 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4724 if ( !IsLoaded() ) {
4725 MESSAGE( "Pattern not loaded" );
4726 return setErrorCode( ERR_APPL_NOT_LOADED );
4729 TopAbs_ShapeEnum aType = theShape.ShapeType();
4730 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4732 MESSAGE( "Pattern dimention mismatch" );
4733 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4736 // check if a face is closed
4737 int nbNodeOnSeamEdge = 0;
4739 TopTools_MapOfShape seamVertices;
4740 TopoDS_Face face = TopoDS::Face( theShape );
4741 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4742 for ( ; eExp.More() && nbNodeOnSeamEdge == 0; eExp.Next() ) {
4743 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4744 if ( BRep_Tool::IsClosed(ee, face) ) {
4745 // seam edge and vertices encounter twice in theFace
4746 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4747 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4752 // check nb of vertices
4753 TopTools_IndexedMapOfShape vMap;
4754 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4755 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4756 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4757 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4760 myElements.clear(); // not refine elements
4761 myElemXYZIDs.clear();
4763 myShapeIDMap.Clear();
4768 //=======================================================================
4769 //function : GetMappedPoints
4770 //purpose : Return nodes coordinates computed by Apply() method
4771 //=======================================================================
4773 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4776 if ( !myIsComputed )
4779 if ( myElements.empty() ) { // applied to shape
4780 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4781 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4782 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4784 else { // applied to mesh elements
4785 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4786 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4787 for ( ; xyz != myXYZ.end(); ++xyz )
4788 if ( !isDefined( *xyz ))
4789 thePoints.push_back( definedXYZ );
4791 thePoints.push_back( & (*xyz) );
4793 return !thePoints.empty();
4797 //=======================================================================
4798 //function : GetPoints
4799 //purpose : Return nodes coordinates of the pattern
4800 //=======================================================================
4802 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4809 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4810 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4811 thePoints.push_back( & (*pVecIt).myInitXYZ );
4813 return ( thePoints.size() > 0 );
4816 //=======================================================================
4817 //function : getShapePoints
4818 //purpose : return list of points located on theShape
4819 //=======================================================================
4821 list< SMESH_Pattern::TPoint* > &
4822 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4825 if ( !myShapeIDMap.Contains( theShape ))
4826 aShapeID = myShapeIDMap.Add( theShape );
4828 aShapeID = myShapeIDMap.FindIndex( theShape );
4830 return myShapeIDToPointsMap[ aShapeID ];
4833 //=======================================================================
4834 //function : getShapePoints
4835 //purpose : return list of points located on the shape
4836 //=======================================================================
4838 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4840 return myShapeIDToPointsMap[ theShapeID ];
4843 //=======================================================================
4844 //function : DumpPoints
4846 //=======================================================================
4848 void SMESH_Pattern::DumpPoints() const
4851 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4852 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4853 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4857 //=======================================================================
4858 //function : TPoint()
4860 //=======================================================================
4862 SMESH_Pattern::TPoint::TPoint()
4865 myInitXYZ.SetCoord(0,0,0);
4866 myInitUV.SetCoord(0.,0.);
4868 myXYZ.SetCoord(0,0,0);
4869 myUV.SetCoord(0.,0.);
4874 //=======================================================================
4875 //function : operator <<
4877 //=======================================================================
4879 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4881 gp_XYZ xyz = p.myInitXYZ;
4882 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4883 gp_XY xy = p.myInitUV;
4884 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4885 double u = p.myInitU;
4886 OS << " u( " << u << " )) " << &p << endl;
4887 xyz = p.myXYZ.XYZ();
4888 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4890 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4892 OS << " u( " << u << " ))" << endl;