1 // Copyright (C) 2007-2016 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 )
92 //=======================================================================
95 //=======================================================================
97 inline int getInt( const char * theSring )
99 if ( *theSring < '0' || *theSring > '9' )
103 int val = strtol( theSring, &ptr, 10 );
104 if ( ptr == theSring ||
105 // there must not be neither '.' nor ',' nor 'E' ...
106 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0' && *ptr != '\r'))
112 //=======================================================================
113 //function : getDouble
115 //=======================================================================
117 inline double getDouble( const char * theSring )
120 return strtod( theSring, &ptr );
123 //=======================================================================
124 //function : readLine
125 //purpose : Put token starting positions in theFields until '\n' or '\0'
126 // Return the number of the found tokens
127 //=======================================================================
129 int readLine (list <const char*> & theFields,
130 const char* & theLineBeg,
131 const bool theClearFields )
133 if ( theClearFields )
138 /* switch ( symbol ) { */
139 /* case white-space: */
140 /* look for a non-space symbol; */
141 /* case string-end: */
144 /* case comment beginning: */
145 /* skip all till a line-end; */
147 /* put its position in theFields, skip till a white-space;*/
153 bool stopReading = false;
156 bool isNumber = false;
157 switch ( *theLineBeg )
159 case ' ': // white space
164 case '\n': // a line ends
165 stopReading = ( nbRead > 0 );
170 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
174 case '\0': // file ends
177 case '-': // real number
182 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
184 theFields.push_back( theLineBeg );
187 while (*theLineBeg != ' ' &&
188 *theLineBeg != '\n' &&
189 *theLineBeg != '\0');
193 return 0; // incorrect file format
199 } while ( !stopReading );
204 //=======================================================================
205 //function : isRealSeam
206 //purpose : return true if an EDGE encounters twice in a FACE
207 //=======================================================================
209 // bool isRealSeam( const TopoDS_Edge& e, const TopoDS_Face& f )
211 // if ( BRep_Tool::IsClosed( e, f ))
214 // for (TopExp_Explorer exp( f, TopAbs_EDGE ); exp.More(); exp.Next())
215 // if ( exp.Current().IsSame( e ))
222 //=======================================================================
224 //purpose : load VERTEXes and EDGEs in a map. Return nb loaded VERTEXes
225 //=======================================================================
227 int loadVE( const list< TopoDS_Edge > & eList,
228 TopTools_IndexedMapOfOrientedShape & map )
230 list< TopoDS_Edge >::const_iterator eIt = eList.begin();
233 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
236 map.Add( TopExp::FirstVertex( *eIt, true ));
237 bool added = ( nbV < map.Extent() );
238 if ( !added ) { // vertex encountered twice
239 // a seam vertex have two corresponding key points
240 map.Add( TopExp::FirstVertex( *eIt, true ).Reversed());
246 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
254 //=======================================================================
255 //function : SMESH_Pattern
257 //=======================================================================
259 SMESH_Pattern::SMESH_Pattern (): myToKeepNodes(false)
263 //=======================================================================
265 //purpose : Load a pattern from <theFile>
266 //=======================================================================
268 bool SMESH_Pattern::Load (const char* theFileContents)
270 Kernel_Utils::Localizer loc;
274 // ! This is a comment
275 // NB_POINTS ! 1 integer - the number of points in the pattern.
276 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
277 // X2 Y2 [Z2] ! the pattern dimension is defined by the number of coordinates
279 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
280 // ! elements description goes after all
281 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
286 const char* lineBeg = theFileContents;
287 list <const char*> fields;
288 const bool clearFields = true;
290 // NB_POINTS ! 1 integer - the number of points in the pattern.
292 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
293 MESSAGE("Error reading NB_POINTS");
294 return setErrorCode( ERR_READ_NB_POINTS );
296 int nbPoints = getInt( fields.front() );
298 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
300 // read the first point coordinates to define pattern dimension
301 int dim = readLine( fields, lineBeg, clearFields );
307 MESSAGE("Error reading points: wrong nb of coordinates");
308 return setErrorCode( ERR_READ_POINT_COORDS );
310 if ( nbPoints <= dim ) {
311 MESSAGE(" Too few points ");
312 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
315 // read the rest points
317 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
318 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
319 MESSAGE("Error reading points : wrong nb of coordinates ");
320 return setErrorCode( ERR_READ_POINT_COORDS );
322 // store point coordinates
323 myPoints.resize( nbPoints );
324 list <const char*>::iterator fIt = fields.begin();
325 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
327 TPoint & p = myPoints[ iPoint ];
328 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
330 double coord = getDouble( *fIt );
331 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
332 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
334 return setErrorCode( ERR_READ_3D_COORD );
336 p.myInitXYZ.SetCoord( iCoord, coord );
338 p.myInitUV.SetCoord( iCoord, coord );
342 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
345 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
346 MESSAGE("Error: missing key-points");
348 return setErrorCode( ERR_READ_NO_KEYPOINT );
351 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
353 int pointIndex = getInt( *fIt );
354 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
355 MESSAGE("Error: invalid point index " << pointIndex );
357 return setErrorCode( ERR_READ_BAD_INDEX );
359 if ( idSet.insert( pointIndex ).second ) // unique?
360 myKeyPointIDs.push_back( pointIndex );
364 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
366 while ( readLine( fields, lineBeg, clearFields ))
368 myElemPointIDs.push_back( TElemDef() );
369 TElemDef& elemPoints = myElemPointIDs.back();
370 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
372 int pointIndex = getInt( *fIt );
373 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
374 MESSAGE("Error: invalid point index " << pointIndex );
376 return setErrorCode( ERR_READ_BAD_INDEX );
378 elemPoints.push_back( pointIndex );
380 // check the nb of nodes in element
382 switch ( elemPoints.size() ) {
383 case 3: if ( !myIs2D ) Ok = false; break;
387 case 8: if ( myIs2D ) Ok = false; break;
391 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
393 return setErrorCode( ERR_READ_ELEM_POINTS );
396 if ( myElemPointIDs.empty() ) {
397 MESSAGE("Error: no elements");
399 return setErrorCode( ERR_READ_NO_ELEMS );
402 findBoundaryPoints(); // sort key-points
404 return setErrorCode( ERR_OK );
407 //=======================================================================
409 //purpose : Save the loaded pattern into the file <theFileName>
410 //=======================================================================
412 bool SMESH_Pattern::Save (ostream& theFile)
414 Kernel_Utils::Localizer loc;
417 MESSAGE(" Pattern not loaded ");
418 return setErrorCode( ERR_SAVE_NOT_LOADED );
421 theFile << "!!! SALOME Mesh Pattern file" << endl;
422 theFile << "!!!" << endl;
423 theFile << "!!! Nb of points:" << endl;
424 theFile << myPoints.size() << endl;
428 // theFile.width( 8 );
429 // theFile.setf(ios::fixed);// use 123.45 floating notation
430 // theFile.setf(ios::right);
431 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
432 // theFile.setf(ios::showpoint); // do not show trailing zeros
433 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
434 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
435 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
436 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
437 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
438 theFile << " !- " << i << endl; // point id to ease reading by a human being
442 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
443 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
444 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
445 theFile << " " << *kpIt;
446 if ( !myKeyPointIDs.empty() )
450 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
451 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
452 for ( ; epIt != myElemPointIDs.end(); epIt++ )
454 const TElemDef & elemPoints = *epIt;
455 TElemDef::const_iterator iIt = elemPoints.begin();
456 for ( ; iIt != elemPoints.end(); iIt++ )
457 theFile << " " << *iIt;
463 return setErrorCode( ERR_OK );
466 //=======================================================================
467 //function : sortBySize
468 //purpose : sort theListOfList by size
469 //=======================================================================
471 template<typename T> struct TSizeCmp {
472 bool operator ()( const list < T > & l1, const list < T > & l2 )
473 const { return l1.size() < l2.size(); }
476 template<typename T> void sortBySize( list< list < T > > & theListOfList )
478 if ( theListOfList.size() > 2 ) {
479 TSizeCmp< T > SizeCmp;
480 theListOfList.sort( SizeCmp );
484 //=======================================================================
487 //=======================================================================
489 static gp_XY project (const SMDS_MeshNode* theNode,
490 Extrema_GenExtPS & theProjectorPS)
492 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
493 theProjectorPS.Perform( P );
494 if ( !theProjectorPS.IsDone() ) {
495 MESSAGE( "SMESH_Pattern: point projection FAILED");
498 double u =0, v =0, minVal = DBL_MAX;
499 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
500 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
501 minVal = theProjectorPS.SquareDistance( i );
502 theProjectorPS.Point( i ).Parameter( u, v );
504 return gp_XY( u, v );
507 //=======================================================================
508 //function : areNodesBound
509 //purpose : true if all nodes of faces are bound to shapes
510 //=======================================================================
512 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
514 while ( faceItr->more() )
516 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
517 while ( nIt->more() )
519 const SMDS_MeshNode* node = smdsNode( nIt->next() );
520 if (node->getshapeId() <1) {
528 //=======================================================================
529 //function : isMeshBoundToShape
530 //purpose : return true if all 2d elements are bound to shape
531 // if aFaceSubmesh != NULL, then check faces bound to it
532 // else check all faces in aMeshDS
533 //=======================================================================
535 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
536 SMESHDS_SubMesh * aFaceSubmesh,
537 const bool isMainShape)
539 if ( isMainShape && aFaceSubmesh ) {
540 // check that all faces are bound to aFaceSubmesh
541 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
545 // check face nodes binding
546 if ( aFaceSubmesh ) {
547 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
548 return areNodesBound( fIt );
550 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
551 return areNodesBound( fIt );
554 //=======================================================================
556 //purpose : Create a pattern from the mesh built on <theFace>.
557 // <theProject>==true makes override nodes positions
558 // on <theFace> computed by mesher
559 //=======================================================================
561 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
562 const TopoDS_Face& theFace,
564 TopoDS_Vertex the1stVertex,
569 myToKeepNodes = theKeepNodes;
571 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
572 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
573 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
574 SMESH_MesherHelper helper( *theMesh );
575 helper.SetSubShape( theFace );
577 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
578 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
579 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
581 MESSAGE( "No elements bound to the face");
582 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
585 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
587 // check if face is closed
588 bool isClosed = helper.HasSeam();
589 list<TopoDS_Edge> eList;
590 list<TopoDS_Edge>::iterator elIt;
591 SMESH_Block::GetOrderedEdges( face, eList, myNbKeyPntInBoundary, the1stVertex );
593 // check that requested or needed projection is possible
594 bool isMainShape = theMesh->IsMainShape( face );
595 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
596 bool canProject = ( nbElems ? true : isMainShape );
598 canProject = false; // so far
600 if ( ( theProject || needProject ) && !canProject )
601 return setErrorCode( ERR_LOADF_CANT_PROJECT );
603 Extrema_GenExtPS projector;
604 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
605 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
608 TNodePointIDMap nodePointIDMap;
609 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
613 // ---------------------------------------------------------------
614 // The case where the submesh is projected to theFace
615 // ---------------------------------------------------------------
618 SMDS_ElemIteratorPtr fIt;
620 fIt = fSubMesh->GetElements();
622 fIt = aMeshDS->elementsIterator( SMDSAbs_Face );
624 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
625 while ( fIt->more() )
627 const SMDS_MeshElement* face = fIt->next();
628 myElemPointIDs.push_back( TElemDef() );
629 TElemDef& elemPoints = myElemPointIDs.back();
630 int nbNodes = face->NbCornerNodes();
631 for ( int i = 0;i < nbNodes; ++i )
633 const SMDS_MeshElement* node = face->GetNode( i );
634 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
635 if ( nIdIt->second == -1 )
636 nIdIt->second = iPoint++;
637 elemPoints.push_back( (*nIdIt).second );
640 myPoints.resize( iPoint );
642 // project all nodes of 2d elements to theFace
643 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
644 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
646 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
647 TPoint * p = & myPoints[ (*nIdIt).second ];
648 p->myInitUV = project( node, projector );
649 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
651 // find key-points: the points most close to UV of vertices
652 TopExp_Explorer vExp( face, TopAbs_VERTEX );
653 set<int> foundIndices;
654 for ( ; vExp.More(); vExp.Next() ) {
655 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
656 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
657 double minDist = DBL_MAX;
659 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
660 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
661 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
662 if ( dist < minDist ) {
667 if ( foundIndices.insert( index ).second ) // unique?
668 myKeyPointIDs.push_back( index );
670 myIsBoundaryPointsFound = false;
675 // ---------------------------------------------------------------------
676 // The case where a pattern is being made from the mesh built by mesher
677 // ---------------------------------------------------------------------
679 // Load shapes in the consequent order and count nb of points
681 loadVE( eList, myShapeIDMap );
682 myShapeIDMap.Add( face );
684 nbNodes += myShapeIDMap.Extent() - 1;
686 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
687 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
688 nbNodes += eSubMesh->NbNodes() + 1;
690 myPoints.resize( nbNodes );
692 // care of INTERNAL VERTEXes
693 TopExp_Explorer vExp( face, TopAbs_VERTEX, TopAbs_EDGE );
694 for ( ; vExp.More(); vExp.Next() )
696 const SMDS_MeshNode* node =
697 SMESH_Algo::VertexNode( TopoDS::Vertex( vExp.Current()), aMeshDS );
698 if ( !node || node->NbInverseElements( SMDSAbs_Face ) == 0 )
700 myPoints.resize( ++nbNodes );
701 list< TPoint* > & fPoints = getShapePoints( face );
702 nodePointIDMap.insert( make_pair( node, iPoint ));
703 TPoint* p = &myPoints[ iPoint++ ];
704 fPoints.push_back( p );
705 gp_XY uv = helper.GetNodeUV( face, node );
706 p->myInitUV.SetCoord( uv.X(), uv.Y() );
707 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
710 // Load U of points on edges
712 Bnd_Box2d edgesUVBox;
714 list<int>::iterator nbEinW = myNbKeyPntInBoundary.begin();
716 vector< TopoDS_Edge > eVec;
717 for ( elIt = eList.begin(); elIt != eList.end(); elIt++, iE++ )
719 if ( isClosed && ( iE == 0 || iE == *nbEinW ))
721 // new wire begins; put wire EDGEs in eVec
722 list<TopoDS_Edge>::iterator eEnd = elIt;
725 std::advance( eEnd, *nbEinW );
726 eVec.assign( elIt, eEnd );
729 TopoDS_Edge & edge = *elIt;
730 list< TPoint* > & ePoints = getShapePoints( edge );
732 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
733 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
735 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
736 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
737 // to make adjacent edges share key-point, we make v2 FORWARD too
738 // (as we have different points for same shape with different orientation)
741 // on closed face we must have REVERSED some of seam vertices
743 if ( helper.IsSeamShape( edge ) ) {
744 if ( helper.IsRealSeam( edge ) && !isForward ) {
745 // reverse on reversed SEAM edge
750 else { // on CLOSED edge (i.e. having one vertex with different orientations)
751 for ( int is2 = 0; is2 < 2; ++is2 ) {
752 TopoDS_Shape & v = is2 ? v2 : v1;
753 if ( helper.IsRealSeam( v ) ) {
754 // reverse or not depending on orientation of adjacent seam
755 int iSeam = helper.WrapIndex( iE + ( is2 ? +1 : -1 ), eVec.size() );
756 if ( eVec[ iSeam ].Orientation() == TopAbs_REVERSED )
763 // the forward key-point
764 list< TPoint* > * vPoint = & getShapePoints( v1 );
765 if ( vPoint->empty() )
767 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
768 if ( vSubMesh && vSubMesh->NbNodes() ) {
769 myKeyPointIDs.push_back( iPoint );
770 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
771 const SMDS_MeshNode* node = nIt->next();
772 if ( v1.Orientation() == TopAbs_REVERSED )
773 closeNodePointIDMap.insert( make_pair( node, iPoint ));
775 nodePointIDMap.insert( make_pair( node, iPoint ));
777 TPoint* keyPoint = &myPoints[ iPoint++ ];
778 vPoint->push_back( keyPoint );
780 keyPoint->myInitUV = project( node, projector );
782 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
783 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
784 edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
787 if ( !vPoint->empty() )
788 ePoints.push_back( vPoint->front() );
791 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
792 if ( eSubMesh && eSubMesh->NbNodes() )
794 // loop on nodes of an edge: sort them by param on edge
795 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
796 TParamNodeMap paramNodeMap;
797 int nbMeduimNodes = 0;
798 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
799 while ( nIt->more() )
801 const SMDS_MeshNode* node = nIt->next();
802 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
806 const SMDS_EdgePosition* epos =
807 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
808 double u = epos->GetUParameter();
809 paramNodeMap.insert( make_pair( u, node ));
811 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes ) {
812 // wrong U on edge, project
814 BRepAdaptor_Curve aCurve( edge );
815 proj.Initialize( aCurve, f, l );
816 paramNodeMap.clear();
817 nIt = eSubMesh->GetNodes();
818 for ( int iNode = 0; nIt->more(); ++iNode ) {
819 const SMDS_MeshNode* node = nIt->next();
820 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
822 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
824 if ( proj.IsDone() ) {
825 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
826 if ( proj.IsMin( i )) {
827 u = proj.Point( i ).Parameter();
831 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
833 paramNodeMap.insert( make_pair( u, node ));
836 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
837 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
838 return setErrorCode(ERR_UNEXPECTED);
841 // put U in [0,1] so that the first key-point has U==0
842 bool isSeam = helper.IsRealSeam( edge );
844 TParamNodeMap::iterator unIt = paramNodeMap.begin();
845 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
846 while ( unIt != paramNodeMap.end() )
848 TPoint* p = & myPoints[ iPoint ];
849 ePoints.push_back( p );
850 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
851 if ( isSeam && !isForward )
852 closeNodePointIDMap.insert( make_pair( node, iPoint ));
854 nodePointIDMap.insert ( make_pair( node, iPoint ));
857 p->myInitUV = project( node, projector );
859 double u = isForward ? (*unIt).first : (*unRIt).first;
860 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
861 p->myInitUV = C2d->Value( u ).XY();
863 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
864 edgesUVBox.Add( gp_Pnt2d( p->myInitUV ));
869 // the reverse key-point
870 vPoint = & getShapePoints( v2 );
871 if ( vPoint->empty() )
873 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
874 if ( vSubMesh && vSubMesh->NbNodes() ) {
875 myKeyPointIDs.push_back( iPoint );
876 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
877 const SMDS_MeshNode* node = nIt->next();
878 if ( v2.Orientation() == TopAbs_REVERSED )
879 closeNodePointIDMap.insert( make_pair( node, iPoint ));
881 nodePointIDMap.insert( make_pair( node, iPoint ));
883 TPoint* keyPoint = &myPoints[ iPoint++ ];
884 vPoint->push_back( keyPoint );
886 keyPoint->myInitUV = project( node, projector );
888 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
889 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
890 edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
893 if ( !vPoint->empty() )
894 ePoints.push_back( vPoint->front() );
896 // compute U of edge-points
899 double totalDist = 0;
900 list< TPoint* >::iterator pIt = ePoints.begin();
901 TPoint* prevP = *pIt;
902 prevP->myInitU = totalDist;
903 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
905 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
906 p->myInitU = totalDist;
909 if ( totalDist > DBL_MIN)
910 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
912 p->myInitU /= totalDist;
915 } // loop on edges of a wire
917 // Load in-face points and elements
919 if ( fSubMesh && fSubMesh->NbElements() )
921 list< TPoint* > & fPoints = getShapePoints( face );
922 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
923 while ( nIt->more() )
925 const SMDS_MeshNode* node = nIt->next();
926 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
928 nodePointIDMap.insert( make_pair( node, iPoint ));
929 TPoint* p = &myPoints[ iPoint++ ];
930 fPoints.push_back( p );
931 if ( theProject || edgesUVBox.IsOut( p->myInitUV ) )
932 p->myInitUV = project( node, projector );
934 const SMDS_FacePosition* pos =
935 static_cast<const SMDS_FacePosition*>(node->GetPosition());
936 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
938 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
941 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
942 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
943 while ( elemIt->more() )
945 const SMDS_MeshElement* elem = elemIt->next();
946 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
947 myElemPointIDs.push_back( TElemDef() );
948 TElemDef& elemPoints = myElemPointIDs.back();
949 // find point indices corresponding to element nodes
950 while ( nIt->more() )
952 const SMDS_MeshNode* node = smdsNode( nIt->next() );
953 n_id = nodePointIDMap.find( node );
954 if ( n_id == nodePointIDMap.end() )
955 continue; // medium node
956 iPoint = n_id->second; // point index of interest
957 // for a node on a seam edge there are two points
958 if ( helper.IsRealSeam( node->getshapeId() ) &&
959 ( n_id = closeNodePointIDMap.find( node )) != not_found )
961 TPoint & p1 = myPoints[ iPoint ];
962 TPoint & p2 = myPoints[ n_id->second ];
963 // Select point closest to the rest nodes of element in UV space
964 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
965 const SMDS_MeshNode* notSeamNode = 0;
966 // find node not on a seam edge
967 while ( nIt2->more() && !notSeamNode ) {
968 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
969 if ( !helper.IsSeamShape( n->getshapeId() ))
972 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
973 double dist1 = uv.SquareDistance( p1.myInitUV );
974 double dist2 = uv.SquareDistance( p2.myInitUV );
976 iPoint = n_id->second;
978 elemPoints.push_back( iPoint );
982 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
984 myIsBoundaryPointsFound = true;
989 myInNodes.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
991 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
992 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
993 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
995 nIdIt = closeNodePointIDMap.begin();
996 for ( ; nIdIt != closeNodePointIDMap.end(); nIdIt++ )
997 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
1000 // Assure that U range is proportional to V range
1003 vector< TPoint >::iterator pVecIt = myPoints.begin();
1004 for ( ; pVecIt != myPoints.end(); pVecIt++ )
1005 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
1006 double minU, minV, maxU, maxV;
1007 bndBox.Get( minU, minV, maxU, maxV );
1008 double dU = maxU - minU, dV = maxV - minV;
1009 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
1012 // define where is the problem, in the face or in the mesh
1013 TopExp_Explorer vExp( face, TopAbs_VERTEX );
1014 for ( ; vExp.More(); vExp.Next() ) {
1015 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
1018 bndBox.Get( minU, minV, maxU, maxV );
1019 dU = maxU - minU, dV = maxV - minV;
1020 if ( dU <= DBL_MIN || dV <= DBL_MIN )
1022 return setErrorCode( ERR_LOADF_NARROW_FACE );
1024 // mesh is projected onto a line, e.g.
1025 return setErrorCode( ERR_LOADF_CANT_PROJECT );
1027 double ratio = dU / dV, maxratio = 3, scale;
1029 if ( ratio > maxratio ) {
1030 scale = ratio / maxratio;
1033 else if ( ratio < 1./maxratio ) {
1034 scale = maxratio / ratio;
1039 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
1040 TPoint & p = *pVecIt;
1041 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
1042 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
1045 if ( myElemPointIDs.empty() ) {
1046 MESSAGE( "No elements bound to the face");
1047 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
1050 return setErrorCode( ERR_OK );
1053 //=======================================================================
1054 //function : computeUVOnEdge
1055 //purpose : compute coordinates of points on theEdge
1056 //=======================================================================
1058 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
1059 const list< TPoint* > & ePoints )
1061 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
1063 Handle(Geom2d_Curve) C2d =
1064 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1066 ePoints.back()->myInitU = 1.0;
1067 //ePoints.front()->myInitU = 0.0; //myUV = C2d->Value( isForward ? f : l ).XY();
1068 list< TPoint* >::const_iterator pIt = ePoints.begin();
1069 for ( pIt++; pIt != ePoints.end(); pIt++ )
1071 TPoint* point = *pIt;
1073 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1074 point->myU = ( f * ( 1 - du ) + l * du );
1076 point->myUV = C2d->Value( point->myU ).XY();
1080 //=======================================================================
1081 //function : intersectIsolines
1083 //=======================================================================
1085 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1086 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1090 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1091 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1092 resUV = 0.5 * ( loc1 + loc2 );
1093 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1094 // SKL 26.07.2007 for NPAL16567
1095 double d1 = (uv11-uv12).Modulus();
1096 double d2 = (uv21-uv22).Modulus();
1097 // double delta = d1*d2*1e-6; PAL17233
1098 double delta = min( d1, d2 ) / 10.;
1099 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1101 // double len1 = ( uv11 - uv12 ).Modulus();
1102 // double len2 = ( uv21 - uv22 ).Modulus();
1103 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1107 // gp_Lin2d line1( uv11, uv12 - uv11 );
1108 // gp_Lin2d line2( uv21, uv22 - uv21 );
1109 // double angle = Abs( line1.Angle( line2 ) );
1111 // IntAna2d_AnaIntersection inter;
1112 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1113 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1115 // gp_Pnt2d interUV = inter.Point(1).Value();
1116 // resUV += interUV.XY();
1117 // inter.Perform( line1, line2 );
1118 // interUV = inter.Point(1).Value();
1119 // resUV += interUV.XY();
1123 // if ( isDeformed ) {
1124 // MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1125 // ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1130 //=======================================================================
1131 //function : compUVByIsoIntersection
1133 //=======================================================================
1135 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1136 const gp_XY& theInitUV,
1138 bool & theIsDeformed )
1140 // compute UV by intersection of 2 iso lines
1141 //gp_Lin2d isoLine[2];
1142 gp_XY uv1[2], uv2[2];
1144 const double zero = DBL_MIN;
1145 for ( int iIso = 0; iIso < 2; iIso++ )
1147 // to build an iso line:
1148 // find 2 pairs of consequent edge-points such that the range of their
1149 // initial parameters encloses the in-face point initial parameter
1150 gp_XY UV[2], initUV[2];
1151 int nbUV = 0, iCoord = iIso + 1;
1152 double initParam = theInitUV.Coord( iCoord );
1154 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1155 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1157 const list< TPoint* > & bndPoints = * bndIt;
1158 TPoint* prevP = bndPoints.back(); // this is the first point
1159 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1160 bool coincPrev = false;
1161 // loop on the edge-points
1162 for ( ; pIt != bndPoints.end(); pIt++ )
1164 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1165 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1166 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1167 if (!coincPrev && // ignore if initParam coincides with prev point param
1168 sumOfDiff > zero && // ignore if both points coincide with initParam
1169 prevParamDiff * paramDiff <= zero )
1171 // find UV in parametric space of theFace
1172 double r = Abs(prevParamDiff) / sumOfDiff;
1173 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1176 // throw away uv most distant from <theInitUV>
1177 gp_XY vec0 = initUV[0] - theInitUV;
1178 gp_XY vec1 = initUV[1] - theInitUV;
1179 gp_XY vec = uvInit - theInitUV;
1180 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1181 double dist0 = vec0.SquareModulus();
1182 double dist1 = vec1.SquareModulus();
1183 double dist = vec .SquareModulus();
1184 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1185 i = ( dist0 < dist1 ? 1 : 0 );
1186 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1187 i = 3; // theInitUV must remain between
1191 initUV[ i ] = uvInit;
1192 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1194 coincPrev = ( Abs(paramDiff) <= zero );
1201 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1202 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1203 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1204 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1206 // an iso line should be normal to UV[0] - UV[1] direction
1207 // and be located at the same relative distance as from initial ends
1208 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1210 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1211 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1212 //isoLine[ iIso ] = iso.Normal( isoLoc );
1213 uv1[ iIso ] = UV[0];
1214 uv2[ iIso ] = UV[1];
1217 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1218 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1219 MESSAGE(" Can't intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1220 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1227 // ==========================================================
1228 // structure representing a node of a grid of iso-poly-lines
1229 // ==========================================================
1236 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1237 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1238 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1239 TIsoNode(double initU, double initV):
1240 myIsMovable(true), myInitUV( initU, initV ), myUV( 1e100, 1e100 )
1241 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1242 bool IsUVComputed() const
1243 { return myUV.X() != 1e100; }
1244 bool IsMovable() const
1245 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1246 void SetNotMovable()
1247 { myIsMovable = false; }
1248 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1249 { myBndNodes[ iDir + i * 2 ] = node; }
1250 TIsoNode* GetBoundaryNode(int iDir, int i)
1251 { return myBndNodes[ iDir + i * 2 ]; }
1252 void SetNext(TIsoNode* node, int iDir, int isForward)
1253 { myNext[ iDir + isForward * 2 ] = node; }
1254 TIsoNode* GetNext(int iDir, int isForward)
1255 { return myNext[ iDir + isForward * 2 ]; }
1258 //=======================================================================
1259 //function : getNextNode
1261 //=======================================================================
1263 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1265 TIsoNode* n = node->myNext[ dir ];
1266 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1267 n = 0;//node->myBndNodes[ dir ];
1268 // MESSAGE("getNextNode: use bnd for node "<<
1269 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1273 //=======================================================================
1274 //function : checkQuads
1275 //purpose : check if newUV destortes quadrangles around node,
1276 // and if ( crit == FIX_OLD ) fix newUV in this case
1277 //=======================================================================
1279 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1281 static bool checkQuads (const TIsoNode* node,
1283 const bool reversed,
1284 const int crit = FIX_OLD,
1285 double fixSize = 0.)
1287 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1288 int nbOldFix = 0, nbOldImpr = 0;
1289 double newBadRate = 0, oldBadRate = 0;
1290 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1291 int i, dir1 = 0, dir2 = 3;
1292 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1294 if ( dir2 > 3 ) dir2 = 0;
1296 // walking counterclockwise around a quad,
1297 // nodes are in the order: node, n[0], n[1], n[2]
1298 n[0] = getNextNode( node, dir1 );
1299 n[2] = getNextNode( node, dir2 );
1300 if ( !n[0] || !n[2] ) continue;
1301 n[1] = getNextNode( n[0], dir2 );
1302 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1303 bool isTriangle = ( !n[1] );
1305 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1307 // if ( fixSize != 0 ) {
1308 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1309 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1310 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1311 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1313 // check if a quadrangle is degenerated
1315 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1316 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1319 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1322 // find min size of the diagonal node-n[1]
1323 double minDiag = fixSize;
1324 if ( minDiag == 0. ) {
1325 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1326 if ( !isTriangle ) {
1327 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1328 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1330 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1331 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1334 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1335 // ( behind means "to the right of")
1337 // 1. newUV is not behind 01 and 12 dirs
1338 // 2. or newUV is not behind 02 dir and n[2] is convex
1339 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1340 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1341 gp_Vec2d moveVec[3], outVec[3];
1342 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1344 bool isDiag = ( i == 2 );
1345 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1349 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1351 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1353 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1355 gp_Vec2d newDir( n[i]->myUV, newUV );
1356 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1358 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1359 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1360 if ( crit == FIX_OLD ) {
1361 wasIn[i] = ( outDir * oldDir < 0 );
1362 wasOk[i] = ( outDir * oldDir < -minDiag );
1364 newBadRate += outDir * newDir;
1366 oldBadRate += outDir * oldDir;
1369 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1370 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1371 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1372 moveVec[i] = ( oldDist - minDiag ) * outDir;
1377 // check if n[2] is convex
1380 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1382 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1383 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1384 newIsOk = ( newIsOk && isNewOk );
1385 newIsIn = ( newIsIn && isNewIn );
1387 if ( crit != FIX_OLD ) {
1388 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1389 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1393 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1394 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1395 oldIsIn = ( oldIsIn && isOldIn );
1396 oldIsOk = ( oldIsOk && isOldIn );
1399 if ( !isOldIn ) { // node is outside a quadrangle
1400 // move newUV inside a quadrangle
1401 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1402 // node and newUV are outside: push newUV inside
1404 if ( convex || isTriangle ) {
1405 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1408 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1409 double outSize = out.Magnitude();
1410 if ( outSize > DBL_MIN )
1413 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1414 uv = n[1]->myUV - minDiag * out.XY();
1416 oldUVFixed[ nbOldFix++ ] = uv;
1417 //node->myUV = newUV;
1419 else if ( !isOldOk ) {
1420 // try to fix old UV: move node inside as less as possible
1421 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1422 gp_XY uv1, uv2 = node->myUV;
1423 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1425 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1426 while ( !isOldOk ) {
1427 // find the least moveVec
1429 double minMove2 = 1e100;
1430 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1432 if ( moveVec[i].Coord(1) < 1e100 ) {
1433 double move2 = moveVec[i].SquareMagnitude();
1434 if ( move2 < minMove2 ) {
1443 // move node to newUV
1444 uv1 = node->myUV + moveVec[ iMin ].XY();
1445 uv2 += moveVec[ iMin ].XY();
1446 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1447 // check if uv1 is ok
1448 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1449 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1450 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1452 oldUVImpr[ nbOldImpr++ ] = uv1;
1454 // check if uv2 is ok
1455 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1456 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1457 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1459 oldUVImpr[ nbOldImpr++ ] = uv2;
1464 } // loop on 4 quadrangles around <node>
1466 if ( crit == CHECK_NEW_OK )
1468 if ( crit == CHECK_NEW_IN )
1477 if ( oldIsIn && nbOldImpr ) {
1478 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1479 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1480 gp_XY uv = oldUVImpr[ 0 ];
1481 for ( int i = 1; i < nbOldImpr; i++ )
1482 uv += oldUVImpr[ i ];
1484 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1489 //MESSAGE(" Can't improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1492 if ( !oldIsIn && nbOldFix ) {
1493 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1494 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1495 gp_XY uv = oldUVFixed[ 0 ];
1496 for ( int i = 1; i < nbOldFix; i++ )
1497 uv += oldUVFixed[ i ];
1499 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1504 //MESSAGE(" Can't fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1507 if ( newIsIn && oldIsIn )
1508 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1509 else if ( !newIsIn )
1516 //=======================================================================
1517 //function : compUVByElasticIsolines
1518 //purpose : compute UV as nodes of iso-poly-lines consisting of
1519 // segments keeping relative size as in the pattern
1520 //=======================================================================
1521 //#define DEB_COMPUVBYELASTICISOLINES
1522 bool SMESH_Pattern::
1523 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1524 const list< TPoint* >& thePntToCompute)
1526 return false; // PAL17233
1527 //cout << "============================== KEY POINTS =============================="<<endl;
1528 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1529 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1530 // TPoint& p = myPoints[ *kpIt ];
1531 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1532 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1534 //cout << "=============================="<<endl;
1536 // Define parameters of iso-grid nodes in U and V dir
1538 set< double > paramSet[ 2 ];
1539 list< list< TPoint* > >::const_iterator pListIt;
1540 list< TPoint* >::const_iterator pIt;
1541 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1542 const list< TPoint* > & pList = * pListIt;
1543 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1544 paramSet[0].insert( (*pIt)->myInitUV.X() );
1545 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1548 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1549 paramSet[0].insert( (*pIt)->myInitUV.X() );
1550 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1552 // unite close parameters and split too long segments
1555 for ( iDir = 0; iDir < 2; iDir++ )
1557 set< double > & params = paramSet[ iDir ];
1558 double range = ( *params.rbegin() - *params.begin() );
1559 double toler = range / 1e6;
1560 tol[ iDir ] = toler;
1561 // double maxSegment = range / params.size() / 2.;
1563 // set< double >::iterator parIt = params.begin();
1564 // double prevPar = *parIt;
1565 // for ( parIt++; parIt != params.end(); parIt++ )
1567 // double segLen = (*parIt) - prevPar;
1568 // if ( segLen < toler )
1569 // ;//params.erase( prevPar ); // unite
1570 // else if ( segLen > maxSegment )
1571 // params.insert( prevPar + 0.5 * segLen ); // split
1572 // prevPar = (*parIt);
1576 // Make nodes of a grid of iso-poly-lines
1578 list < TIsoNode > nodes;
1579 typedef list < TIsoNode *> TIsoLine;
1580 map < double, TIsoLine > isoMap[ 2 ];
1582 set< double > & params0 = paramSet[ 0 ];
1583 set< double >::iterator par0It = params0.begin();
1584 for ( ; par0It != params0.end(); par0It++ )
1586 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1587 set< double > & params1 = paramSet[ 1 ];
1588 set< double >::iterator par1It = params1.begin();
1589 for ( ; par1It != params1.end(); par1It++ )
1591 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1592 isoLine0.push_back( & nodes.back() );
1593 isoMap[1][ *par1It ].push_back( & nodes.back() );
1597 // Compute intersections of boundaries with iso-lines:
1598 // only boundary nodes will have computed UV so far
1601 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1602 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1603 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1605 const list< TPoint* > & bndPoints = * bndIt;
1606 TPoint* prevP = bndPoints.back(); // this is the first point
1607 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1608 // loop on the edge-points
1609 for ( ; pIt != bndPoints.end(); pIt++ )
1611 TPoint* point = *pIt;
1612 for ( iDir = 0; iDir < 2; iDir++ )
1614 const int iCoord = iDir + 1;
1615 const int iOtherCoord = 2 - iDir;
1616 double par1 = prevP->myInitUV.Coord( iCoord );
1617 double par2 = point->myInitUV.Coord( iCoord );
1618 double parDif = par2 - par1;
1619 if ( Abs( parDif ) <= DBL_MIN )
1621 // find iso-lines intersecting a bounadry
1622 double toler = tol[ 1 - iDir ];
1623 double minPar = Min ( par1, par2 );
1624 double maxPar = Max ( par1, par2 );
1625 map < double, TIsoLine >& isos = isoMap[ iDir ];
1626 map < double, TIsoLine >::iterator isoIt = isos.begin();
1627 for ( ; isoIt != isos.end(); isoIt++ )
1629 double isoParam = (*isoIt).first;
1630 if ( isoParam < minPar || isoParam > maxPar )
1632 double r = ( isoParam - par1 ) / parDif;
1633 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1634 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1635 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1636 // find existing node with otherPar or insert a new one
1637 TIsoLine & isoLine = (*isoIt).second;
1639 TIsoLine::iterator nIt = isoLine.begin();
1640 for ( ; nIt != isoLine.end(); nIt++ ) {
1641 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1642 if ( nodePar >= otherPar )
1646 if ( Abs( nodePar - otherPar ) <= toler )
1647 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1649 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1650 node = & nodes.back();
1651 isoLine.insert( nIt, node );
1653 node->SetNotMovable();
1655 uvBnd.Add( gp_Pnt2d( uv ));
1656 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1658 gp_XY tgt( point->myUV - prevP->myUV );
1659 if ( ::IsEqual( r, 1. ))
1660 node->myDir[ 0 ] = tgt;
1661 else if ( ::IsEqual( r, 0. ))
1662 node->myDir[ 1 ] = tgt;
1664 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1665 // keep boundary nodes corresponding to boundary points
1666 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1667 if ( bndNodes.empty() || bndNodes.back() != node )
1668 bndNodes.push_back( node );
1669 } // loop on isolines
1670 } // loop on 2 directions
1672 } // loop on boundary points
1673 } // loop on boundaries
1675 // Define orientation
1677 // find the point with the least X
1678 double leastX = DBL_MAX;
1679 TIsoNode * leftNode;
1680 list < TIsoNode >::iterator nodeIt = nodes.begin();
1681 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1682 TIsoNode & node = *nodeIt;
1683 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1684 leastX = node.myUV.X();
1687 // if ( node.IsUVComputed() ) {
1688 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1689 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1690 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1691 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1694 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1695 //SCRUTE( reversed );
1697 // Prepare internal nodes:
1699 // 2. compute ratios
1700 // 3. find boundary nodes for each node
1701 // 4. remove nodes out of the boundary
1702 for ( iDir = 0; iDir < 2; iDir++ )
1704 const int iCoord = 2 - iDir; // coord changing along an isoline
1705 map < double, TIsoLine >& isos = isoMap[ iDir ];
1706 map < double, TIsoLine >::iterator isoIt = isos.begin();
1707 for ( ; isoIt != isos.end(); isoIt++ )
1709 TIsoLine & isoLine = (*isoIt).second;
1710 bool firstCompNodeFound = false;
1711 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1712 nPrevIt = nIt = nNextIt = isoLine.begin();
1714 nNextIt++; nNextIt++;
1715 while ( nIt != isoLine.end() )
1717 // 1. connect prev - cur
1718 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1719 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1720 firstCompNodeFound = true;
1721 lastCompNodePos = nPrevIt;
1723 if ( firstCompNodeFound ) {
1724 node->SetNext( prevNode, iDir, 0 );
1725 prevNode->SetNext( node, iDir, 1 );
1728 if ( nNextIt != isoLine.end() ) {
1729 double par1 = prevNode->myInitUV.Coord( iCoord );
1730 double par2 = node->myInitUV.Coord( iCoord );
1731 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1732 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1734 // 3. find boundary nodes
1735 if ( node->IsUVComputed() )
1736 lastCompNodePos = nIt;
1737 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1738 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1739 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1740 if ( (*nIt2)->IsUVComputed() )
1742 if ( nIt2 != isoLine.end() ) {
1744 node->SetBoundaryNode( bndNode1, iDir, 0 );
1745 node->SetBoundaryNode( bndNode2, iDir, 1 );
1746 // cout << "--------------------------------------------------"<<endl;
1747 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1748 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1749 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1750 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1751 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1752 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1755 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1756 node->SetBoundaryNode( 0, iDir, 0 );
1757 node->SetBoundaryNode( 0, iDir, 1 );
1761 if ( nNextIt != isoLine.end() ) nNextIt++;
1762 // 4. remove nodes out of the boundary
1763 if ( !firstCompNodeFound )
1764 isoLine.pop_front();
1765 } // loop on isoLine nodes
1767 // remove nodes after the boundary
1768 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1769 // (*nIt)->SetNotMovable();
1770 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1771 } // loop on isolines
1772 } // loop on 2 directions
1774 // Compute local isoline direction for internal nodes
1777 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1778 map < double, TIsoLine >::iterator isoIt = isos.begin();
1779 for ( ; isoIt != isos.end(); isoIt++ )
1781 TIsoLine & isoLine = (*isoIt).second;
1782 TIsoLine::iterator nIt = isoLine.begin();
1783 for ( ; nIt != isoLine.end(); nIt++ )
1785 TIsoNode* node = *nIt;
1786 if ( node->IsUVComputed() || !node->IsMovable() )
1788 gp_Vec2d aTgt[2], aNorm[2];
1791 for ( iDir = 0; iDir < 2; iDir++ )
1793 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1794 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1795 if ( !bndNode1 || !bndNode2 ) {
1799 const int iCoord = 2 - iDir; // coord changing along an isoline
1800 double par1 = bndNode1->myInitUV.Coord( iCoord );
1801 double par2 = node->myInitUV.Coord( iCoord );
1802 double par3 = bndNode2->myInitUV.Coord( iCoord );
1803 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1805 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1806 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1807 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1808 else tgt1.Reverse();
1809 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1811 if ( ratio[ iDir ] < 0.5 )
1812 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1814 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1816 aNorm[ iDir ].Reverse(); // along iDir isoline
1818 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1819 // maybe angle is more than |PI|
1820 if ( Abs( angle ) > PI / 2. ) {
1821 // check direction of the last but one perpendicular isoline
1822 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1823 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1824 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1825 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1826 if ( isoDir * tgt2 < 0 )
1828 double angle2 = tgt1.Angle( isoDir );
1829 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1830 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1831 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1832 //MESSAGE("REVERSE ANGLE");
1835 if ( Abs( angle2 ) > Abs( angle ) ||
1836 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1837 //MESSAGE("Add PI");
1838 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1839 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1840 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1841 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1842 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1843 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1846 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1850 for ( iDir = 0; iDir < 2; iDir++ )
1852 aTgt[iDir].Normalize();
1853 aNorm[1-iDir].Normalize();
1854 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1857 node->myDir[iDir] = //aTgt[iDir];
1858 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1860 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1861 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1862 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1863 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1865 } // loop on iso nodes
1866 } // loop on isolines
1868 // Find nodes to start computing UV from
1870 list< TIsoNode* > startNodes;
1871 list< TIsoNode* >::iterator nIt = bndNodes.end();
1872 TIsoNode* node = *(--nIt);
1873 TIsoNode* prevNode = *(--nIt);
1874 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1876 TIsoNode* nextNode = *nIt;
1877 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1878 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1879 double initAngle = initTgt1.Angle( initTgt2 );
1880 double angle = node->myDir[0].Angle( node->myDir[1] );
1881 if ( reversed ) angle = -angle;
1882 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1883 // find a close internal node
1884 TIsoNode* nClose = 0;
1885 list< TIsoNode* > testNodes;
1886 testNodes.push_back( node );
1887 list< TIsoNode* >::iterator it = testNodes.begin();
1888 for ( ; !nClose && it != testNodes.end(); it++ )
1890 for (int i = 0; i < 4; i++ )
1892 nClose = (*it)->myNext[ i ];
1894 if ( !nClose->IsUVComputed() )
1897 testNodes.push_back( nClose );
1903 startNodes.push_back( nClose );
1904 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1905 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1906 // "initAngle: " << initAngle << " angle: " << angle << endl;
1907 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1908 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1909 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1910 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1916 // Compute starting UV of internal nodes
1918 list < TIsoNode* > internNodes;
1919 bool needIteration = true;
1920 if ( startNodes.empty() ) {
1921 //MESSAGE( " Starting UV by compUVByIsoIntersection()");
1922 needIteration = false;
1923 map < double, TIsoLine >& isos = isoMap[ 0 ];
1924 map < double, TIsoLine >::iterator isoIt = isos.begin();
1925 for ( ; isoIt != isos.end(); isoIt++ )
1927 TIsoLine & isoLine = (*isoIt).second;
1928 TIsoLine::iterator nIt = isoLine.begin();
1929 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1931 TIsoNode* node = *nIt;
1932 if ( !node->IsUVComputed() && node->IsMovable() ) {
1933 internNodes.push_back( node );
1935 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1936 node->myUV, needIteration ))
1937 node->myUV = node->myInitUV;
1941 if ( needIteration )
1942 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1944 TIsoNode* node = *nIt, *nClose = 0;
1945 list< TIsoNode* > testNodes;
1946 testNodes.push_back( node );
1947 list< TIsoNode* >::iterator it = testNodes.begin();
1948 for ( ; !nClose && it != testNodes.end(); it++ )
1950 for (int i = 0; i < 4; i++ )
1952 nClose = (*it)->myNext[ i ];
1954 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1957 testNodes.push_back( nClose );
1963 startNodes.push_back( nClose );
1967 double aMin[2], aMax[2], step[2];
1968 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1969 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1970 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1971 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1972 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1974 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1976 TIsoNode *node = *nIt;
1977 if ( node->IsUVComputed() || !node->IsMovable() )
1979 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1980 int nbComp = 0, nbPrev = 0;
1981 for ( iDir = 0; iDir < 2; iDir++ )
1983 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1984 TIsoNode* n = node->GetNext( iDir, 0 );
1985 if ( n->IsUVComputed() )
1988 startNodes.push_back( n );
1989 n = node->GetNext( iDir, 1 );
1990 if ( n->IsUVComputed() )
1993 startNodes.push_back( n );
1995 prevNode1 = prevNode2;
1998 if ( prevNode1 ) nbPrev++;
1999 if ( prevNode2 ) nbPrev++;
2002 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
2003 double par = node->myInitUV.Coord( 2 - iDir );
2004 bool isEnd = ( prevPar > par );
2005 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
2006 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2007 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
2009 MESSAGE("Why we are here?");
2012 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
2013 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
2014 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
2015 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
2016 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
2017 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
2018 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
2019 //" par: " << prevPar << endl;
2020 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
2021 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
2023 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2024 gp_XY & uv1 = prevNode1->myUV;
2025 gp_XY & uv2 = prevNode2->myUV;
2026 // dir = ( uv2 - uv1 );
2027 // double len = dir.Modulus();
2028 // if ( len > DBL_MIN )
2029 // dir /= len * 0.5;
2030 double r = node->myRatio[ iDir ];
2031 newUV += uv1 * ( 1 - r ) + uv2 * r;
2034 newUV += prevNode1->myUV + dir * step[ iDir ];
2040 if ( !nbComp ) continue;
2043 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2045 // check if a quadrangle is not distorted
2047 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
2048 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
2049 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
2050 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
2054 internNodes.push_back( node );
2059 static int maxNbIter = 100;
2060 #ifdef DEB_COMPUVBYELASTICISOLINES
2062 bool useNbMoveNode = 0;
2063 static int maxNbNodeMove = 100;
2066 if ( !useNbMoveNode )
2067 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2072 if ( !needIteration) break;
2073 #ifdef DEB_COMPUVBYELASTICISOLINES
2074 if ( nbIter >= maxNbIter ) break;
2077 list < TIsoNode* >::iterator nIt = internNodes.begin();
2078 for ( ; nIt != internNodes.end(); nIt++ ) {
2079 #ifdef DEB_COMPUVBYELASTICISOLINES
2081 cout << nbNodeMove <<" =================================================="<<endl;
2083 TIsoNode * node = *nIt;
2087 for ( iDir = 0; iDir < 2; iDir++ )
2089 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2090 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2091 double r = node->myRatio[ iDir ];
2092 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2093 // line[ iDir ].SetLocation( loc[ iDir ] );
2094 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2097 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2098 // double locR[2] = { 0, 0 };
2099 for ( iDir = 0; iDir < 2; iDir++ )
2101 const int iCoord = 2 - iDir; // coord changing along an isoline
2102 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2103 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2104 if ( !bndNode1 || !bndNode2 ) {
2107 double par1 = bndNode1->myInitUV.Coord( iCoord );
2108 double par2 = node->myInitUV.Coord( iCoord );
2109 double par3 = bndNode2->myInitUV.Coord( iCoord );
2110 double r = ( par2 - par1 ) / ( par3 - par1 );
2111 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2112 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2114 //locR[0] = locR[1] = 0.25;
2115 // intersect the 2 lines and move a node
2116 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2117 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2119 // double intR = 1 - locR[0] - locR[1];
2120 // gp_XY newUV = inter.Point(1).Value().XY();
2121 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2122 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2124 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2125 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2126 // avoid parallel isolines intersection
2127 checkQuads( node, newUV, reversed );
2129 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2131 } // intersection found
2132 #ifdef DEB_COMPUVBYELASTICISOLINES
2133 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2135 } // loop on internal nodes
2136 #ifdef DEB_COMPUVBYELASTICISOLINES
2137 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2139 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2141 //MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2143 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2144 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2145 #ifndef DEB_COMPUVBYELASTICISOLINES
2150 // Set computed UV to points
2152 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2153 TPoint* point = *pIt;
2154 //gp_XY oldUV = point->myUV;
2155 double minDist = DBL_MAX;
2156 list < TIsoNode >::iterator nIt = nodes.begin();
2157 for ( ; nIt != nodes.end(); nIt++ ) {
2158 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2159 if ( dist < minDist ) {
2161 point->myUV = (*nIt).myUV;
2170 //=======================================================================
2171 //function : setFirstEdge
2172 //purpose : choose the best first edge of theWire; return the summary distance
2173 // between point UV computed by isolines intersection and
2174 // eventual UV got from edge p-curves
2175 //=======================================================================
2177 //#define DBG_SETFIRSTEDGE
2178 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2180 int iE, nbEdges = theWire.size();
2184 // Transform UVs computed by iso to fit bnd box of a wire
2186 // max nb of points on an edge
2188 int eID = theFirstEdgeID;
2189 for ( iE = 0; iE < nbEdges; iE++ )
2190 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2192 // compute bnd boxes
2193 TopoDS_Face face = TopoDS::Face( myShape );
2194 Bnd_Box2d bndBox, eBndBox;
2195 eID = theFirstEdgeID;
2196 list< TopoDS_Edge >::iterator eIt;
2197 list< TPoint* >::iterator pIt;
2198 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2200 // UV by isos stored in TPoint.myXYZ
2201 list< TPoint* > & ePoints = getShapePoints( eID++ );
2202 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2204 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2206 // UV by an edge p-curve
2208 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2209 double dU = ( l - f ) / ( maxNbPnt - 1 );
2210 for ( int i = 0; i < maxNbPnt; i++ )
2211 eBndBox.Add( C2d->Value( f + i * dU ));
2214 // transform UVs by isos
2215 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2216 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2217 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2218 #ifdef DBG_SETFIRSTEDGE
2219 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2220 << eMinPar[1] << " - " << eMaxPar[1] );
2222 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2224 double dMin = eMinPar[i] - minPar[i];
2225 double dMax = eMaxPar[i] - maxPar[i];
2226 double dPar = maxPar[i] - minPar[i];
2227 eID = theFirstEdgeID;
2228 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2230 list< TPoint* > & ePoints = getShapePoints( eID++ );
2231 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2233 double par = (*pIt)->myXYZ.Coord( iC );
2234 double r = ( par - minPar[i] ) / dPar;
2235 par += ( 1 - r ) * dMin + r * dMax;
2236 (*pIt)->myXYZ.SetCoord( iC, par );
2242 double minDist = DBL_MAX;
2243 for ( iE = 0 ; iE < nbEdges; iE++ )
2245 #ifdef DBG_SETFIRSTEDGE
2246 MESSAGE ( " VARIANT " << iE );
2248 // evaluate the distance between UV computed by the 2 methods:
2249 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2251 int eID = theFirstEdgeID;
2252 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2254 list< TPoint* > & ePoints = getShapePoints( eID++ );
2255 computeUVOnEdge( *eIt, ePoints );
2256 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2258 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2259 #ifdef DBG_SETFIRSTEDGE
2260 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2261 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2265 #ifdef DBG_SETFIRSTEDGE
2266 MESSAGE ( "dist -- " << dist );
2268 if ( dist < minDist ) {
2270 eBest = theWire.front();
2272 // check variant with another first edge
2273 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2275 // put the best first edge to the theWire front
2276 if ( eBest != theWire.front() ) {
2277 eIt = find ( theWire.begin(), theWire.end(), eBest );
2278 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2284 //=======================================================================
2285 //function : sortSameSizeWires
2286 //purpose : sort wires in theWireList from theFromWire until theToWire,
2287 // the wires are set in the order to correspond to the order
2288 // of boundaries; after sorting, edges in the wires are put
2289 // in a good order, point UVs on edges are computed and points
2290 // are appended to theEdgesPointsList
2291 //=======================================================================
2293 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2294 const TListOfEdgesList::iterator& theFromWire,
2295 const TListOfEdgesList::iterator& theToWire,
2296 const int theFirstEdgeID,
2297 list< list< TPoint* > >& theEdgesPointsList )
2299 TopoDS_Face F = TopoDS::Face( myShape );
2300 int iW, nbWires = 0;
2301 TListOfEdgesList::iterator wlIt = theFromWire;
2302 while ( wlIt++ != theToWire )
2305 // Recompute key-point UVs by isolines intersection,
2306 // compute CG of key-points for each wire and bnd boxes of GCs
2309 gp_XY orig( gp::Origin2d().XY() );
2310 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2311 Bnd_Box2d bndBox, vBndBox;
2312 int eID = theFirstEdgeID;
2313 list< TopoDS_Edge >::iterator eIt;
2314 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2316 list< TopoDS_Edge > & wire = *wlIt;
2317 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2319 list< TPoint* > & ePoints = getShapePoints( eID++ );
2320 TPoint* p = ePoints.front();
2321 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2322 MESSAGE("can't sortSameSizeWires()");
2325 gcVec[iW] += p->myUV;
2326 bndBox.Add( gp_Pnt2d( p->myUV ));
2327 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2328 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2329 vGcVec[iW] += vXY.XY();
2331 // keep the computed UV to compare against by setFirstEdge()
2332 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2334 gcVec[iW] /= nbWires;
2335 vGcVec[iW] /= nbWires;
2336 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2337 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2340 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2342 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2343 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2344 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2345 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2347 double dMin = vMinPar[i] - minPar[i];
2348 double dMax = vMaxPar[i] - maxPar[i];
2349 double dPar = maxPar[i] - minPar[i];
2350 if ( Abs( dPar ) <= DBL_MIN )
2352 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2353 double par = gcVec[iW].Coord( iC );
2354 double r = ( par - minPar[i] ) / dPar;
2355 par += ( 1 - r ) * dMin + r * dMax;
2356 gcVec[iW].SetCoord( iC, par );
2360 // Define boundary - wire correspondence by GC closeness
2362 TListOfEdgesList tmpWList;
2363 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2364 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2365 TIntWirePosMap bndIndWirePosMap;
2366 vector< bool > bndFound( nbWires, false );
2367 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2369 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2370 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2371 double minDist = DBL_MAX;
2372 gp_XY & wGc = vGcVec[ iW ];
2374 for ( int iB = 0; iB < nbWires; iB++ ) {
2375 if ( bndFound[ iB ] ) continue;
2376 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2377 if ( dist < minDist ) {
2382 bndFound[ bIndex ] = true;
2383 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2388 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2389 eID = theFirstEdgeID;
2390 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2392 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2393 list < TopoDS_Edge > & wire = ( *wirePos );
2395 // choose the best first edge of a wire
2396 setFirstEdge( wire, eID );
2398 // compute eventual UV and fill theEdgesPointsList
2399 theEdgesPointsList.push_back( list< TPoint* >() );
2400 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2401 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2403 list< TPoint* > & ePoints = getShapePoints( eID++ );
2404 computeUVOnEdge( *eIt, ePoints );
2405 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2407 // put wire back to theWireList
2409 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2415 //=======================================================================
2417 //purpose : Compute nodes coordinates applying
2418 // the loaded pattern to <theFace>. The first key-point
2419 // will be mapped into <theVertexOnKeyPoint1>
2420 //=======================================================================
2422 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2423 const TopoDS_Vertex& theVertexOnKeyPoint1,
2424 const bool theReverse)
2426 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2427 if ( !setShapeToMesh( face ))
2430 // find points on edges, it fills myNbKeyPntInBoundary
2431 if ( !findBoundaryPoints() )
2434 // Define the edges order so that the first edge starts at
2435 // theVertexOnKeyPoint1
2437 list< TopoDS_Edge > eList;
2438 list< int > nbVertexInWires;
2439 int nbWires = SMESH_Block::GetOrderedEdges( face, eList, nbVertexInWires, theVertexOnKeyPoint1);
2440 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2442 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2443 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2445 // check nb wires and edges
2446 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2447 l1.sort(); l2.sort();
2450 MESSAGE( "Wrong nb vertices in wires" );
2451 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2454 // here shapes get IDs, for the outer wire IDs are OK
2455 int nbVertices = loadVE( eList, myShapeIDMap );
2456 myShapeIDMap.Add( face );
2458 if ((int) myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2459 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2460 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2463 // points on edges to be used for UV computation of in-face points
2464 list< list< TPoint* > > edgesPointsList;
2465 edgesPointsList.push_back( list< TPoint* >() );
2466 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2467 list< TPoint* >::iterator pIt, pEnd;
2469 // compute UV of points on the outer wire
2470 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2471 list< TopoDS_Edge >::iterator elIt;
2472 for (iE = 0, elIt = eList.begin();
2473 iE < nbEdgesInOuterWire && elIt != eList.end();
2476 list< TPoint* > & ePoints = getShapePoints( *elIt );
2478 computeUVOnEdge( *elIt, ePoints );
2479 // collect on-edge points (excluding the last one)
2480 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2483 // If there are several wires, define the order of edges of inner wires:
2484 // compute UV of inner edge-points using 2 methods: the one for in-face points
2485 // and the one for on-edge points and then choose the best edge order
2486 // by the best correspondance of the 2 results
2489 // compute UV of inner edge-points using the method for in-face points
2490 // and divide eList into a list of separate wires
2492 list< list< TopoDS_Edge > > wireList;
2493 list<TopoDS_Edge>::iterator eIt = elIt;
2494 list<int>::iterator nbEIt = nbVertexInWires.begin();
2495 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2497 int nbEdges = *nbEIt;
2498 wireList.push_back( list< TopoDS_Edge >() );
2499 list< TopoDS_Edge > & wire = wireList.back();
2500 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2502 list< TPoint* > & ePoints = getShapePoints( *eIt );
2503 pIt = ePoints.begin();
2504 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2506 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2507 MESSAGE("can't Apply(face)");
2510 // keep the computed UV to compare against by setFirstEdge()
2511 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2513 wire.push_back( *eIt );
2516 // remove inner edges from eList
2517 eList.erase( elIt, eList.end() );
2519 // sort wireList by nb edges in a wire
2520 sortBySize< TopoDS_Edge > ( wireList );
2522 // an ID of the first edge of a boundary
2523 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2524 // if ( nbSeamShapes > 0 )
2525 // id1 += 2; // 2 vertices more
2527 // find points - edge correspondence for wires of unique size,
2528 // edge order within a wire should be defined only
2530 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2531 while ( wlIt != wireList.end() )
2533 list< TopoDS_Edge >& wire = (*wlIt);
2534 size_t nbEdges = wire.size();
2536 if ( wlIt != wireList.end() && (*wlIt).size() != nbEdges ) // a unique size wire
2538 // choose the best first edge of a wire
2539 setFirstEdge( wire, id1 );
2541 // compute eventual UV and collect on-edge points
2542 edgesPointsList.push_back( list< TPoint* >() );
2543 edgesPoints = & edgesPointsList.back();
2545 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2547 list< TPoint* > & ePoints = getShapePoints( eID++ );
2548 computeUVOnEdge( *eIt, ePoints );
2549 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2555 // find boundary - wire correspondence for several wires of same size
2557 id1 = nbVertices + nbEdgesInOuterWire + 1;
2558 wlIt = wireList.begin();
2559 while ( wlIt != wireList.end() )
2561 size_t nbSameSize = 0, nbEdges = (*wlIt).size();
2562 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2564 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2568 if ( nbSameSize > 0 )
2569 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2572 id1 += nbEdges * ( nbSameSize + 1 );
2575 // add well-ordered edges to eList
2577 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2579 list< TopoDS_Edge >& wire = (*wlIt);
2580 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2583 // re-fill myShapeIDMap - all shapes get good IDs
2585 myShapeIDMap.Clear();
2586 nbVertices = loadVE( eList, myShapeIDMap );
2587 myShapeIDMap.Add( face );
2589 } // there are inner wires
2591 // Set XYZ of on-vertex points
2593 // for ( int iV = 1; iV <= nbVertices; ++iV )
2595 // const TopoDS_Vertex& V = TopoDS::Vertex( myShapeIDMap( iV ));
2596 // list< TPoint* > & vPoints = getShapePoints( iV );
2597 // if ( !vPoints.empty() )
2599 // //vPoints.front()->myUV = BRep_Tool::Parameters( V, theFace ).XY();
2600 // vPoints.front()->myXYZ = BRep_Tool::Pnt( V );
2604 // Compute XYZ of on-edge points
2606 TopLoc_Location loc;
2607 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2609 BRepAdaptor_Curve C3d( *elIt );
2610 list< TPoint* > & ePoints = getShapePoints( iE++ );
2611 for ( pIt = ++ePoints.begin(), pEnd = ePoints.end(); pIt != pEnd; pIt++ )
2613 TPoint* point = *pIt;
2614 point->myXYZ = C3d.Value( point->myU );
2618 // Compute UV and XYZ of in-face points
2620 // try to use a simple algo
2621 list< TPoint* > & fPoints = getShapePoints( face );
2622 bool isDeformed = false;
2623 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2624 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2625 (*pIt)->myUV, isDeformed )) {
2626 MESSAGE("can't Apply(face)");
2629 // try to use a complex algo if it is a difficult case
2630 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2632 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2633 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2634 (*pIt)->myUV, isDeformed )) {
2635 MESSAGE("can't Apply(face)");
2640 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2641 const gp_Trsf & aTrsf = loc.Transformation();
2642 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2644 TPoint * point = *pIt;
2645 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2646 if ( !loc.IsIdentity() )
2647 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2650 myIsComputed = true;
2652 return setErrorCode( ERR_OK );
2655 //=======================================================================
2657 //purpose : Compute nodes coordinates applying
2658 // the loaded pattern to <theFace>. The first key-point
2659 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2660 //=======================================================================
2662 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2663 const int theNodeIndexOnKeyPoint1,
2664 const bool theReverse)
2666 // MESSAGE(" ::Apply(MeshFace) " );
2668 if ( !IsLoaded() ) {
2669 MESSAGE( "Pattern not loaded" );
2670 return setErrorCode( ERR_APPL_NOT_LOADED );
2673 // check nb of nodes
2674 const int nbFaceNodes = theFace->NbCornerNodes();
2675 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2676 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2677 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2680 // find points on edges, it fills myNbKeyPntInBoundary
2681 if ( !findBoundaryPoints() )
2684 // check that there are no holes in a pattern
2685 if (myNbKeyPntInBoundary.size() > 1 ) {
2686 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2689 // Define the nodes order
2691 list< const SMDS_MeshNode* > nodes;
2692 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2693 SMDS_NodeIteratorPtr noIt = theFace->nodeIterator();
2695 while ( noIt->more() && iSub < nbFaceNodes ) {
2696 const SMDS_MeshNode* node = noIt->next();
2697 nodes.push_back( node );
2698 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2701 if ( n != nodes.end() ) {
2703 if ( n != --nodes.end() )
2704 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2707 else if ( n != nodes.begin() )
2708 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2710 list< gp_XYZ > xyzList;
2711 myOrderedNodes.resize( nbFaceNodes );
2712 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2713 xyzList.push_back( SMESH_TNodeXYZ( *n ));
2714 myOrderedNodes[ iSub++] = *n;
2717 // Define a face plane
2719 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2720 gp_Pnt P ( *xyzIt++ );
2721 gp_Vec Vx( P, *xyzIt++ ), N;
2723 N = Vx ^ gp_Vec( P, *xyzIt++ );
2724 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2725 if ( N.SquareMagnitude() <= DBL_MIN )
2726 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2727 gp_Ax2 pos( P, N, Vx );
2729 // Compute UV of key-points on a plane
2730 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2732 gp_Vec vec ( pos.Location(), *xyzIt );
2733 TPoint* p = getShapePoints( iSub ).front();
2734 p->myUV.SetX( vec * pos.XDirection() );
2735 p->myUV.SetY( vec * pos.YDirection() );
2739 // points on edges to be used for UV computation of in-face points
2740 list< list< TPoint* > > edgesPointsList;
2741 edgesPointsList.push_back( list< TPoint* >() );
2742 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2743 list< TPoint* >::iterator pIt;
2745 // compute UV and XYZ of points on edges
2747 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2749 gp_XYZ& xyz1 = *xyzIt++;
2750 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2752 list< TPoint* > & ePoints = getShapePoints( iSub );
2753 ePoints.back()->myInitU = 1.0;
2754 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2755 while ( *pIt != ePoints.back() )
2758 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2759 gp_Vec vec ( pos.Location(), p->myXYZ );
2760 p->myUV.SetX( vec * pos.XDirection() );
2761 p->myUV.SetY( vec * pos.YDirection() );
2763 // collect on-edge points (excluding the last one)
2764 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2767 // Compute UV and XYZ of in-face points
2769 // try to use a simple algo to compute UV
2770 list< TPoint* > & fPoints = getShapePoints( iSub );
2771 bool isDeformed = false;
2772 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2773 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2774 (*pIt)->myUV, isDeformed )) {
2775 MESSAGE("can't Apply(face)");
2778 // try to use a complex algo if it is a difficult case
2779 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2781 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2782 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2783 (*pIt)->myUV, isDeformed )) {
2784 MESSAGE("can't Apply(face)");
2789 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2791 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2794 myIsComputed = true;
2796 return setErrorCode( ERR_OK );
2799 //=======================================================================
2801 //purpose : Compute nodes coordinates applying
2802 // the loaded pattern to <theFace>. The first key-point
2803 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2804 //=======================================================================
2806 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2807 const SMDS_MeshFace* theFace,
2808 const TopoDS_Shape& theSurface,
2809 const int theNodeIndexOnKeyPoint1,
2810 const bool theReverse)
2812 // MESSAGE(" ::Apply(MeshFace) " );
2813 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2814 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2816 const TopoDS_Face& face = TopoDS::Face( theSurface );
2817 TopLoc_Location loc;
2818 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2819 const gp_Trsf & aTrsf = loc.Transformation();
2821 if ( !IsLoaded() ) {
2822 MESSAGE( "Pattern not loaded" );
2823 return setErrorCode( ERR_APPL_NOT_LOADED );
2826 // check nb of nodes
2827 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2828 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2829 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2832 // find points on edges, it fills myNbKeyPntInBoundary
2833 if ( !findBoundaryPoints() )
2836 // check that there are no holes in a pattern
2837 if (myNbKeyPntInBoundary.size() > 1 ) {
2838 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2841 // Define the nodes order
2843 list< const SMDS_MeshNode* > nodes;
2844 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2845 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2847 while ( noIt->more() ) {
2848 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2849 nodes.push_back( node );
2850 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2853 if ( n != nodes.end() ) {
2855 if ( n != --nodes.end() )
2856 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2859 else if ( n != nodes.begin() )
2860 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2863 // find a node not on a seam edge, if necessary
2864 SMESH_MesherHelper helper( *theMesh );
2865 helper.SetSubShape( theSurface );
2866 const SMDS_MeshNode* inFaceNode = 0;
2867 if ( helper.GetNodeUVneedInFaceNode() )
2869 SMESH_MeshEditor editor( theMesh );
2870 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2871 int shapeID = editor.FindShape( *n );
2873 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2874 if ( !helper.IsSeamShape( shapeID ))
2879 // Set UV of key-points (i.e. of nodes of theFace )
2880 vector< gp_XY > keyUV( theFace->NbNodes() );
2881 myOrderedNodes.resize( theFace->NbNodes() );
2882 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2884 TPoint* p = getShapePoints( iSub ).front();
2885 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2886 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2888 keyUV[ iSub-1 ] = p->myUV;
2889 myOrderedNodes[ iSub-1 ] = *n;
2892 // points on edges to be used for UV computation of in-face points
2893 list< list< TPoint* > > edgesPointsList;
2894 edgesPointsList.push_back( list< TPoint* >() );
2895 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2896 list< TPoint* >::iterator pIt;
2898 // compute UV and XYZ of points on edges
2900 for ( size_t i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2902 gp_XY& uv1 = keyUV[ i ];
2903 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2905 list< TPoint* > & ePoints = getShapePoints( iSub );
2906 ePoints.back()->myInitU = 1.0;
2907 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2908 while ( *pIt != ePoints.back() )
2911 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2912 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2913 if ( !loc.IsIdentity() )
2914 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2916 // collect on-edge points (excluding the last one)
2917 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2920 // Compute UV and XYZ of in-face points
2922 // try to use a simple algo to compute UV
2923 list< TPoint* > & fPoints = getShapePoints( iSub );
2924 bool isDeformed = false;
2925 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2926 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2927 (*pIt)->myUV, isDeformed )) {
2928 MESSAGE("can't Apply(face)");
2931 // try to use a complex algo if it is a difficult case
2932 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2934 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2935 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2936 (*pIt)->myUV, isDeformed )) {
2937 MESSAGE("can't Apply(face)");
2942 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2944 TPoint * point = *pIt;
2945 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2946 if ( !loc.IsIdentity() )
2947 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2950 myIsComputed = true;
2952 return setErrorCode( ERR_OK );
2955 //=======================================================================
2956 //function : undefinedXYZ
2958 //=======================================================================
2960 static const gp_XYZ& undefinedXYZ()
2962 static gp_XYZ xyz( 1.e100, 0., 0. );
2966 //=======================================================================
2967 //function : isDefined
2969 //=======================================================================
2971 inline static bool isDefined(const gp_XYZ& theXYZ)
2973 return theXYZ.X() < 1.e100;
2976 //=======================================================================
2978 //purpose : Compute nodes coordinates applying
2979 // the loaded pattern to <theFaces>. The first key-point
2980 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2981 //=======================================================================
2983 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2984 std::set<const SMDS_MeshFace*>& theFaces,
2985 const int theNodeIndexOnKeyPoint1,
2986 const bool theReverse)
2988 MESSAGE(" ::Apply(set<MeshFace>) " );
2990 if ( !IsLoaded() ) {
2991 MESSAGE( "Pattern not loaded" );
2992 return setErrorCode( ERR_APPL_NOT_LOADED );
2995 // find points on edges, it fills myNbKeyPntInBoundary
2996 if ( !findBoundaryPoints() )
2999 // check that there are no holes in a pattern
3000 if (myNbKeyPntInBoundary.size() > 1 ) {
3001 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3006 myElemXYZIDs.clear();
3007 myXYZIdToNodeMap.clear();
3009 myIdsOnBoundary.clear();
3010 myReverseConnectivity.clear();
3012 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
3013 myElements.reserve( theFaces.size() );
3015 int ind1 = 0; // lowest point index for a face
3020 // SMESH_MeshEditor editor( theMesh );
3022 // apply to each face in theFaces set
3023 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
3024 for ( ; face != theFaces.end(); ++face )
3026 // int curShapeId = editor.FindShape( *face );
3027 // if ( curShapeId != shapeID ) {
3028 // if ( curShapeId )
3029 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
3032 // shapeID = curShapeId;
3035 if ( shape.IsNull() )
3036 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
3038 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
3040 MESSAGE( "Failed on " << *face );
3043 myElements.push_back( *face );
3045 // store computed points belonging to elements
3046 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3047 for ( ; ll != myElemPointIDs.end(); ++ll )
3049 myElemXYZIDs.push_back(TElemDef());
3050 TElemDef& xyzIds = myElemXYZIDs.back();
3051 TElemDef& pIds = *ll;
3052 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3053 int pIndex = *id + ind1;
3054 xyzIds.push_back( pIndex );
3055 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3056 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3059 // put points on links to myIdsOnBoundary,
3060 // they will be used to sew new elements on adjacent refined elements
3061 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3062 for ( int i = 0; i < nbNodes; i++ )
3064 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3065 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3066 const SMDS_MeshNode* n2 = myOrderedNodes[( i+1 ) % nbNodes ];
3067 // make a link and a node set
3068 TNodeSet linkSet, node1Set;
3069 linkSet.insert( n1 );
3070 linkSet.insert( n2 );
3071 node1Set.insert( n1 );
3072 list< TPoint* >::iterator p = linkPoints.begin();
3074 // map the first link point to n1
3075 int nId = ( *p - &myPoints[0] ) + ind1;
3076 myXYZIdToNodeMap[ nId ] = n1;
3077 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3078 groups.push_back(list< int > ());
3079 groups.back().push_back( nId );
3081 // add the linkSet to the map
3082 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3083 groups.push_back(list< int > ());
3084 list< int >& indList = groups.back();
3085 // add points to the map excluding the end points
3086 for ( p++; *p != linkPoints.back(); p++ )
3087 indList.push_back( ( *p - &myPoints[0] ) + ind1 );
3089 ind1 += myPoints.size();
3092 return !myElemXYZIDs.empty();
3095 //=======================================================================
3097 //purpose : Compute nodes coordinates applying
3098 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3099 // will be mapped into <theNode000Index>-th node. The
3100 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3102 //=======================================================================
3104 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3105 const int theNode000Index,
3106 const int theNode001Index)
3108 if ( !IsLoaded() ) {
3109 MESSAGE( "Pattern not loaded" );
3110 return setErrorCode( ERR_APPL_NOT_LOADED );
3113 // bind ID to points
3114 if ( !findBoundaryPoints() )
3117 // check that there are no holes in a pattern
3118 if (myNbKeyPntInBoundary.size() > 1 ) {
3119 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3124 myElemXYZIDs.clear();
3125 myXYZIdToNodeMap.clear();
3127 myIdsOnBoundary.clear();
3128 myReverseConnectivity.clear();
3130 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3131 myElements.reserve( theVolumes.size() );
3133 // to find point index
3134 map< TPoint*, int > pointIndex;
3135 for ( size_t i = 0; i < myPoints.size(); i++ )
3136 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3138 int ind1 = 0; // lowest point index for an element
3140 // apply to each element in theVolumes set
3141 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3142 for ( ; vol != theVolumes.end(); ++vol )
3144 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3145 MESSAGE( "Failed on " << *vol );
3148 myElements.push_back( *vol );
3150 // store computed points belonging to elements
3151 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3152 for ( ; ll != myElemPointIDs.end(); ++ll )
3154 myElemXYZIDs.push_back(TElemDef());
3155 TElemDef& xyzIds = myElemXYZIDs.back();
3156 TElemDef& pIds = *ll;
3157 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3158 int pIndex = *id + ind1;
3159 xyzIds.push_back( pIndex );
3160 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3161 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3164 // put points on edges and faces to myIdsOnBoundary,
3165 // they will be used to sew new elements on adjacent refined elements
3166 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3168 // make a set of sub-points
3170 vector< int > subIDs;
3171 if ( SMESH_Block::IsVertexID( Id )) {
3172 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3174 else if ( SMESH_Block::IsEdgeID( Id )) {
3175 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3176 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3177 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3180 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3181 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3182 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3183 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3184 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3185 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3186 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3187 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3190 list< TPoint* > & points = getShapePoints( Id );
3191 list< TPoint* >::iterator p = points.begin();
3192 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3193 groups.push_back(list< int > ());
3194 list< int >& indList = groups.back();
3195 for ( ; p != points.end(); p++ )
3196 indList.push_back( pointIndex[ *p ] + ind1 );
3197 if ( subNodes.size() == 1 ) // vertex case
3198 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3200 ind1 += myPoints.size();
3203 return !myElemXYZIDs.empty();
3206 //=======================================================================
3208 //purpose : Create a pattern from the mesh built on <theBlock>
3209 //=======================================================================
3211 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3212 const TopoDS_Shell& theBlock,
3217 myToKeepNodes = theKeepNodes;
3218 SMESHDS_SubMesh * aSubMesh;
3220 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3222 // load shapes in myShapeIDMap
3224 TopoDS_Vertex v1, v2;
3225 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3226 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3229 int nbNodes = 0, shapeID;
3230 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3232 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3233 aSubMesh = getSubmeshWithElements( theMesh, S );
3235 nbNodes += aSubMesh->NbNodes();
3237 myPoints.resize( nbNodes );
3239 // load U of points on edges
3240 TNodePointIDMap nodePointIDMap;
3242 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3244 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3245 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3246 aSubMesh = getSubmeshWithElements( theMesh, S );
3247 if ( ! aSubMesh ) continue;
3248 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3249 if ( !nIt->more() ) continue;
3251 // store a node and a point
3252 while ( nIt->more() ) {
3253 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3254 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3256 nodePointIDMap.insert( make_pair( node, iPoint ));
3257 if ( block.IsVertexID( shapeID ))
3258 myKeyPointIDs.push_back( iPoint );
3259 TPoint* p = & myPoints[ iPoint++ ];
3260 shapePoints.push_back( p );
3261 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3262 p->myInitXYZ.SetCoord( 0,0,0 );
3264 list< TPoint* >::iterator pIt = shapePoints.begin();
3267 switch ( S.ShapeType() )
3272 for ( ; pIt != shapePoints.end(); pIt++ ) {
3273 double * coef = block.GetShapeCoef( shapeID );
3274 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3275 if ( coef[ iCoord - 1] > 0 )
3276 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3278 if ( S.ShapeType() == TopAbs_VERTEX )
3281 const TopoDS_Edge& edge = TopoDS::Edge( S );
3283 BRep_Tool::Range( edge, f, l );
3284 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3285 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3286 pIt = shapePoints.begin();
3287 nIt = aSubMesh->GetNodes();
3288 for ( ; nIt->more(); pIt++ )
3290 const SMDS_MeshNode* node = nIt->next();
3291 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3293 const SMDS_EdgePosition* epos =
3294 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3295 double u = ( epos->GetUParameter() - f ) / ( l - f );
3296 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3301 for ( ; pIt != shapePoints.end(); pIt++ )
3303 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3304 MESSAGE( "!block.ComputeParameters()" );
3305 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3309 } // loop on block sub-shapes
3313 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3316 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3317 while ( elemIt->more() ) {
3318 const SMDS_MeshElement* elem = elemIt->next();
3319 myElemPointIDs.push_back( TElemDef() );
3320 TElemDef& elemPoints = myElemPointIDs.back();
3321 int nbNodes = elem->NbCornerNodes();
3322 for ( int i = 0;i < nbNodes; ++i )
3323 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3327 myIsBoundaryPointsFound = true;
3329 if ( myToKeepNodes )
3331 myInNodes.resize( nodePointIDMap.size() );
3332 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
3333 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
3334 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
3337 return setErrorCode( ERR_OK );
3340 //=======================================================================
3341 //function : getSubmeshWithElements
3342 //purpose : return submesh containing elements bound to theBlock in theMesh
3343 //=======================================================================
3345 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3346 const TopoDS_Shape& theShape)
3348 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3349 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3352 if ( theShape.ShapeType() == TopAbs_SHELL )
3354 // look for submesh of VOLUME
3355 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3356 for (; it.More(); it.Next()) {
3357 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3358 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3366 //=======================================================================
3368 //purpose : Compute nodes coordinates applying
3369 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3370 // will be mapped into <theVertex000>. The (0,0,1)
3371 // fifth key-point will be mapped into <theVertex001>.
3372 //=======================================================================
3374 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3375 const TopoDS_Vertex& theVertex000,
3376 const TopoDS_Vertex& theVertex001)
3378 if (!findBoundaryPoints() || // bind ID to points
3379 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3382 SMESH_Block block; // bind ID to shape
3383 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3384 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3386 // compute XYZ of points on shapes
3388 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3390 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3391 list< TPoint* >::iterator pIt = shapePoints.begin();
3392 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3393 switch ( S.ShapeType() )
3395 case TopAbs_VERTEX: {
3397 for ( ; pIt != shapePoints.end(); pIt++ )
3398 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3403 for ( ; pIt != shapePoints.end(); pIt++ )
3404 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3409 for ( ; pIt != shapePoints.end(); pIt++ )
3410 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3414 for ( ; pIt != shapePoints.end(); pIt++ )
3415 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3417 } // loop on block sub-shapes
3419 myIsComputed = true;
3421 return setErrorCode( ERR_OK );
3424 //=======================================================================
3426 //purpose : Compute nodes coordinates applying
3427 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3428 // will be mapped into <theNode000Index>-th node. The
3429 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3431 //=======================================================================
3433 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3434 const int theNode000Index,
3435 const int theNode001Index)
3437 if (!findBoundaryPoints()) // bind ID to points
3440 SMESH_Block block; // bind ID to shape
3441 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3442 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3443 // compute XYZ of points on shapes
3445 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3447 list< TPoint* > & shapePoints = getShapePoints( ID );
3448 list< TPoint* >::iterator pIt = shapePoints.begin();
3450 if ( block.IsVertexID( ID ))
3451 for ( ; pIt != shapePoints.end(); pIt++ ) {
3452 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3454 else if ( block.IsEdgeID( ID ))
3455 for ( ; pIt != shapePoints.end(); pIt++ ) {
3456 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3458 else if ( block.IsFaceID( ID ))
3459 for ( ; pIt != shapePoints.end(); pIt++ ) {
3460 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3463 for ( ; pIt != shapePoints.end(); pIt++ )
3464 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3465 } // loop on block sub-shapes
3467 myIsComputed = true;
3469 return setErrorCode( ERR_OK );
3472 //=======================================================================
3473 //function : mergePoints
3474 //purpose : Merge XYZ on edges and/or faces.
3475 //=======================================================================
3477 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3479 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3480 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3482 list<list< int > >& groups = idListIt->second;
3483 if ( groups.size() < 2 )
3487 const TNodeSet& nodes = idListIt->first;
3488 double tol2 = 1.e-10;
3489 if ( nodes.size() > 1 ) {
3491 TNodeSet::const_iterator n = nodes.begin();
3492 for ( ; n != nodes.end(); ++n )
3493 box.Add( gp_Pnt( SMESH_TNodeXYZ( *n )));
3494 double x, y, z, X, Y, Z;
3495 box.Get( x, y, z, X, Y, Z );
3496 gp_Pnt p( x, y, z ), P( X, Y, Z );
3497 tol2 = 1.e-4 * p.SquareDistance( P );
3500 // to unite groups on link
3501 bool unite = ( uniteGroups && nodes.size() == 2 );
3502 map< double, int > distIndMap;
3503 const SMDS_MeshNode* node = *nodes.begin();
3504 gp_Pnt P = SMESH_TNodeXYZ( node );
3506 // compare points, replace indices
3508 list< int >::iterator ind1, ind2;
3509 list< list< int > >::iterator grpIt1, grpIt2;
3510 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3512 list< int >& indices1 = *grpIt1;
3514 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3516 list< int >& indices2 = *grpIt2;
3517 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3519 gp_XYZ& p1 = myXYZ[ *ind1 ];
3520 ind2 = indices2.begin();
3521 while ( ind2 != indices2.end() )
3523 gp_XYZ& p2 = myXYZ[ *ind2 ];
3524 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3525 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3527 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3528 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3529 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3530 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3532 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3533 myXYZ[ *ind2 ] = undefinedXYZ();
3534 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3536 ind2 = indices2.erase( ind2 );
3543 if ( unite ) { // sort indices using distIndMap
3544 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3546 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3547 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3548 distIndMap.insert( make_pair( dist, *ind1 ));
3552 if ( unite ) { // put all sorted indices into the first group
3553 list< int >& g = groups.front();
3555 map< double, int >::iterator dist_ind = distIndMap.begin();
3556 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3557 g.push_back( dist_ind->second );
3559 } // loop on myIdsOnBoundary
3562 //=======================================================================
3563 //function : makePolyElements
3564 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3565 //=======================================================================
3567 void SMESH_Pattern::
3568 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3569 const bool toCreatePolygons,
3570 const bool toCreatePolyedrs)
3572 myPolyElemXYZIDs.clear();
3573 myPolyElems.clear();
3574 myPolyElems.reserve( myIdsOnBoundary.size() );
3576 // make a set of refined elements
3577 TIDSortedElemSet elemSet, avoidSet( myElements.begin(), myElements.end() );
3579 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3581 if ( toCreatePolygons )
3583 int lastFreeId = myXYZ.size();
3585 // loop on links of refined elements
3586 indListIt = myIdsOnBoundary.begin();
3587 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3589 const TNodeSet & linkNodes = indListIt->first;
3590 if ( linkNodes.size() != 2 )
3591 continue; // skip face
3592 const SMDS_MeshNode* n1 = * linkNodes.begin();
3593 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3595 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3596 if ( idGroups.empty() || idGroups.front().empty() )
3599 // find not refined face having n1-n2 link
3603 const SMDS_MeshElement* face =
3604 SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3607 avoidSet.insert ( face );
3608 myPolyElems.push_back( face );
3610 // some links of <face> are split;
3611 // make list of xyz for <face>
3612 myPolyElemXYZIDs.push_back(TElemDef());
3613 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3614 // loop on links of a <face>
3615 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3616 int i = 0, nbNodes = face->NbNodes();
3617 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3618 while ( nIt->more() )
3619 nodes[ i++ ] = smdsNode( nIt->next() );
3620 nodes[ i ] = nodes[ 0 ];
3621 for ( i = 0; i < nbNodes; ++i )
3623 // look for point mapped on a link
3624 TNodeSet faceLinkNodes;
3625 faceLinkNodes.insert( nodes[ i ] );
3626 faceLinkNodes.insert( nodes[ i + 1 ] );
3627 if ( faceLinkNodes == linkNodes )
3628 nn_IdList = indListIt;
3630 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3631 // add face point ids
3632 faceNodeIds.push_back( ++lastFreeId );
3633 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3634 if ( nn_IdList != myIdsOnBoundary.end() )
3636 // there are points mapped on a link
3637 list< int >& mappedIds = nn_IdList->second.front();
3638 if ( isReversed( nodes[ i ], mappedIds ))
3639 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3641 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3643 } // loop on links of a <face>
3649 if ( myIs2D && idGroups.size() > 1 ) {
3651 // sew new elements on 2 refined elements sharing n1-n2 link
3653 list< int >& idsOnLink = idGroups.front();
3654 // temporarily add ids of link nodes to idsOnLink
3655 bool rev = isReversed( n1, idsOnLink );
3656 for ( int i = 0; i < 2; ++i )
3659 nodeSet.insert( i ? n2 : n1 );
3660 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3661 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3662 int nodeId = groups.front().front();
3664 if ( rev ) append = !append;
3666 idsOnLink.push_back( nodeId );
3668 idsOnLink.push_front( nodeId );
3670 list< int >::iterator id = idsOnLink.begin();
3671 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3673 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3674 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3675 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3677 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3678 // look for <id> in element definition
3679 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3680 ASSERT ( idDef != pIdList->end() );
3681 // look for 2 neighbour ids of <id> in element definition
3682 for ( int prev = 0; prev < 2; ++prev ) {
3683 TElemDef::iterator idDef2 = idDef;
3685 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3687 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3688 // look for idDef2 on a link starting from id
3689 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3690 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3691 // insert ids located on link between <id> and <id2>
3692 // into the element definition between idDef and idDef2
3694 for ( ; id2 != id; --id2 )
3695 pIdList->insert( idDef, *id2 );
3697 list< int >::iterator id1 = id;
3698 for ( ++id1, ++id2; id1 != id2; ++id1 )
3699 pIdList->insert( idDef2, *id1 );
3705 // remove ids of link nodes
3706 idsOnLink.pop_front();
3707 idsOnLink.pop_back();
3709 } // loop on myIdsOnBoundary
3710 } // if ( toCreatePolygons )
3712 if ( toCreatePolyedrs )
3714 // check volumes adjacent to the refined elements
3715 SMDS_VolumeTool volTool;
3716 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3717 for ( ; refinedElem != myElements.end(); ++refinedElem )
3719 // loop on nodes of refinedElem
3720 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3721 while ( nIt->more() ) {
3722 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3723 // loop on inverse elements of node
3724 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3725 while ( eIt->more() )
3727 const SMDS_MeshElement* elem = eIt->next();
3728 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3729 continue; // skip faces or refined elements
3730 // add polyhedron definition
3731 myPolyhedronQuantities.push_back(vector<int> ());
3732 myPolyElemXYZIDs.push_back(TElemDef());
3733 vector<int>& quantity = myPolyhedronQuantities.back();
3734 TElemDef & elemDef = myPolyElemXYZIDs.back();
3735 // get definitions of new elements on volume faces
3736 bool makePoly = false;
3737 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3739 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3740 volTool.NbFaceNodes( iF ),
3741 theNodes, elemDef, quantity))
3745 myPolyElems.push_back( elem );
3747 myPolyhedronQuantities.pop_back();
3748 myPolyElemXYZIDs.pop_back();
3756 //=======================================================================
3757 //function : getFacesDefinition
3758 //purpose : return faces definition for a volume face defined by theBndNodes
3759 //=======================================================================
3761 bool SMESH_Pattern::
3762 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3763 const int theNbBndNodes,
3764 const vector< const SMDS_MeshNode* >& theNodes,
3765 list< int >& theFaceDefs,
3766 vector<int>& theQuantity)
3768 bool makePoly = false;
3770 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3772 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3774 // make a set of all nodes on a face
3776 if ( !myIs2D ) { // for 2D, merge only edges
3777 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3778 if ( nn_IdList != myIdsOnBoundary.end() ) {
3779 list< int > & faceIds = nn_IdList->second.front();
3780 if ( !faceIds.empty() ) {
3782 ids.insert( faceIds.begin(), faceIds.end() );
3787 // add ids on links and bnd nodes
3788 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3789 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3790 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3792 // add id of iN-th bnd node
3794 nSet.insert( theBndNodes[ iN ] );
3795 nn_IdList = myIdsOnBoundary.find( nSet );
3796 int bndId = ++lastFreeId;
3797 if ( nn_IdList != myIdsOnBoundary.end() ) {
3798 bndId = nn_IdList->second.front().front();
3799 ids.insert( bndId );
3802 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3804 faceDef.push_back( bndId );
3805 // add ids on a link
3807 linkNodes.insert( theBndNodes[ iN ]);
3808 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3809 nn_IdList = myIdsOnBoundary.find( linkNodes );
3810 if ( nn_IdList != myIdsOnBoundary.end() ) {
3811 list< int > & linkIds = nn_IdList->second.front();
3812 if ( !linkIds.empty() )
3815 ids.insert( linkIds.begin(), linkIds.end() );
3816 if ( isReversed( theBndNodes[ iN ], linkIds ))
3817 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3819 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3824 // find faces definition of new volumes
3826 bool defsAdded = false;
3827 if ( !myIs2D ) { // for 2D, merge only edges
3828 SMDS_VolumeTool vol;
3829 set< TElemDef* > checkedVolDefs;
3830 set< int >::iterator id = ids.begin();
3831 for ( ; id != ids.end(); ++id )
3833 // definitions of volumes sharing id
3834 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3835 ASSERT( !defList.empty() );
3836 // loop on volume definitions
3837 list< TElemDef* >::iterator pIdList = defList.begin();
3838 for ( ; pIdList != defList.end(); ++pIdList)
3840 if ( !checkedVolDefs.insert( *pIdList ).second )
3841 continue; // skip already checked volume definition
3842 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3843 // loop on face defs of a volume
3844 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3845 if ( volType == SMDS_VolumeTool::UNKNOWN )
3847 int nbFaces = vol.NbFaces( volType );
3848 for ( int iF = 0; iF < nbFaces; ++iF )
3850 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3851 int iN, nbN = vol.NbFaceNodes( volType, iF );
3852 // check if all nodes of a faces are in <ids>
3854 for ( iN = 0; iN < nbN && all; ++iN ) {
3855 int nodeId = idVec[ nodeInds[ iN ]];
3856 all = ( ids.find( nodeId ) != ids.end() );
3859 // store a face definition
3860 for ( iN = 0; iN < nbN; ++iN ) {
3861 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3863 theQuantity.push_back( nbN );
3871 theQuantity.push_back( faceDef.size() );
3872 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3878 //=======================================================================
3879 //function : clearSubMesh
3881 //=======================================================================
3883 static bool clearSubMesh( SMESH_Mesh* theMesh,
3884 const TopoDS_Shape& theShape)
3886 bool removed = false;
3887 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3889 removed = !aSubMesh->IsEmpty();
3891 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3894 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3895 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3897 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3898 removed = eIt->more();
3899 while ( eIt->more() )
3900 aMeshDS->RemoveElement( eIt->next() );
3901 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3902 removed = removed || nIt->more();
3903 while ( nIt->more() )
3904 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3910 //=======================================================================
3911 //function : clearMesh
3912 //purpose : clear mesh elements existing on myShape in theMesh
3913 //=======================================================================
3915 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3918 if ( !myShape.IsNull() )
3920 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3921 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3922 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3924 clearSubMesh( theMesh, it.Value() );
3930 //=======================================================================
3931 //function : findExistingNodes
3932 //purpose : fills nodes vector with nodes existing on a given shape (IMP 22368)
3933 // Returns true if all nodes for all points on S are found
3934 //=======================================================================
3936 bool SMESH_Pattern::findExistingNodes( SMESH_Mesh* mesh,
3937 const TopoDS_Shape& S,
3938 const std::list< TPoint* > & points,
3939 vector< const SMDS_MeshNode* > & nodesVector)
3941 if ( S.IsNull() || points.empty() )
3944 SMESHDS_Mesh* aMeshDS = mesh->GetMeshDS();
3946 switch ( S.ShapeType() )
3950 int pIndex = points.back() - &myPoints[0];
3951 if ( !nodesVector[ pIndex ] )
3952 nodesVector[ pIndex ] = SMESH_Algo::VertexNode( TopoDS::Vertex( S ), aMeshDS );
3953 return nodesVector[ pIndex ];
3957 const TopoDS_Edge& edge = TopoDS::Edge( S );
3958 map< double, const SMDS_MeshNode* > paramsOfNodes;
3959 if ( !SMESH_Algo::GetSortedNodesOnEdge( aMeshDS, edge,
3960 /*ignoreMediumNodes=*/false,
3962 || paramsOfNodes.size() < 3 )
3964 // points on VERTEXes are included with wrong myU
3965 list< TPoint* >::const_reverse_iterator pItR = ++points.rbegin();
3966 list< TPoint* >::const_iterator pItF = ++points.begin();
3967 const bool isForward = ( (*pItF)->myU < (*pItR)->myU );
3968 map< double, const SMDS_MeshNode* >::iterator u2n = ++paramsOfNodes.begin();
3969 map< double, const SMDS_MeshNode* >::iterator u2nEnd = --paramsOfNodes.end();
3971 if ( paramsOfNodes.size() == points.size() )
3973 for ( ; u2n != u2nEnd; ++u2n )
3975 p = ( isForward ? *pItF : *pItR );
3976 int pIndex = p - &myPoints[0];
3977 if ( !nodesVector [ pIndex ] )
3978 nodesVector [ pIndex ] = u2n->second;
3986 const double tolFact = 0.05;
3987 while ( u2n != u2nEnd && pItF != points.end() )
3989 const double u = u2n->first;
3990 const SMDS_MeshNode* n = u2n->second;
3991 const double tol = ( (++u2n)->first - u ) * tolFact;
3994 p = ( isForward ? *pItF : *pItR );
3995 if ( Abs( u - p->myU ) < tol )
3997 int pIndex = p - &myPoints[0];
3998 if ( !nodesVector [ pIndex ] )
3999 nodesVector [ pIndex ] = n;
4005 while ( p->myU < u && ( ++pItF, ++pItR != points.rend() ));
4009 } // case TopAbs_EDGE:
4012 } // switch ( S.ShapeType() )
4017 //=======================================================================
4018 //function : MakeMesh
4019 //purpose : Create nodes and elements in <theMesh> using nodes
4020 // coordinates computed by either of Apply...() methods
4021 //=======================================================================
4023 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
4024 const bool toCreatePolygons,
4025 const bool toCreatePolyedrs)
4027 if ( !myIsComputed )
4028 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
4030 mergePoints( toCreatePolygons );
4032 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4034 // clear elements and nodes existing on myShape
4037 bool onMeshElements = ( !myElements.empty() );
4039 // Create missing nodes
4041 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
4042 if ( onMeshElements )
4044 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
4045 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
4046 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
4047 nodesVector[ i_node->first ] = i_node->second;
4049 for ( size_t i = 0; i < myXYZ.size(); ++i ) {
4050 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
4051 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
4055 if ( theMesh->HasShapeToMesh() )
4057 // set nodes on EDGEs (IMP 22368)
4058 SMESH_MesherHelper helper( *theMesh );
4059 helper.ToFixNodeParameters( true );
4060 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
4061 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
4063 list<list< int > >& groups = idListIt->second;
4064 const TNodeSet& nodes = idListIt->first;
4065 if ( nodes.size() != 2 )
4066 continue; // not a link
4067 const SMDS_MeshNode* n1 = *nodes.begin();
4068 const SMDS_MeshNode* n2 = *nodes.rbegin();
4069 TopoDS_Shape S1 = helper.GetSubShapeByNode( n1, aMeshDS );
4070 TopoDS_Shape S2 = helper.GetSubShapeByNode( n2, aMeshDS );
4071 if ( S1.IsNull() || S1.ShapeType() < TopAbs_EDGE ||
4072 S2.IsNull() || S2.ShapeType() < TopAbs_EDGE )
4075 if ( S1.ShapeType() == TopAbs_EDGE )
4077 if ( S1 == S2 || helper.IsSubShape( S2, S1 ))
4080 else if ( S2.ShapeType() == TopAbs_EDGE )
4082 if ( helper.IsSubShape( S1, S2 ))
4087 S = helper.GetCommonAncestor( S1, S2, *theMesh, TopAbs_EDGE );
4091 const TopoDS_Edge & E = TopoDS::Edge( S );
4092 helper.SetSubShape( E );
4093 list<list< int > >::iterator g = groups.begin();
4094 for ( ; g != groups.end(); ++g )
4096 list< int >& ids = *g;
4097 list< int >::iterator id = ids.begin();
4098 for ( ; id != ids.end(); ++id )
4099 if ( nodesVector[ *id ] && nodesVector[ *id ]->getshapeId() < 1 )
4102 aMeshDS->SetNodeOnEdge( nodesVector[ *id ], E, u );
4103 helper.CheckNodeU( E, nodesVector[ *id ], u, 1e-7, true );
4108 } // if ( onMeshElements )
4112 nodesVector.resize( myPoints.size(), 0 );
4114 // loop on sub-shapes of myShape: create nodes
4115 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
4116 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
4118 list< TPoint* > & points = idPointIt->second;
4120 if ( !myShapeIDMap.IsEmpty() )
4121 S = myShapeIDMap( idPointIt->first );
4123 // find existing nodes on EDGEs and VERTEXes
4124 if ( findExistingNodes( theMesh, S, points, nodesVector ))
4127 list< TPoint* >::iterator pIt = points.begin();
4128 for ( ; pIt != points.end(); pIt++ )
4130 TPoint* point = *pIt;
4131 int pIndex = point - &myPoints[0];
4132 if ( nodesVector [ pIndex ] )
4134 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
4137 nodesVector [ pIndex ] = node;
4139 if ( !S.IsNull() ) {
4141 switch ( S.ShapeType() ) {
4142 case TopAbs_VERTEX: {
4143 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
4146 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
4149 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
4150 point->myUV.X(), point->myUV.Y() ); break;
4153 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
4162 if ( onMeshElements )
4164 // prepare data to create poly elements
4165 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
4168 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
4169 // sew old and new elements
4170 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
4174 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4177 aMeshDS->compactMesh();
4179 if ( myToKeepNodes )
4180 myOutNodes.swap( nodesVector );
4182 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4183 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4184 // for ( ; i_sm != sm.end(); i_sm++ )
4186 // cout << " SM " << i_sm->first << " ";
4187 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4188 // //SMDS_ElemIteratorPtr GetElements();
4189 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4190 // while ( nit->more() )
4191 // cout << nit->next()->GetID() << " ";
4194 return setErrorCode( ERR_OK );
4197 //=======================================================================
4198 //function : createElements
4199 //purpose : add elements to the mesh
4200 //=======================================================================
4202 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4203 const vector<const SMDS_MeshNode* >& theNodesVector,
4204 const list< TElemDef > & theElemNodeIDs,
4205 const vector<const SMDS_MeshElement*>& theElements)
4207 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4208 SMESH_MeshEditor editor( theMesh );
4210 bool onMeshElements = !theElements.empty();
4212 // shapes and groups theElements are on
4213 vector< int > shapeIDs;
4214 vector< list< SMESHDS_Group* > > groups;
4215 set< const SMDS_MeshNode* > shellNodes;
4216 if ( onMeshElements )
4218 shapeIDs.resize( theElements.size() );
4219 groups.resize( theElements.size() );
4220 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4221 set<SMESHDS_GroupBase*>::const_iterator grIt;
4222 for ( size_t i = 0; i < theElements.size(); i++ )
4224 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4225 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4226 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4227 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4228 groups[ i ].push_back( group );
4231 // get all nodes bound to shells because their SpacePosition is not set
4232 // by SMESHDS_Mesh::SetNodeInVolume()
4233 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4234 if ( !aMainShape.IsNull() ) {
4235 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4236 for ( ; shellExp.More(); shellExp.Next() )
4238 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4240 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4241 while ( nIt->more() )
4242 shellNodes.insert( nIt->next() );
4247 // nb new elements per a refined element
4248 int nbNewElemsPerOld = 1;
4249 if ( onMeshElements )
4250 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4254 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4255 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4256 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4258 const TElemDef & elemNodeInd = *enIt;
4260 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4261 TElemDef::const_iterator id = elemNodeInd.begin();
4263 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4264 if ( *id < (int) theNodesVector.size() )
4265 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4267 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4269 // dim of refined elem
4270 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4271 if ( onMeshElements ) {
4272 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4275 const SMDS_MeshElement* elem = 0;
4277 switch ( nbNodes ) {
4279 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4281 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4283 if ( !onMeshElements ) {// create a quadratic face
4284 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4285 nodes[4], nodes[5] ); break;
4286 } // else do not break but create a polygon
4288 if ( !onMeshElements ) {// create a quadratic face
4289 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4290 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4291 } // else do not break but create a polygon
4293 elem = aMeshDS->AddPolygonalFace( nodes );
4297 switch ( nbNodes ) {
4299 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4301 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4304 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4305 nodes[4], nodes[5] ); break;
4307 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4308 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4310 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4313 // set element on a shape
4314 if ( elem && onMeshElements ) // applied to mesh elements
4316 int shapeID = shapeIDs[ elemIndex ];
4317 if ( shapeID > 0 ) {
4318 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4319 // set nodes on a shape
4320 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4321 if ( S.ShapeType() == TopAbs_SOLID ) {
4322 TopoDS_Iterator shellIt( S );
4323 if ( shellIt.More() )
4324 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4326 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4327 while ( noIt->more() ) {
4328 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4329 if ( node->getshapeId() < 1 &&
4330 shellNodes.find( node ) == shellNodes.end() )
4332 if ( S.ShapeType() == TopAbs_FACE )
4333 aMeshDS->SetNodeOnFace( node, shapeID,
4334 Precision::Infinite(),// <- it's a sign that UV is not set
4335 Precision::Infinite());
4337 aMeshDS->SetNodeInVolume( node, shapeID );
4338 shellNodes.insert( node );
4343 // add elem in groups
4344 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4345 for ( ; g != groups[ elemIndex ].end(); ++g )
4346 (*g)->SMDSGroup().Add( elem );
4348 if ( elem && !myShape.IsNull() ) // applied to shape
4349 aMeshDS->SetMeshElementOnShape( elem, myShape );
4352 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4353 // so that operations with hypotheses will erase the mesh being built
4355 SMESH_subMesh * subMesh;
4356 if ( !myShape.IsNull() ) {
4357 subMesh = theMesh->GetSubMesh( myShape );
4359 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4361 if ( onMeshElements ) {
4362 list< int > elemIDs;
4363 for ( size_t i = 0; i < theElements.size(); i++ )
4365 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4367 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4369 elemIDs.push_back( theElements[ i ]->GetID() );
4371 // remove refined elements
4372 editor.Remove( elemIDs, false );
4376 //=======================================================================
4377 //function : isReversed
4378 //purpose : check xyz ids order in theIdsList taking into account
4379 // theFirstNode on a link
4380 //=======================================================================
4382 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4383 const list< int >& theIdsList) const
4385 if ( theIdsList.size() < 2 )
4388 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4390 list<int>::const_iterator id = theIdsList.begin();
4391 for ( int i = 0; i < 2; ++i, ++id ) {
4392 if ( *id < (int) myXYZ.size() )
4393 P[ i ] = myXYZ[ *id ];
4395 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4396 i_n = myXYZIdToNodeMap.find( *id );
4397 ASSERT( i_n != myXYZIdToNodeMap.end() );
4398 const SMDS_MeshNode* n = i_n->second;
4399 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4402 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4406 //=======================================================================
4407 //function : arrangeBoundaries
4408 //purpose : if there are several wires, arrange boundaryPoints so that
4409 // the outer wire goes first and fix inner wires orientation
4410 // update myKeyPointIDs to correspond to the order of key-points
4411 // in boundaries; sort internal boundaries by the nb of key-points
4412 //=======================================================================
4414 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4416 typedef list< list< TPoint* > >::iterator TListOfListIt;
4417 TListOfListIt bndIt;
4418 list< TPoint* >::iterator pIt;
4420 int nbBoundaries = boundaryList.size();
4421 if ( nbBoundaries > 1 )
4423 // sort boundaries by nb of key-points
4424 if ( nbBoundaries > 2 )
4426 // move boundaries in tmp list
4427 list< list< TPoint* > > tmpList;
4428 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4429 // make a map nb-key-points to boundary-position-in-tmpList,
4430 // boundary-positions get ordered in it
4431 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4432 TNbKpBndPosMap nbKpBndPosMap;
4433 bndIt = tmpList.begin();
4434 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4435 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4436 int nb = *nbKpIt * nbBoundaries;
4437 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4439 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4441 // move boundaries back to boundaryList
4442 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4443 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4444 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4445 TListOfListIt bndPos1 = bndPos2++;
4446 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4450 // Look for the outer boundary: the one with the point with the least X
4451 double leastX = DBL_MAX;
4452 TListOfListIt outerBndPos;
4453 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4455 list< TPoint* >& boundary = (*bndIt);
4456 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4458 TPoint* point = *pIt;
4459 if ( point->myInitXYZ.X() < leastX ) {
4460 leastX = point->myInitXYZ.X();
4461 outerBndPos = bndIt;
4466 if ( outerBndPos != boundaryList.begin() )
4467 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos );
4469 } // if nbBoundaries > 1
4471 // Check boundaries orientation and re-fill myKeyPointIDs
4473 set< TPoint* > keyPointSet;
4474 list< int >::iterator kpIt = myKeyPointIDs.begin();
4475 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4476 keyPointSet.insert( & myPoints[ *kpIt ]);
4477 myKeyPointIDs.clear();
4479 // update myNbKeyPntInBoundary also
4480 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4482 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4484 // find the point with the least X
4485 double leastX = DBL_MAX;
4486 list< TPoint* >::iterator xpIt;
4487 list< TPoint* >& boundary = (*bndIt);
4488 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4490 TPoint* point = *pIt;
4491 if ( point->myInitXYZ.X() < leastX ) {
4492 leastX = point->myInitXYZ.X();
4496 // find points next to the point with the least X
4497 TPoint* p = *xpIt, *pPrev, *pNext;
4498 if ( p == boundary.front() )
4499 pPrev = *(++boundary.rbegin());
4505 if ( p == boundary.back() )
4506 pNext = *(++boundary.begin());
4511 // vectors of boundary direction near <p>
4512 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4513 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4514 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4515 double yPrev = v1.Y() / sqrt( sqMag1 );
4516 double yNext = v2.Y() / sqrt( sqMag2 );
4517 double sumY = yPrev + yNext;
4519 if ( bndIt == boundaryList.begin() ) // outer boundary
4527 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4528 (*nbKpIt) = 0; // count nb of key-points again
4529 pIt = boundary.begin();
4530 for ( ; pIt != boundary.end(); pIt++)
4532 TPoint* point = *pIt;
4533 if ( keyPointSet.find( point ) == keyPointSet.end() )
4535 // find an index of a keypoint
4537 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4538 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4539 if ( &(*pVecIt) == point )
4541 myKeyPointIDs.push_back( index );
4544 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4547 } // loop on a list of boundaries
4549 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4552 //=======================================================================
4553 //function : findBoundaryPoints
4554 //purpose : if loaded from file, find points to map on edges and faces and
4555 // compute their parameters
4556 //=======================================================================
4558 bool SMESH_Pattern::findBoundaryPoints()
4560 if ( myIsBoundaryPointsFound ) return true;
4562 myNbKeyPntInBoundary.clear();
4566 set< TPoint* > pointsInElems;
4568 // Find free links of elements:
4569 // put links of all elements in a set and remove links encountered twice
4571 typedef pair< TPoint*, TPoint*> TLink;
4572 set< TLink > linkSet;
4573 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4574 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4576 TElemDef & elemPoints = *epIt;
4577 TElemDef::iterator pIt = elemPoints.begin();
4578 int prevP = elemPoints.back();
4579 for ( ; pIt != elemPoints.end(); pIt++ ) {
4580 TPoint* p1 = & myPoints[ prevP ];
4581 TPoint* p2 = & myPoints[ *pIt ];
4582 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4583 ASSERT( link.first != link.second );
4584 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4585 if ( !itUniq.second )
4586 linkSet.erase( itUniq.first );
4589 pointsInElems.insert( p1 );
4592 // Now linkSet contains only free links,
4593 // find the points order that they have in boundaries
4595 // 1. make a map of key-points
4596 set< TPoint* > keyPointSet;
4597 list< int >::iterator kpIt = myKeyPointIDs.begin();
4598 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4599 keyPointSet.insert( & myPoints[ *kpIt ]);
4601 // 2. chain up boundary points
4602 list< list< TPoint* > > boundaryList;
4603 boundaryList.push_back( list< TPoint* >() );
4604 list< TPoint* > * boundary = & boundaryList.back();
4606 TPoint *point1, *point2, *keypoint1;
4607 kpIt = myKeyPointIDs.begin();
4608 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4609 // loop on free links: look for the next point
4611 set< TLink >::iterator lIt = linkSet.begin();
4612 while ( lIt != linkSet.end() )
4614 if ( (*lIt).first == point1 )
4615 point2 = (*lIt).second;
4616 else if ( (*lIt).second == point1 )
4617 point2 = (*lIt).first;
4622 linkSet.erase( lIt );
4623 lIt = linkSet.begin();
4625 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4627 boundary->push_back( point2 );
4629 else // a key-point found
4631 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4633 if ( point2 != keypoint1 ) // its not the boundary end
4635 boundary->push_back( point2 );
4637 else // the boundary end reached
4639 boundary->push_front( keypoint1 );
4640 boundary->push_back( keypoint1 );
4641 myNbKeyPntInBoundary.push_back( iKeyPoint );
4642 if ( keyPointSet.empty() )
4643 break; // all boundaries containing key-points are found
4645 // prepare to search for the next boundary
4646 boundaryList.push_back( list< TPoint* >() );
4647 boundary = & boundaryList.back();
4648 point2 = keypoint1 = (*keyPointSet.begin());
4652 } // loop on the free links set
4654 if ( boundary->empty() ) {
4655 MESSAGE(" a separate key-point");
4656 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4659 // if there are several wires, arrange boundaryPoints so that
4660 // the outer wire goes first and fix inner wires orientation;
4661 // sort myKeyPointIDs to correspond to the order of key-points
4663 arrangeBoundaries( boundaryList );
4665 // Find correspondence shape ID - points,
4666 // compute points parameter on edge
4668 keyPointSet.clear();
4669 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4670 keyPointSet.insert( & myPoints[ *kpIt ]);
4672 set< TPoint* > edgePointSet; // to find in-face points
4673 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4674 int edgeID = myKeyPointIDs.size() + 1;
4676 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4677 for ( ; bndIt != boundaryList.end(); bndIt++ )
4679 boundary = & (*bndIt);
4680 double edgeLength = 0;
4681 list< TPoint* >::iterator pIt = boundary->begin();
4682 getShapePoints( edgeID ).push_back( *pIt );
4683 getShapePoints( vertexID++ ).push_back( *pIt );
4684 for ( pIt++; pIt != boundary->end(); pIt++)
4686 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4687 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4688 TPoint* point = *pIt;
4689 edgePointSet.insert( point );
4690 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4692 edgePoints.push_back( point );
4693 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4694 point->myInitU = edgeLength;
4698 // treat points on the edge which ends up: compute U [0,1]
4699 edgePoints.push_back( point );
4700 if ( edgePoints.size() > 2 ) {
4701 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4702 list< TPoint* >::iterator epIt = edgePoints.begin();
4703 for ( ; epIt != edgePoints.end(); epIt++ )
4704 (*epIt)->myInitU /= edgeLength;
4706 // begin the next edge treatment
4709 if ( point != boundary->front() ) { // not the first key-point again
4710 getShapePoints( edgeID ).push_back( point );
4711 getShapePoints( vertexID++ ).push_back( point );
4717 // find in-face points
4718 list< TPoint* > & facePoints = getShapePoints( edgeID );
4719 vector< TPoint >::iterator pVecIt = myPoints.begin();
4720 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4721 TPoint* point = &(*pVecIt);
4722 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4723 pointsInElems.find( point ) != pointsInElems.end())
4724 facePoints.push_back( point );
4731 // bind points to shapes according to point parameters
4732 vector< TPoint >::iterator pVecIt = myPoints.begin();
4733 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4734 TPoint* point = &(*pVecIt);
4735 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4736 getShapePoints( shapeID ).push_back( point );
4737 // detect key-points
4738 if ( SMESH_Block::IsVertexID( shapeID ))
4739 myKeyPointIDs.push_back( i );
4743 myIsBoundaryPointsFound = true;
4744 return myIsBoundaryPointsFound;
4747 //=======================================================================
4749 //purpose : clear fields
4750 //=======================================================================
4752 void SMESH_Pattern::Clear()
4754 myIsComputed = myIsBoundaryPointsFound = false;
4757 myKeyPointIDs.clear();
4758 myElemPointIDs.clear();
4759 myShapeIDToPointsMap.clear();
4760 myShapeIDMap.Clear();
4762 myNbKeyPntInBoundary.clear();
4765 myElemXYZIDs.clear();
4766 myXYZIdToNodeMap.clear();
4768 myOrderedNodes.clear();
4769 myPolyElems.clear();
4770 myPolyElemXYZIDs.clear();
4771 myPolyhedronQuantities.clear();
4772 myIdsOnBoundary.clear();
4773 myReverseConnectivity.clear();
4776 //================================================================================
4778 * \brief set ErrorCode and return true if it is Ok
4780 //================================================================================
4782 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4784 myErrorCode = theErrorCode;
4785 return myErrorCode == ERR_OK;
4788 //=======================================================================
4789 //function : setShapeToMesh
4790 //purpose : set a shape to be meshed. Return True if meshing is possible
4791 //=======================================================================
4793 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4795 if ( !IsLoaded() ) {
4796 MESSAGE( "Pattern not loaded" );
4797 return setErrorCode( ERR_APPL_NOT_LOADED );
4800 TopAbs_ShapeEnum aType = theShape.ShapeType();
4801 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4803 MESSAGE( "Pattern dimension mismatch" );
4804 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4807 // check if a face is closed
4808 int nbNodeOnSeamEdge = 0;
4810 TopTools_MapOfShape seamVertices;
4811 TopoDS_Face face = TopoDS::Face( theShape );
4812 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4813 for ( ; eExp.More() /*&& nbNodeOnSeamEdge == 0*/; eExp.Next() ) {
4814 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4815 if ( BRep_Tool::IsClosed(ee, face) ) {
4816 // seam edge and vertices encounter twice in theFace
4817 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4818 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4823 // check nb of vertices
4824 TopTools_IndexedMapOfShape vMap;
4825 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4826 if ( vMap.Extent() + nbNodeOnSeamEdge != (int)myKeyPointIDs.size() ) {
4827 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4828 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4831 myElements.clear(); // not refine elements
4832 myElemXYZIDs.clear();
4834 myShapeIDMap.Clear();
4839 //=======================================================================
4840 //function : GetMappedPoints
4841 //purpose : Return nodes coordinates computed by Apply() method
4842 //=======================================================================
4844 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4847 if ( !myIsComputed )
4850 if ( myElements.empty() ) { // applied to shape
4851 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4852 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4853 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4855 else { // applied to mesh elements
4856 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4857 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4858 for ( ; xyz != myXYZ.end(); ++xyz )
4859 if ( !isDefined( *xyz ))
4860 thePoints.push_back( definedXYZ );
4862 thePoints.push_back( & (*xyz) );
4864 return !thePoints.empty();
4868 //=======================================================================
4869 //function : GetPoints
4870 //purpose : Return nodes coordinates of the pattern
4871 //=======================================================================
4873 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4880 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4881 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4882 thePoints.push_back( & (*pVecIt).myInitXYZ );
4884 return ( thePoints.size() > 0 );
4887 //=======================================================================
4888 //function : getShapePoints
4889 //purpose : return list of points located on theShape
4890 //=======================================================================
4892 list< SMESH_Pattern::TPoint* > &
4893 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4896 if ( !myShapeIDMap.Contains( theShape ))
4897 aShapeID = myShapeIDMap.Add( theShape );
4899 aShapeID = myShapeIDMap.FindIndex( theShape );
4901 return myShapeIDToPointsMap[ aShapeID ];
4904 //=======================================================================
4905 //function : getShapePoints
4906 //purpose : return list of points located on the shape
4907 //=======================================================================
4909 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4911 return myShapeIDToPointsMap[ theShapeID ];
4914 //=======================================================================
4915 //function : DumpPoints
4917 //=======================================================================
4919 void SMESH_Pattern::DumpPoints() const
4922 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4923 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4924 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4928 //=======================================================================
4929 //function : TPoint()
4931 //=======================================================================
4933 SMESH_Pattern::TPoint::TPoint()
4936 myInitXYZ.SetCoord(0,0,0);
4937 myInitUV.SetCoord(0.,0.);
4939 myXYZ.SetCoord(0,0,0);
4940 myUV.SetCoord(0.,0.);
4945 //=======================================================================
4946 //function : operator <<
4948 //=======================================================================
4950 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4952 gp_XYZ xyz = p.myInitXYZ;
4953 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4954 gp_XY xy = p.myInitUV;
4955 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4956 double u = p.myInitU;
4957 OS << " u( " << u << " )) " << &p << endl;
4958 xyz = p.myXYZ.XYZ();
4959 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4961 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4963 OS << " u( " << u << " ))" << endl;