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 if ( theProject || needProject )
606 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
609 TNodePointIDMap nodePointIDMap;
610 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
614 // ---------------------------------------------------------------
615 // The case where the submesh is projected to theFace
616 // ---------------------------------------------------------------
619 SMDS_ElemIteratorPtr fIt;
621 fIt = fSubMesh->GetElements();
623 fIt = aMeshDS->elementsIterator( SMDSAbs_Face );
625 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
626 while ( fIt->more() )
628 const SMDS_MeshElement* face = fIt->next();
629 myElemPointIDs.push_back( TElemDef() );
630 TElemDef& elemPoints = myElemPointIDs.back();
631 int nbNodes = face->NbCornerNodes();
632 for ( int i = 0;i < nbNodes; ++i )
634 const SMDS_MeshElement* node = face->GetNode( i );
635 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
636 if ( nIdIt->second == -1 )
637 nIdIt->second = iPoint++;
638 elemPoints.push_back( (*nIdIt).second );
641 myPoints.resize( iPoint );
643 // project all nodes of 2d elements to theFace
644 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
645 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
647 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
648 TPoint * p = & myPoints[ (*nIdIt).second ];
649 p->myInitUV = project( node, projector );
650 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
652 // find key-points: the points most close to UV of vertices
653 TopExp_Explorer vExp( face, TopAbs_VERTEX );
654 set<int> foundIndices;
655 for ( ; vExp.More(); vExp.Next() ) {
656 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
657 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
658 double minDist = DBL_MAX;
660 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
661 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
662 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
663 if ( dist < minDist ) {
668 if ( foundIndices.insert( index ).second ) // unique?
669 myKeyPointIDs.push_back( index );
671 myIsBoundaryPointsFound = false;
676 // ---------------------------------------------------------------------
677 // The case where a pattern is being made from the mesh built by mesher
678 // ---------------------------------------------------------------------
680 // Load shapes in the consequent order and count nb of points
682 loadVE( eList, myShapeIDMap );
683 myShapeIDMap.Add( face );
685 nbNodes += myShapeIDMap.Extent() - 1;
687 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
688 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
689 nbNodes += eSubMesh->NbNodes() + 1;
691 myPoints.resize( nbNodes );
693 // Load U of points on edges
695 list<int>::iterator nbEinW = myNbKeyPntInBoundary.begin();
697 vector< TopoDS_Edge > eVec;
698 for ( elIt = eList.begin(); elIt != eList.end(); elIt++, iE++ )
700 if ( isClosed && ( iE == 0 || iE == *nbEinW ))
702 // new wire begins; put wire EDGEs in eVec
703 list<TopoDS_Edge>::iterator eEnd = elIt;
706 std::advance( eEnd, *nbEinW );
707 eVec.assign( elIt, eEnd );
710 TopoDS_Edge & edge = *elIt;
711 list< TPoint* > & ePoints = getShapePoints( edge );
713 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
714 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
716 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
717 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
718 // to make adjacent edges share key-point, we make v2 FORWARD too
719 // (as we have different points for same shape with different orientation)
722 // on closed face we must have REVERSED some of seam vertices
724 if ( helper.IsSeamShape( edge ) ) {
725 if ( helper.IsRealSeam( edge ) && !isForward ) {
726 // reverse on reversed SEAM edge
731 else { // on CLOSED edge (i.e. having one vertex with different orientations)
732 for ( int is2 = 0; is2 < 2; ++is2 ) {
733 TopoDS_Shape & v = is2 ? v2 : v1;
734 if ( helper.IsRealSeam( v ) ) {
735 // reverse or not depending on orientation of adjacent seam
736 int iSeam = helper.WrapIndex( iE + ( is2 ? +1 : -1 ), eVec.size() );
737 if ( eVec[ iSeam ].Orientation() == TopAbs_REVERSED )
744 // the forward key-point
745 list< TPoint* > * vPoint = & getShapePoints( v1 );
746 if ( vPoint->empty() )
748 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
749 if ( vSubMesh && vSubMesh->NbNodes() ) {
750 myKeyPointIDs.push_back( iPoint );
751 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
752 const SMDS_MeshNode* node = nIt->next();
753 if ( v1.Orientation() == TopAbs_REVERSED )
754 closeNodePointIDMap.insert( make_pair( node, iPoint ));
756 nodePointIDMap.insert( make_pair( node, iPoint ));
758 TPoint* keyPoint = &myPoints[ iPoint++ ];
759 vPoint->push_back( keyPoint );
761 keyPoint->myInitUV = project( node, projector );
763 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
764 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
767 if ( !vPoint->empty() )
768 ePoints.push_back( vPoint->front() );
771 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
772 if ( eSubMesh && eSubMesh->NbNodes() )
774 // loop on nodes of an edge: sort them by param on edge
775 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
776 TParamNodeMap paramNodeMap;
777 int nbMeduimNodes = 0;
778 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
779 while ( nIt->more() )
781 const SMDS_MeshNode* node = nIt->next();
782 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
786 const SMDS_EdgePosition* epos =
787 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
788 double u = epos->GetUParameter();
789 paramNodeMap.insert( make_pair( u, node ));
791 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes ) {
792 // wrong U on edge, project
794 BRepAdaptor_Curve aCurve( edge );
795 proj.Initialize( aCurve, f, l );
796 paramNodeMap.clear();
797 nIt = eSubMesh->GetNodes();
798 for ( int iNode = 0; nIt->more(); ++iNode ) {
799 const SMDS_MeshNode* node = nIt->next();
800 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
802 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
804 if ( proj.IsDone() ) {
805 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
806 if ( proj.IsMin( i )) {
807 u = proj.Point( i ).Parameter();
811 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
813 paramNodeMap.insert( make_pair( u, node ));
816 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
817 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
818 return setErrorCode(ERR_UNEXPECTED);
821 // put U in [0,1] so that the first key-point has U==0
822 bool isSeam = helper.IsRealSeam( edge );
824 TParamNodeMap::iterator unIt = paramNodeMap.begin();
825 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
826 while ( unIt != paramNodeMap.end() )
828 TPoint* p = & myPoints[ iPoint ];
829 ePoints.push_back( p );
830 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
831 if ( isSeam && !isForward )
832 closeNodePointIDMap.insert( make_pair( node, iPoint ));
834 nodePointIDMap.insert ( make_pair( node, iPoint ));
837 p->myInitUV = project( node, projector );
839 double u = isForward ? (*unIt).first : (*unRIt).first;
840 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
841 p->myInitUV = C2d->Value( u ).XY();
843 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
848 // the reverse key-point
849 vPoint = & getShapePoints( v2 );
850 if ( vPoint->empty() )
852 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
853 if ( vSubMesh && vSubMesh->NbNodes() ) {
854 myKeyPointIDs.push_back( iPoint );
855 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
856 const SMDS_MeshNode* node = nIt->next();
857 if ( v2.Orientation() == TopAbs_REVERSED )
858 closeNodePointIDMap.insert( make_pair( node, iPoint ));
860 nodePointIDMap.insert( make_pair( node, iPoint ));
862 TPoint* keyPoint = &myPoints[ iPoint++ ];
863 vPoint->push_back( keyPoint );
865 keyPoint->myInitUV = project( node, projector );
867 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
868 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
871 if ( !vPoint->empty() )
872 ePoints.push_back( vPoint->front() );
874 // compute U of edge-points
877 double totalDist = 0;
878 list< TPoint* >::iterator pIt = ePoints.begin();
879 TPoint* prevP = *pIt;
880 prevP->myInitU = totalDist;
881 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
883 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
884 p->myInitU = totalDist;
887 if ( totalDist > DBL_MIN)
888 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
890 p->myInitU /= totalDist;
893 } // loop on edges of a wire
895 // Load in-face points and elements
897 if ( fSubMesh && fSubMesh->NbElements() )
899 list< TPoint* > & fPoints = getShapePoints( face );
900 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
901 while ( nIt->more() )
903 const SMDS_MeshNode* node = nIt->next();
904 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
906 nodePointIDMap.insert( make_pair( node, iPoint ));
907 TPoint* p = &myPoints[ iPoint++ ];
908 fPoints.push_back( p );
910 p->myInitUV = project( node, projector );
912 const SMDS_FacePosition* pos =
913 static_cast<const SMDS_FacePosition*>(node->GetPosition());
914 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
916 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
919 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
920 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
921 while ( elemIt->more() )
923 const SMDS_MeshElement* elem = elemIt->next();
924 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
925 myElemPointIDs.push_back( TElemDef() );
926 TElemDef& elemPoints = myElemPointIDs.back();
927 // find point indices corresponding to element nodes
928 while ( nIt->more() )
930 const SMDS_MeshNode* node = smdsNode( nIt->next() );
931 n_id = nodePointIDMap.find( node );
932 if ( n_id == nodePointIDMap.end() )
933 continue; // medium node
934 iPoint = n_id->second; // point index of interest
935 // for a node on a seam edge there are two points
936 if ( helper.IsRealSeam( node->getshapeId() ) &&
937 ( n_id = closeNodePointIDMap.find( node )) != not_found )
939 TPoint & p1 = myPoints[ iPoint ];
940 TPoint & p2 = myPoints[ n_id->second ];
941 // Select point closest to the rest nodes of element in UV space
942 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
943 const SMDS_MeshNode* notSeamNode = 0;
944 // find node not on a seam edge
945 while ( nIt2->more() && !notSeamNode ) {
946 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
947 if ( !helper.IsSeamShape( n->getshapeId() ))
950 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
951 double dist1 = uv.SquareDistance( p1.myInitUV );
952 double dist2 = uv.SquareDistance( p2.myInitUV );
954 iPoint = n_id->second;
956 elemPoints.push_back( iPoint );
960 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
962 myIsBoundaryPointsFound = true;
967 myInNodes.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
969 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
970 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
971 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
973 nIdIt = closeNodePointIDMap.begin();
974 for ( ; nIdIt != closeNodePointIDMap.end(); nIdIt++ )
975 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
978 // Assure that U range is proportional to V range
981 vector< TPoint >::iterator pVecIt = myPoints.begin();
982 for ( ; pVecIt != myPoints.end(); pVecIt++ )
983 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
984 double minU, minV, maxU, maxV;
985 bndBox.Get( minU, minV, maxU, maxV );
986 double dU = maxU - minU, dV = maxV - minV;
987 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
990 // define where is the problem, in the face or in the mesh
991 TopExp_Explorer vExp( face, TopAbs_VERTEX );
992 for ( ; vExp.More(); vExp.Next() ) {
993 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
996 bndBox.Get( minU, minV, maxU, maxV );
997 dU = maxU - minU, dV = maxV - minV;
998 if ( dU <= DBL_MIN || dV <= DBL_MIN )
1000 return setErrorCode( ERR_LOADF_NARROW_FACE );
1002 // mesh is projected onto a line, e.g.
1003 return setErrorCode( ERR_LOADF_CANT_PROJECT );
1005 double ratio = dU / dV, maxratio = 3, scale;
1007 if ( ratio > maxratio ) {
1008 scale = ratio / maxratio;
1011 else if ( ratio < 1./maxratio ) {
1012 scale = maxratio / ratio;
1017 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
1018 TPoint & p = *pVecIt;
1019 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
1020 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
1023 if ( myElemPointIDs.empty() ) {
1024 MESSAGE( "No elements bound to the face");
1025 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
1028 return setErrorCode( ERR_OK );
1031 //=======================================================================
1032 //function : computeUVOnEdge
1033 //purpose : compute coordinates of points on theEdge
1034 //=======================================================================
1036 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
1037 const list< TPoint* > & ePoints )
1039 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
1041 Handle(Geom2d_Curve) C2d =
1042 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1044 ePoints.back()->myInitU = 1.0;
1045 //ePoints.front()->myInitU = 0.0; //myUV = C2d->Value( isForward ? f : l ).XY();
1046 list< TPoint* >::const_iterator pIt = ePoints.begin();
1047 for ( pIt++; pIt != ePoints.end(); pIt++ )
1049 TPoint* point = *pIt;
1051 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1052 point->myU = ( f * ( 1 - du ) + l * du );
1054 point->myUV = C2d->Value( point->myU ).XY();
1058 //=======================================================================
1059 //function : intersectIsolines
1061 //=======================================================================
1063 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1064 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1068 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1069 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1070 resUV = 0.5 * ( loc1 + loc2 );
1071 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1072 // SKL 26.07.2007 for NPAL16567
1073 double d1 = (uv11-uv12).Modulus();
1074 double d2 = (uv21-uv22).Modulus();
1075 // double delta = d1*d2*1e-6; PAL17233
1076 double delta = min( d1, d2 ) / 10.;
1077 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1079 // double len1 = ( uv11 - uv12 ).Modulus();
1080 // double len2 = ( uv21 - uv22 ).Modulus();
1081 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1085 // gp_Lin2d line1( uv11, uv12 - uv11 );
1086 // gp_Lin2d line2( uv21, uv22 - uv21 );
1087 // double angle = Abs( line1.Angle( line2 ) );
1089 // IntAna2d_AnaIntersection inter;
1090 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1091 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1093 // gp_Pnt2d interUV = inter.Point(1).Value();
1094 // resUV += interUV.XY();
1095 // inter.Perform( line1, line2 );
1096 // interUV = inter.Point(1).Value();
1097 // resUV += interUV.XY();
1101 // if ( isDeformed ) {
1102 // MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1103 // ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1108 //=======================================================================
1109 //function : compUVByIsoIntersection
1111 //=======================================================================
1113 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1114 const gp_XY& theInitUV,
1116 bool & theIsDeformed )
1118 // compute UV by intersection of 2 iso lines
1119 //gp_Lin2d isoLine[2];
1120 gp_XY uv1[2], uv2[2];
1122 const double zero = DBL_MIN;
1123 for ( int iIso = 0; iIso < 2; iIso++ )
1125 // to build an iso line:
1126 // find 2 pairs of consequent edge-points such that the range of their
1127 // initial parameters encloses the in-face point initial parameter
1128 gp_XY UV[2], initUV[2];
1129 int nbUV = 0, iCoord = iIso + 1;
1130 double initParam = theInitUV.Coord( iCoord );
1132 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1133 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1135 const list< TPoint* > & bndPoints = * bndIt;
1136 TPoint* prevP = bndPoints.back(); // this is the first point
1137 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1138 bool coincPrev = false;
1139 // loop on the edge-points
1140 for ( ; pIt != bndPoints.end(); pIt++ )
1142 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1143 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1144 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1145 if (!coincPrev && // ignore if initParam coincides with prev point param
1146 sumOfDiff > zero && // ignore if both points coincide with initParam
1147 prevParamDiff * paramDiff <= zero )
1149 // find UV in parametric space of theFace
1150 double r = Abs(prevParamDiff) / sumOfDiff;
1151 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1154 // throw away uv most distant from <theInitUV>
1155 gp_XY vec0 = initUV[0] - theInitUV;
1156 gp_XY vec1 = initUV[1] - theInitUV;
1157 gp_XY vec = uvInit - theInitUV;
1158 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1159 double dist0 = vec0.SquareModulus();
1160 double dist1 = vec1.SquareModulus();
1161 double dist = vec .SquareModulus();
1162 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1163 i = ( dist0 < dist1 ? 1 : 0 );
1164 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1165 i = 3; // theInitUV must remain between
1169 initUV[ i ] = uvInit;
1170 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1172 coincPrev = ( Abs(paramDiff) <= zero );
1179 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1180 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1181 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1182 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1184 // an iso line should be normal to UV[0] - UV[1] direction
1185 // and be located at the same relative distance as from initial ends
1186 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1188 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1189 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1190 //isoLine[ iIso ] = iso.Normal( isoLoc );
1191 uv1[ iIso ] = UV[0];
1192 uv2[ iIso ] = UV[1];
1195 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1196 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1197 MESSAGE(" Can't intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1198 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1205 // ==========================================================
1206 // structure representing a node of a grid of iso-poly-lines
1207 // ==========================================================
1214 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1215 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1216 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1217 TIsoNode(double initU, double initV):
1218 myIsMovable(true), myInitUV( initU, initV ), myUV( 1e100, 1e100 )
1219 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1220 bool IsUVComputed() const
1221 { return myUV.X() != 1e100; }
1222 bool IsMovable() const
1223 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1224 void SetNotMovable()
1225 { myIsMovable = false; }
1226 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1227 { myBndNodes[ iDir + i * 2 ] = node; }
1228 TIsoNode* GetBoundaryNode(int iDir, int i)
1229 { return myBndNodes[ iDir + i * 2 ]; }
1230 void SetNext(TIsoNode* node, int iDir, int isForward)
1231 { myNext[ iDir + isForward * 2 ] = node; }
1232 TIsoNode* GetNext(int iDir, int isForward)
1233 { return myNext[ iDir + isForward * 2 ]; }
1236 //=======================================================================
1237 //function : getNextNode
1239 //=======================================================================
1241 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1243 TIsoNode* n = node->myNext[ dir ];
1244 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1245 n = 0;//node->myBndNodes[ dir ];
1246 // MESSAGE("getNextNode: use bnd for node "<<
1247 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1251 //=======================================================================
1252 //function : checkQuads
1253 //purpose : check if newUV destortes quadrangles around node,
1254 // and if ( crit == FIX_OLD ) fix newUV in this case
1255 //=======================================================================
1257 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1259 static bool checkQuads (const TIsoNode* node,
1261 const bool reversed,
1262 const int crit = FIX_OLD,
1263 double fixSize = 0.)
1265 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1266 int nbOldFix = 0, nbOldImpr = 0;
1267 double newBadRate = 0, oldBadRate = 0;
1268 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1269 int i, dir1 = 0, dir2 = 3;
1270 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1272 if ( dir2 > 3 ) dir2 = 0;
1274 // walking counterclockwise around a quad,
1275 // nodes are in the order: node, n[0], n[1], n[2]
1276 n[0] = getNextNode( node, dir1 );
1277 n[2] = getNextNode( node, dir2 );
1278 if ( !n[0] || !n[2] ) continue;
1279 n[1] = getNextNode( n[0], dir2 );
1280 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1281 bool isTriangle = ( !n[1] );
1283 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1285 // if ( fixSize != 0 ) {
1286 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1287 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1288 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1289 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1291 // check if a quadrangle is degenerated
1293 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1294 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1297 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1300 // find min size of the diagonal node-n[1]
1301 double minDiag = fixSize;
1302 if ( minDiag == 0. ) {
1303 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1304 if ( !isTriangle ) {
1305 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1306 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1308 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1309 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1312 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1313 // ( behind means "to the right of")
1315 // 1. newUV is not behind 01 and 12 dirs
1316 // 2. or newUV is not behind 02 dir and n[2] is convex
1317 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1318 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1319 gp_Vec2d moveVec[3], outVec[3];
1320 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1322 bool isDiag = ( i == 2 );
1323 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1327 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1329 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1331 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1333 gp_Vec2d newDir( n[i]->myUV, newUV );
1334 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1336 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1337 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1338 if ( crit == FIX_OLD ) {
1339 wasIn[i] = ( outDir * oldDir < 0 );
1340 wasOk[i] = ( outDir * oldDir < -minDiag );
1342 newBadRate += outDir * newDir;
1344 oldBadRate += outDir * oldDir;
1347 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1348 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1349 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1350 moveVec[i] = ( oldDist - minDiag ) * outDir;
1355 // check if n[2] is convex
1358 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1360 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1361 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1362 newIsOk = ( newIsOk && isNewOk );
1363 newIsIn = ( newIsIn && isNewIn );
1365 if ( crit != FIX_OLD ) {
1366 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1367 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1371 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1372 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1373 oldIsIn = ( oldIsIn && isOldIn );
1374 oldIsOk = ( oldIsOk && isOldIn );
1377 if ( !isOldIn ) { // node is outside a quadrangle
1378 // move newUV inside a quadrangle
1379 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1380 // node and newUV are outside: push newUV inside
1382 if ( convex || isTriangle ) {
1383 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1386 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1387 double outSize = out.Magnitude();
1388 if ( outSize > DBL_MIN )
1391 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1392 uv = n[1]->myUV - minDiag * out.XY();
1394 oldUVFixed[ nbOldFix++ ] = uv;
1395 //node->myUV = newUV;
1397 else if ( !isOldOk ) {
1398 // try to fix old UV: move node inside as less as possible
1399 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1400 gp_XY uv1, uv2 = node->myUV;
1401 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1403 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1404 while ( !isOldOk ) {
1405 // find the least moveVec
1407 double minMove2 = 1e100;
1408 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1410 if ( moveVec[i].Coord(1) < 1e100 ) {
1411 double move2 = moveVec[i].SquareMagnitude();
1412 if ( move2 < minMove2 ) {
1421 // move node to newUV
1422 uv1 = node->myUV + moveVec[ iMin ].XY();
1423 uv2 += moveVec[ iMin ].XY();
1424 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1425 // check if uv1 is ok
1426 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1427 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1428 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1430 oldUVImpr[ nbOldImpr++ ] = uv1;
1432 // check if uv2 is ok
1433 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1434 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1435 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1437 oldUVImpr[ nbOldImpr++ ] = uv2;
1442 } // loop on 4 quadrangles around <node>
1444 if ( crit == CHECK_NEW_OK )
1446 if ( crit == CHECK_NEW_IN )
1455 if ( oldIsIn && nbOldImpr ) {
1456 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1457 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1458 gp_XY uv = oldUVImpr[ 0 ];
1459 for ( int i = 1; i < nbOldImpr; i++ )
1460 uv += oldUVImpr[ i ];
1462 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1467 //MESSAGE(" Can't improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1470 if ( !oldIsIn && nbOldFix ) {
1471 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1472 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1473 gp_XY uv = oldUVFixed[ 0 ];
1474 for ( int i = 1; i < nbOldFix; i++ )
1475 uv += oldUVFixed[ i ];
1477 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1482 //MESSAGE(" Can't fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1485 if ( newIsIn && oldIsIn )
1486 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1487 else if ( !newIsIn )
1494 //=======================================================================
1495 //function : compUVByElasticIsolines
1496 //purpose : compute UV as nodes of iso-poly-lines consisting of
1497 // segments keeping relative size as in the pattern
1498 //=======================================================================
1499 //#define DEB_COMPUVBYELASTICISOLINES
1500 bool SMESH_Pattern::
1501 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1502 const list< TPoint* >& thePntToCompute)
1504 return false; // PAL17233
1505 //cout << "============================== KEY POINTS =============================="<<endl;
1506 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1507 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1508 // TPoint& p = myPoints[ *kpIt ];
1509 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1510 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1512 //cout << "=============================="<<endl;
1514 // Define parameters of iso-grid nodes in U and V dir
1516 set< double > paramSet[ 2 ];
1517 list< list< TPoint* > >::const_iterator pListIt;
1518 list< TPoint* >::const_iterator pIt;
1519 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1520 const list< TPoint* > & pList = * pListIt;
1521 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1522 paramSet[0].insert( (*pIt)->myInitUV.X() );
1523 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1526 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1527 paramSet[0].insert( (*pIt)->myInitUV.X() );
1528 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1530 // unite close parameters and split too long segments
1533 for ( iDir = 0; iDir < 2; iDir++ )
1535 set< double > & params = paramSet[ iDir ];
1536 double range = ( *params.rbegin() - *params.begin() );
1537 double toler = range / 1e6;
1538 tol[ iDir ] = toler;
1539 // double maxSegment = range / params.size() / 2.;
1541 // set< double >::iterator parIt = params.begin();
1542 // double prevPar = *parIt;
1543 // for ( parIt++; parIt != params.end(); parIt++ )
1545 // double segLen = (*parIt) - prevPar;
1546 // if ( segLen < toler )
1547 // ;//params.erase( prevPar ); // unite
1548 // else if ( segLen > maxSegment )
1549 // params.insert( prevPar + 0.5 * segLen ); // split
1550 // prevPar = (*parIt);
1554 // Make nodes of a grid of iso-poly-lines
1556 list < TIsoNode > nodes;
1557 typedef list < TIsoNode *> TIsoLine;
1558 map < double, TIsoLine > isoMap[ 2 ];
1560 set< double > & params0 = paramSet[ 0 ];
1561 set< double >::iterator par0It = params0.begin();
1562 for ( ; par0It != params0.end(); par0It++ )
1564 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1565 set< double > & params1 = paramSet[ 1 ];
1566 set< double >::iterator par1It = params1.begin();
1567 for ( ; par1It != params1.end(); par1It++ )
1569 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1570 isoLine0.push_back( & nodes.back() );
1571 isoMap[1][ *par1It ].push_back( & nodes.back() );
1575 // Compute intersections of boundaries with iso-lines:
1576 // only boundary nodes will have computed UV so far
1579 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1580 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1581 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1583 const list< TPoint* > & bndPoints = * bndIt;
1584 TPoint* prevP = bndPoints.back(); // this is the first point
1585 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1586 // loop on the edge-points
1587 for ( ; pIt != bndPoints.end(); pIt++ )
1589 TPoint* point = *pIt;
1590 for ( iDir = 0; iDir < 2; iDir++ )
1592 const int iCoord = iDir + 1;
1593 const int iOtherCoord = 2 - iDir;
1594 double par1 = prevP->myInitUV.Coord( iCoord );
1595 double par2 = point->myInitUV.Coord( iCoord );
1596 double parDif = par2 - par1;
1597 if ( Abs( parDif ) <= DBL_MIN )
1599 // find iso-lines intersecting a bounadry
1600 double toler = tol[ 1 - iDir ];
1601 double minPar = Min ( par1, par2 );
1602 double maxPar = Max ( par1, par2 );
1603 map < double, TIsoLine >& isos = isoMap[ iDir ];
1604 map < double, TIsoLine >::iterator isoIt = isos.begin();
1605 for ( ; isoIt != isos.end(); isoIt++ )
1607 double isoParam = (*isoIt).first;
1608 if ( isoParam < minPar || isoParam > maxPar )
1610 double r = ( isoParam - par1 ) / parDif;
1611 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1612 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1613 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1614 // find existing node with otherPar or insert a new one
1615 TIsoLine & isoLine = (*isoIt).second;
1617 TIsoLine::iterator nIt = isoLine.begin();
1618 for ( ; nIt != isoLine.end(); nIt++ ) {
1619 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1620 if ( nodePar >= otherPar )
1624 if ( Abs( nodePar - otherPar ) <= toler )
1625 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1627 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1628 node = & nodes.back();
1629 isoLine.insert( nIt, node );
1631 node->SetNotMovable();
1633 uvBnd.Add( gp_Pnt2d( uv ));
1634 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1636 gp_XY tgt( point->myUV - prevP->myUV );
1637 if ( ::IsEqual( r, 1. ))
1638 node->myDir[ 0 ] = tgt;
1639 else if ( ::IsEqual( r, 0. ))
1640 node->myDir[ 1 ] = tgt;
1642 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1643 // keep boundary nodes corresponding to boundary points
1644 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1645 if ( bndNodes.empty() || bndNodes.back() != node )
1646 bndNodes.push_back( node );
1647 } // loop on isolines
1648 } // loop on 2 directions
1650 } // loop on boundary points
1651 } // loop on boundaries
1653 // Define orientation
1655 // find the point with the least X
1656 double leastX = DBL_MAX;
1657 TIsoNode * leftNode;
1658 list < TIsoNode >::iterator nodeIt = nodes.begin();
1659 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1660 TIsoNode & node = *nodeIt;
1661 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1662 leastX = node.myUV.X();
1665 // if ( node.IsUVComputed() ) {
1666 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1667 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1668 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1669 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1672 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1673 //SCRUTE( reversed );
1675 // Prepare internal nodes:
1677 // 2. compute ratios
1678 // 3. find boundary nodes for each node
1679 // 4. remove nodes out of the boundary
1680 for ( iDir = 0; iDir < 2; iDir++ )
1682 const int iCoord = 2 - iDir; // coord changing along an isoline
1683 map < double, TIsoLine >& isos = isoMap[ iDir ];
1684 map < double, TIsoLine >::iterator isoIt = isos.begin();
1685 for ( ; isoIt != isos.end(); isoIt++ )
1687 TIsoLine & isoLine = (*isoIt).second;
1688 bool firstCompNodeFound = false;
1689 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1690 nPrevIt = nIt = nNextIt = isoLine.begin();
1692 nNextIt++; nNextIt++;
1693 while ( nIt != isoLine.end() )
1695 // 1. connect prev - cur
1696 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1697 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1698 firstCompNodeFound = true;
1699 lastCompNodePos = nPrevIt;
1701 if ( firstCompNodeFound ) {
1702 node->SetNext( prevNode, iDir, 0 );
1703 prevNode->SetNext( node, iDir, 1 );
1706 if ( nNextIt != isoLine.end() ) {
1707 double par1 = prevNode->myInitUV.Coord( iCoord );
1708 double par2 = node->myInitUV.Coord( iCoord );
1709 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1710 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1712 // 3. find boundary nodes
1713 if ( node->IsUVComputed() )
1714 lastCompNodePos = nIt;
1715 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1716 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1717 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1718 if ( (*nIt2)->IsUVComputed() )
1720 if ( nIt2 != isoLine.end() ) {
1722 node->SetBoundaryNode( bndNode1, iDir, 0 );
1723 node->SetBoundaryNode( bndNode2, iDir, 1 );
1724 // cout << "--------------------------------------------------"<<endl;
1725 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1726 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1727 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1728 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1729 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1730 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1733 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1734 node->SetBoundaryNode( 0, iDir, 0 );
1735 node->SetBoundaryNode( 0, iDir, 1 );
1739 if ( nNextIt != isoLine.end() ) nNextIt++;
1740 // 4. remove nodes out of the boundary
1741 if ( !firstCompNodeFound )
1742 isoLine.pop_front();
1743 } // loop on isoLine nodes
1745 // remove nodes after the boundary
1746 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1747 // (*nIt)->SetNotMovable();
1748 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1749 } // loop on isolines
1750 } // loop on 2 directions
1752 // Compute local isoline direction for internal nodes
1755 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1756 map < double, TIsoLine >::iterator isoIt = isos.begin();
1757 for ( ; isoIt != isos.end(); isoIt++ )
1759 TIsoLine & isoLine = (*isoIt).second;
1760 TIsoLine::iterator nIt = isoLine.begin();
1761 for ( ; nIt != isoLine.end(); nIt++ )
1763 TIsoNode* node = *nIt;
1764 if ( node->IsUVComputed() || !node->IsMovable() )
1766 gp_Vec2d aTgt[2], aNorm[2];
1769 for ( iDir = 0; iDir < 2; iDir++ )
1771 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1772 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1773 if ( !bndNode1 || !bndNode2 ) {
1777 const int iCoord = 2 - iDir; // coord changing along an isoline
1778 double par1 = bndNode1->myInitUV.Coord( iCoord );
1779 double par2 = node->myInitUV.Coord( iCoord );
1780 double par3 = bndNode2->myInitUV.Coord( iCoord );
1781 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1783 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1784 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1785 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1786 else tgt1.Reverse();
1787 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1789 if ( ratio[ iDir ] < 0.5 )
1790 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1792 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1794 aNorm[ iDir ].Reverse(); // along iDir isoline
1796 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1797 // maybe angle is more than |PI|
1798 if ( Abs( angle ) > PI / 2. ) {
1799 // check direction of the last but one perpendicular isoline
1800 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1801 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1802 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1803 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1804 if ( isoDir * tgt2 < 0 )
1806 double angle2 = tgt1.Angle( isoDir );
1807 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1808 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1809 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1810 //MESSAGE("REVERSE ANGLE");
1813 if ( Abs( angle2 ) > Abs( angle ) ||
1814 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1815 //MESSAGE("Add PI");
1816 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1817 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1818 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1819 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1820 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1821 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1824 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1828 for ( iDir = 0; iDir < 2; iDir++ )
1830 aTgt[iDir].Normalize();
1831 aNorm[1-iDir].Normalize();
1832 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1835 node->myDir[iDir] = //aTgt[iDir];
1836 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1838 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1839 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1840 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1841 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1843 } // loop on iso nodes
1844 } // loop on isolines
1846 // Find nodes to start computing UV from
1848 list< TIsoNode* > startNodes;
1849 list< TIsoNode* >::iterator nIt = bndNodes.end();
1850 TIsoNode* node = *(--nIt);
1851 TIsoNode* prevNode = *(--nIt);
1852 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1854 TIsoNode* nextNode = *nIt;
1855 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1856 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1857 double initAngle = initTgt1.Angle( initTgt2 );
1858 double angle = node->myDir[0].Angle( node->myDir[1] );
1859 if ( reversed ) angle = -angle;
1860 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1861 // find a close internal node
1862 TIsoNode* nClose = 0;
1863 list< TIsoNode* > testNodes;
1864 testNodes.push_back( node );
1865 list< TIsoNode* >::iterator it = testNodes.begin();
1866 for ( ; !nClose && it != testNodes.end(); it++ )
1868 for (int i = 0; i < 4; i++ )
1870 nClose = (*it)->myNext[ i ];
1872 if ( !nClose->IsUVComputed() )
1875 testNodes.push_back( nClose );
1881 startNodes.push_back( nClose );
1882 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1883 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1884 // "initAngle: " << initAngle << " angle: " << angle << endl;
1885 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1886 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1887 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1888 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1894 // Compute starting UV of internal nodes
1896 list < TIsoNode* > internNodes;
1897 bool needIteration = true;
1898 if ( startNodes.empty() ) {
1899 //MESSAGE( " Starting UV by compUVByIsoIntersection()");
1900 needIteration = false;
1901 map < double, TIsoLine >& isos = isoMap[ 0 ];
1902 map < double, TIsoLine >::iterator isoIt = isos.begin();
1903 for ( ; isoIt != isos.end(); isoIt++ )
1905 TIsoLine & isoLine = (*isoIt).second;
1906 TIsoLine::iterator nIt = isoLine.begin();
1907 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1909 TIsoNode* node = *nIt;
1910 if ( !node->IsUVComputed() && node->IsMovable() ) {
1911 internNodes.push_back( node );
1913 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1914 node->myUV, needIteration ))
1915 node->myUV = node->myInitUV;
1919 if ( needIteration )
1920 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1922 TIsoNode* node = *nIt, *nClose = 0;
1923 list< TIsoNode* > testNodes;
1924 testNodes.push_back( node );
1925 list< TIsoNode* >::iterator it = testNodes.begin();
1926 for ( ; !nClose && it != testNodes.end(); it++ )
1928 for (int i = 0; i < 4; i++ )
1930 nClose = (*it)->myNext[ i ];
1932 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1935 testNodes.push_back( nClose );
1941 startNodes.push_back( nClose );
1945 double aMin[2], aMax[2], step[2];
1946 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1947 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1948 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1949 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1950 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1952 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1954 TIsoNode *node = *nIt;
1955 if ( node->IsUVComputed() || !node->IsMovable() )
1957 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1958 int nbComp = 0, nbPrev = 0;
1959 for ( iDir = 0; iDir < 2; iDir++ )
1961 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1962 TIsoNode* n = node->GetNext( iDir, 0 );
1963 if ( n->IsUVComputed() )
1966 startNodes.push_back( n );
1967 n = node->GetNext( iDir, 1 );
1968 if ( n->IsUVComputed() )
1971 startNodes.push_back( n );
1973 prevNode1 = prevNode2;
1976 if ( prevNode1 ) nbPrev++;
1977 if ( prevNode2 ) nbPrev++;
1980 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1981 double par = node->myInitUV.Coord( 2 - iDir );
1982 bool isEnd = ( prevPar > par );
1983 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1984 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1985 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1987 MESSAGE("Why we are here?");
1990 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1991 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1992 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1993 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1994 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1995 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
1996 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
1997 //" par: " << prevPar << endl;
1998 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
1999 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
2001 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2002 gp_XY & uv1 = prevNode1->myUV;
2003 gp_XY & uv2 = prevNode2->myUV;
2004 // dir = ( uv2 - uv1 );
2005 // double len = dir.Modulus();
2006 // if ( len > DBL_MIN )
2007 // dir /= len * 0.5;
2008 double r = node->myRatio[ iDir ];
2009 newUV += uv1 * ( 1 - r ) + uv2 * r;
2012 newUV += prevNode1->myUV + dir * step[ iDir ];
2018 if ( !nbComp ) continue;
2021 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2023 // check if a quadrangle is not distorted
2025 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
2026 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
2027 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
2028 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
2032 internNodes.push_back( node );
2037 static int maxNbIter = 100;
2038 #ifdef DEB_COMPUVBYELASTICISOLINES
2040 bool useNbMoveNode = 0;
2041 static int maxNbNodeMove = 100;
2044 if ( !useNbMoveNode )
2045 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2050 if ( !needIteration) break;
2051 #ifdef DEB_COMPUVBYELASTICISOLINES
2052 if ( nbIter >= maxNbIter ) break;
2055 list < TIsoNode* >::iterator nIt = internNodes.begin();
2056 for ( ; nIt != internNodes.end(); nIt++ ) {
2057 #ifdef DEB_COMPUVBYELASTICISOLINES
2059 cout << nbNodeMove <<" =================================================="<<endl;
2061 TIsoNode * node = *nIt;
2065 for ( iDir = 0; iDir < 2; iDir++ )
2067 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2068 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2069 double r = node->myRatio[ iDir ];
2070 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2071 // line[ iDir ].SetLocation( loc[ iDir ] );
2072 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2075 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2076 // double locR[2] = { 0, 0 };
2077 for ( iDir = 0; iDir < 2; iDir++ )
2079 const int iCoord = 2 - iDir; // coord changing along an isoline
2080 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2081 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2082 if ( !bndNode1 || !bndNode2 ) {
2085 double par1 = bndNode1->myInitUV.Coord( iCoord );
2086 double par2 = node->myInitUV.Coord( iCoord );
2087 double par3 = bndNode2->myInitUV.Coord( iCoord );
2088 double r = ( par2 - par1 ) / ( par3 - par1 );
2089 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2090 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2092 //locR[0] = locR[1] = 0.25;
2093 // intersect the 2 lines and move a node
2094 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2095 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2097 // double intR = 1 - locR[0] - locR[1];
2098 // gp_XY newUV = inter.Point(1).Value().XY();
2099 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2100 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2102 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2103 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2104 // avoid parallel isolines intersection
2105 checkQuads( node, newUV, reversed );
2107 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2109 } // intersection found
2110 #ifdef DEB_COMPUVBYELASTICISOLINES
2111 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2113 } // loop on internal nodes
2114 #ifdef DEB_COMPUVBYELASTICISOLINES
2115 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2117 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2119 //MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2121 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2122 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2123 #ifndef DEB_COMPUVBYELASTICISOLINES
2128 // Set computed UV to points
2130 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2131 TPoint* point = *pIt;
2132 //gp_XY oldUV = point->myUV;
2133 double minDist = DBL_MAX;
2134 list < TIsoNode >::iterator nIt = nodes.begin();
2135 for ( ; nIt != nodes.end(); nIt++ ) {
2136 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2137 if ( dist < minDist ) {
2139 point->myUV = (*nIt).myUV;
2148 //=======================================================================
2149 //function : setFirstEdge
2150 //purpose : choose the best first edge of theWire; return the summary distance
2151 // between point UV computed by isolines intersection and
2152 // eventual UV got from edge p-curves
2153 //=======================================================================
2155 //#define DBG_SETFIRSTEDGE
2156 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2158 int iE, nbEdges = theWire.size();
2162 // Transform UVs computed by iso to fit bnd box of a wire
2164 // max nb of points on an edge
2166 int eID = theFirstEdgeID;
2167 for ( iE = 0; iE < nbEdges; iE++ )
2168 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2170 // compute bnd boxes
2171 TopoDS_Face face = TopoDS::Face( myShape );
2172 Bnd_Box2d bndBox, eBndBox;
2173 eID = theFirstEdgeID;
2174 list< TopoDS_Edge >::iterator eIt;
2175 list< TPoint* >::iterator pIt;
2176 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2178 // UV by isos stored in TPoint.myXYZ
2179 list< TPoint* > & ePoints = getShapePoints( eID++ );
2180 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2182 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2184 // UV by an edge p-curve
2186 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2187 double dU = ( l - f ) / ( maxNbPnt - 1 );
2188 for ( int i = 0; i < maxNbPnt; i++ )
2189 eBndBox.Add( C2d->Value( f + i * dU ));
2192 // transform UVs by isos
2193 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2194 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2195 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2196 #ifdef DBG_SETFIRSTEDGE
2197 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2198 << eMinPar[1] << " - " << eMaxPar[1] );
2200 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2202 double dMin = eMinPar[i] - minPar[i];
2203 double dMax = eMaxPar[i] - maxPar[i];
2204 double dPar = maxPar[i] - minPar[i];
2205 eID = theFirstEdgeID;
2206 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2208 list< TPoint* > & ePoints = getShapePoints( eID++ );
2209 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2211 double par = (*pIt)->myXYZ.Coord( iC );
2212 double r = ( par - minPar[i] ) / dPar;
2213 par += ( 1 - r ) * dMin + r * dMax;
2214 (*pIt)->myXYZ.SetCoord( iC, par );
2220 double minDist = DBL_MAX;
2221 for ( iE = 0 ; iE < nbEdges; iE++ )
2223 #ifdef DBG_SETFIRSTEDGE
2224 MESSAGE ( " VARIANT " << iE );
2226 // evaluate the distance between UV computed by the 2 methods:
2227 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2229 int eID = theFirstEdgeID;
2230 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2232 list< TPoint* > & ePoints = getShapePoints( eID++ );
2233 computeUVOnEdge( *eIt, ePoints );
2234 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2236 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2237 #ifdef DBG_SETFIRSTEDGE
2238 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2239 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2243 #ifdef DBG_SETFIRSTEDGE
2244 MESSAGE ( "dist -- " << dist );
2246 if ( dist < minDist ) {
2248 eBest = theWire.front();
2250 // check variant with another first edge
2251 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2253 // put the best first edge to the theWire front
2254 if ( eBest != theWire.front() ) {
2255 eIt = find ( theWire.begin(), theWire.end(), eBest );
2256 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2262 //=======================================================================
2263 //function : sortSameSizeWires
2264 //purpose : sort wires in theWireList from theFromWire until theToWire,
2265 // the wires are set in the order to correspond to the order
2266 // of boundaries; after sorting, edges in the wires are put
2267 // in a good order, point UVs on edges are computed and points
2268 // are appended to theEdgesPointsList
2269 //=======================================================================
2271 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2272 const TListOfEdgesList::iterator& theFromWire,
2273 const TListOfEdgesList::iterator& theToWire,
2274 const int theFirstEdgeID,
2275 list< list< TPoint* > >& theEdgesPointsList )
2277 TopoDS_Face F = TopoDS::Face( myShape );
2278 int iW, nbWires = 0;
2279 TListOfEdgesList::iterator wlIt = theFromWire;
2280 while ( wlIt++ != theToWire )
2283 // Recompute key-point UVs by isolines intersection,
2284 // compute CG of key-points for each wire and bnd boxes of GCs
2287 gp_XY orig( gp::Origin2d().XY() );
2288 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2289 Bnd_Box2d bndBox, vBndBox;
2290 int eID = theFirstEdgeID;
2291 list< TopoDS_Edge >::iterator eIt;
2292 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2294 list< TopoDS_Edge > & wire = *wlIt;
2295 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2297 list< TPoint* > & ePoints = getShapePoints( eID++ );
2298 TPoint* p = ePoints.front();
2299 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2300 MESSAGE("can't sortSameSizeWires()");
2303 gcVec[iW] += p->myUV;
2304 bndBox.Add( gp_Pnt2d( p->myUV ));
2305 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2306 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2307 vGcVec[iW] += vXY.XY();
2309 // keep the computed UV to compare against by setFirstEdge()
2310 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2312 gcVec[iW] /= nbWires;
2313 vGcVec[iW] /= nbWires;
2314 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2315 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2318 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2320 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2321 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2322 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2323 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2325 double dMin = vMinPar[i] - minPar[i];
2326 double dMax = vMaxPar[i] - maxPar[i];
2327 double dPar = maxPar[i] - minPar[i];
2328 if ( Abs( dPar ) <= DBL_MIN )
2330 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2331 double par = gcVec[iW].Coord( iC );
2332 double r = ( par - minPar[i] ) / dPar;
2333 par += ( 1 - r ) * dMin + r * dMax;
2334 gcVec[iW].SetCoord( iC, par );
2338 // Define boundary - wire correspondence by GC closeness
2340 TListOfEdgesList tmpWList;
2341 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2342 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2343 TIntWirePosMap bndIndWirePosMap;
2344 vector< bool > bndFound( nbWires, false );
2345 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2347 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2348 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2349 double minDist = DBL_MAX;
2350 gp_XY & wGc = vGcVec[ iW ];
2352 for ( int iB = 0; iB < nbWires; iB++ ) {
2353 if ( bndFound[ iB ] ) continue;
2354 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2355 if ( dist < minDist ) {
2360 bndFound[ bIndex ] = true;
2361 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2366 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2367 eID = theFirstEdgeID;
2368 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2370 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2371 list < TopoDS_Edge > & wire = ( *wirePos );
2373 // choose the best first edge of a wire
2374 setFirstEdge( wire, eID );
2376 // compute eventual UV and fill theEdgesPointsList
2377 theEdgesPointsList.push_back( list< TPoint* >() );
2378 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2379 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2381 list< TPoint* > & ePoints = getShapePoints( eID++ );
2382 computeUVOnEdge( *eIt, ePoints );
2383 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2385 // put wire back to theWireList
2387 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2393 //=======================================================================
2395 //purpose : Compute nodes coordinates applying
2396 // the loaded pattern to <theFace>. The first key-point
2397 // will be mapped into <theVertexOnKeyPoint1>
2398 //=======================================================================
2400 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2401 const TopoDS_Vertex& theVertexOnKeyPoint1,
2402 const bool theReverse)
2404 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2405 if ( !setShapeToMesh( face ))
2408 // find points on edges, it fills myNbKeyPntInBoundary
2409 if ( !findBoundaryPoints() )
2412 // Define the edges order so that the first edge starts at
2413 // theVertexOnKeyPoint1
2415 list< TopoDS_Edge > eList;
2416 list< int > nbVertexInWires;
2417 int nbWires = SMESH_Block::GetOrderedEdges( face, eList, nbVertexInWires, theVertexOnKeyPoint1);
2418 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2420 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2421 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2423 // check nb wires and edges
2424 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2425 l1.sort(); l2.sort();
2428 MESSAGE( "Wrong nb vertices in wires" );
2429 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2432 // here shapes get IDs, for the outer wire IDs are OK
2433 int nbVertices = loadVE( eList, myShapeIDMap );
2434 myShapeIDMap.Add( face );
2436 if ((int) myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2437 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2438 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2441 // points on edges to be used for UV computation of in-face points
2442 list< list< TPoint* > > edgesPointsList;
2443 edgesPointsList.push_back( list< TPoint* >() );
2444 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2445 list< TPoint* >::iterator pIt, pEnd;
2447 // compute UV of points on the outer wire
2448 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2449 list< TopoDS_Edge >::iterator elIt;
2450 for (iE = 0, elIt = eList.begin();
2451 iE < nbEdgesInOuterWire && elIt != eList.end();
2454 list< TPoint* > & ePoints = getShapePoints( *elIt );
2456 computeUVOnEdge( *elIt, ePoints );
2457 // collect on-edge points (excluding the last one)
2458 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2461 // If there are several wires, define the order of edges of inner wires:
2462 // compute UV of inner edge-points using 2 methods: the one for in-face points
2463 // and the one for on-edge points and then choose the best edge order
2464 // by the best correspondance of the 2 results
2467 // compute UV of inner edge-points using the method for in-face points
2468 // and divide eList into a list of separate wires
2470 list< list< TopoDS_Edge > > wireList;
2471 list<TopoDS_Edge>::iterator eIt = elIt;
2472 list<int>::iterator nbEIt = nbVertexInWires.begin();
2473 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2475 int nbEdges = *nbEIt;
2476 wireList.push_back( list< TopoDS_Edge >() );
2477 list< TopoDS_Edge > & wire = wireList.back();
2478 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2480 list< TPoint* > & ePoints = getShapePoints( *eIt );
2481 pIt = ePoints.begin();
2482 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2484 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2485 MESSAGE("can't Apply(face)");
2488 // keep the computed UV to compare against by setFirstEdge()
2489 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2491 wire.push_back( *eIt );
2494 // remove inner edges from eList
2495 eList.erase( elIt, eList.end() );
2497 // sort wireList by nb edges in a wire
2498 sortBySize< TopoDS_Edge > ( wireList );
2500 // an ID of the first edge of a boundary
2501 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2502 // if ( nbSeamShapes > 0 )
2503 // id1 += 2; // 2 vertices more
2505 // find points - edge correspondence for wires of unique size,
2506 // edge order within a wire should be defined only
2508 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2509 while ( wlIt != wireList.end() )
2511 list< TopoDS_Edge >& wire = (*wlIt);
2512 size_t nbEdges = wire.size();
2514 if ( wlIt != wireList.end() && (*wlIt).size() != nbEdges ) // a unique size wire
2516 // choose the best first edge of a wire
2517 setFirstEdge( wire, id1 );
2519 // compute eventual UV and collect on-edge points
2520 edgesPointsList.push_back( list< TPoint* >() );
2521 edgesPoints = & edgesPointsList.back();
2523 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2525 list< TPoint* > & ePoints = getShapePoints( eID++ );
2526 computeUVOnEdge( *eIt, ePoints );
2527 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2533 // find boundary - wire correspondence for several wires of same size
2535 id1 = nbVertices + nbEdgesInOuterWire + 1;
2536 wlIt = wireList.begin();
2537 while ( wlIt != wireList.end() )
2539 size_t nbSameSize = 0, nbEdges = (*wlIt).size();
2540 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2542 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2546 if ( nbSameSize > 0 )
2547 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2550 id1 += nbEdges * ( nbSameSize + 1 );
2553 // add well-ordered edges to eList
2555 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2557 list< TopoDS_Edge >& wire = (*wlIt);
2558 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2561 // re-fill myShapeIDMap - all shapes get good IDs
2563 myShapeIDMap.Clear();
2564 nbVertices = loadVE( eList, myShapeIDMap );
2565 myShapeIDMap.Add( face );
2567 } // there are inner wires
2569 // Set XYZ of on-vertex points
2571 // for ( int iV = 1; iV <= nbVertices; ++iV )
2573 // const TopoDS_Vertex& V = TopoDS::Vertex( myShapeIDMap( iV ));
2574 // list< TPoint* > & vPoints = getShapePoints( iV );
2575 // if ( !vPoints.empty() )
2577 // //vPoints.front()->myUV = BRep_Tool::Parameters( V, theFace ).XY();
2578 // vPoints.front()->myXYZ = BRep_Tool::Pnt( V );
2582 // Compute XYZ of on-edge points
2584 TopLoc_Location loc;
2585 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2587 BRepAdaptor_Curve C3d( *elIt );
2588 list< TPoint* > & ePoints = getShapePoints( iE++ );
2589 for ( pIt = ++ePoints.begin(), pEnd = ePoints.end(); pIt != pEnd; pIt++ )
2591 TPoint* point = *pIt;
2592 point->myXYZ = C3d.Value( point->myU );
2596 // Compute UV and XYZ of in-face points
2598 // try to use a simple algo
2599 list< TPoint* > & fPoints = getShapePoints( face );
2600 bool isDeformed = false;
2601 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2602 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2603 (*pIt)->myUV, isDeformed )) {
2604 MESSAGE("can't Apply(face)");
2607 // try to use a complex algo if it is a difficult case
2608 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2610 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2611 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2612 (*pIt)->myUV, isDeformed )) {
2613 MESSAGE("can't Apply(face)");
2618 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2619 const gp_Trsf & aTrsf = loc.Transformation();
2620 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2622 TPoint * point = *pIt;
2623 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2624 if ( !loc.IsIdentity() )
2625 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2628 myIsComputed = true;
2630 return setErrorCode( ERR_OK );
2633 //=======================================================================
2635 //purpose : Compute nodes coordinates applying
2636 // the loaded pattern to <theFace>. The first key-point
2637 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2638 //=======================================================================
2640 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2641 const int theNodeIndexOnKeyPoint1,
2642 const bool theReverse)
2644 // MESSAGE(" ::Apply(MeshFace) " );
2646 if ( !IsLoaded() ) {
2647 MESSAGE( "Pattern not loaded" );
2648 return setErrorCode( ERR_APPL_NOT_LOADED );
2651 // check nb of nodes
2652 const int nbFaceNodes = theFace->NbCornerNodes();
2653 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2654 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2655 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2658 // find points on edges, it fills myNbKeyPntInBoundary
2659 if ( !findBoundaryPoints() )
2662 // check that there are no holes in a pattern
2663 if (myNbKeyPntInBoundary.size() > 1 ) {
2664 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2667 // Define the nodes order
2669 list< const SMDS_MeshNode* > nodes;
2670 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2671 SMDS_NodeIteratorPtr noIt = theFace->nodeIterator();
2673 while ( noIt->more() && iSub < nbFaceNodes ) {
2674 const SMDS_MeshNode* node = noIt->next();
2675 nodes.push_back( node );
2676 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2679 if ( n != nodes.end() ) {
2681 if ( n != --nodes.end() )
2682 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2685 else if ( n != nodes.begin() )
2686 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2688 list< gp_XYZ > xyzList;
2689 myOrderedNodes.resize( nbFaceNodes );
2690 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2691 xyzList.push_back( SMESH_TNodeXYZ( *n ));
2692 myOrderedNodes[ iSub++] = *n;
2695 // Define a face plane
2697 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2698 gp_Pnt P ( *xyzIt++ );
2699 gp_Vec Vx( P, *xyzIt++ ), N;
2701 N = Vx ^ gp_Vec( P, *xyzIt++ );
2702 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2703 if ( N.SquareMagnitude() <= DBL_MIN )
2704 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2705 gp_Ax2 pos( P, N, Vx );
2707 // Compute UV of key-points on a plane
2708 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2710 gp_Vec vec ( pos.Location(), *xyzIt );
2711 TPoint* p = getShapePoints( iSub ).front();
2712 p->myUV.SetX( vec * pos.XDirection() );
2713 p->myUV.SetY( vec * pos.YDirection() );
2717 // points on edges to be used for UV computation of in-face points
2718 list< list< TPoint* > > edgesPointsList;
2719 edgesPointsList.push_back( list< TPoint* >() );
2720 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2721 list< TPoint* >::iterator pIt;
2723 // compute UV and XYZ of points on edges
2725 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2727 gp_XYZ& xyz1 = *xyzIt++;
2728 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2730 list< TPoint* > & ePoints = getShapePoints( iSub );
2731 ePoints.back()->myInitU = 1.0;
2732 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2733 while ( *pIt != ePoints.back() )
2736 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2737 gp_Vec vec ( pos.Location(), p->myXYZ );
2738 p->myUV.SetX( vec * pos.XDirection() );
2739 p->myUV.SetY( vec * pos.YDirection() );
2741 // collect on-edge points (excluding the last one)
2742 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2745 // Compute UV and XYZ of in-face points
2747 // try to use a simple algo to compute UV
2748 list< TPoint* > & fPoints = getShapePoints( iSub );
2749 bool isDeformed = false;
2750 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2751 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2752 (*pIt)->myUV, isDeformed )) {
2753 MESSAGE("can't Apply(face)");
2756 // try to use a complex algo if it is a difficult case
2757 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2759 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2760 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2761 (*pIt)->myUV, isDeformed )) {
2762 MESSAGE("can't Apply(face)");
2767 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2769 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2772 myIsComputed = true;
2774 return setErrorCode( ERR_OK );
2777 //=======================================================================
2779 //purpose : Compute nodes coordinates applying
2780 // the loaded pattern to <theFace>. The first key-point
2781 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2782 //=======================================================================
2784 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2785 const SMDS_MeshFace* theFace,
2786 const TopoDS_Shape& theSurface,
2787 const int theNodeIndexOnKeyPoint1,
2788 const bool theReverse)
2790 // MESSAGE(" ::Apply(MeshFace) " );
2791 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2792 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2794 const TopoDS_Face& face = TopoDS::Face( theSurface );
2795 TopLoc_Location loc;
2796 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2797 const gp_Trsf & aTrsf = loc.Transformation();
2799 if ( !IsLoaded() ) {
2800 MESSAGE( "Pattern not loaded" );
2801 return setErrorCode( ERR_APPL_NOT_LOADED );
2804 // check nb of nodes
2805 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2806 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2807 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2810 // find points on edges, it fills myNbKeyPntInBoundary
2811 if ( !findBoundaryPoints() )
2814 // check that there are no holes in a pattern
2815 if (myNbKeyPntInBoundary.size() > 1 ) {
2816 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2819 // Define the nodes order
2821 list< const SMDS_MeshNode* > nodes;
2822 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2823 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2825 while ( noIt->more() ) {
2826 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2827 nodes.push_back( node );
2828 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2831 if ( n != nodes.end() ) {
2833 if ( n != --nodes.end() )
2834 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2837 else if ( n != nodes.begin() )
2838 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2841 // find a node not on a seam edge, if necessary
2842 SMESH_MesherHelper helper( *theMesh );
2843 helper.SetSubShape( theSurface );
2844 const SMDS_MeshNode* inFaceNode = 0;
2845 if ( helper.GetNodeUVneedInFaceNode() )
2847 SMESH_MeshEditor editor( theMesh );
2848 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2849 int shapeID = editor.FindShape( *n );
2851 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2852 if ( !helper.IsSeamShape( shapeID ))
2857 // Set UV of key-points (i.e. of nodes of theFace )
2858 vector< gp_XY > keyUV( theFace->NbNodes() );
2859 myOrderedNodes.resize( theFace->NbNodes() );
2860 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2862 TPoint* p = getShapePoints( iSub ).front();
2863 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2864 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2866 keyUV[ iSub-1 ] = p->myUV;
2867 myOrderedNodes[ iSub-1 ] = *n;
2870 // points on edges to be used for UV computation of in-face points
2871 list< list< TPoint* > > edgesPointsList;
2872 edgesPointsList.push_back( list< TPoint* >() );
2873 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2874 list< TPoint* >::iterator pIt;
2876 // compute UV and XYZ of points on edges
2878 for ( size_t i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2880 gp_XY& uv1 = keyUV[ i ];
2881 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2883 list< TPoint* > & ePoints = getShapePoints( iSub );
2884 ePoints.back()->myInitU = 1.0;
2885 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2886 while ( *pIt != ePoints.back() )
2889 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2890 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2891 if ( !loc.IsIdentity() )
2892 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2894 // collect on-edge points (excluding the last one)
2895 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2898 // Compute UV and XYZ of in-face points
2900 // try to use a simple algo to compute UV
2901 list< TPoint* > & fPoints = getShapePoints( iSub );
2902 bool isDeformed = false;
2903 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2904 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2905 (*pIt)->myUV, isDeformed )) {
2906 MESSAGE("can't Apply(face)");
2909 // try to use a complex algo if it is a difficult case
2910 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2912 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2913 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2914 (*pIt)->myUV, isDeformed )) {
2915 MESSAGE("can't Apply(face)");
2920 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2922 TPoint * point = *pIt;
2923 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2924 if ( !loc.IsIdentity() )
2925 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2928 myIsComputed = true;
2930 return setErrorCode( ERR_OK );
2933 //=======================================================================
2934 //function : undefinedXYZ
2936 //=======================================================================
2938 static const gp_XYZ& undefinedXYZ()
2940 static gp_XYZ xyz( 1.e100, 0., 0. );
2944 //=======================================================================
2945 //function : isDefined
2947 //=======================================================================
2949 inline static bool isDefined(const gp_XYZ& theXYZ)
2951 return theXYZ.X() < 1.e100;
2954 //=======================================================================
2956 //purpose : Compute nodes coordinates applying
2957 // the loaded pattern to <theFaces>. The first key-point
2958 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2959 //=======================================================================
2961 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2962 std::set<const SMDS_MeshFace*>& theFaces,
2963 const int theNodeIndexOnKeyPoint1,
2964 const bool theReverse)
2966 MESSAGE(" ::Apply(set<MeshFace>) " );
2968 if ( !IsLoaded() ) {
2969 MESSAGE( "Pattern not loaded" );
2970 return setErrorCode( ERR_APPL_NOT_LOADED );
2973 // find points on edges, it fills myNbKeyPntInBoundary
2974 if ( !findBoundaryPoints() )
2977 // check that there are no holes in a pattern
2978 if (myNbKeyPntInBoundary.size() > 1 ) {
2979 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2984 myElemXYZIDs.clear();
2985 myXYZIdToNodeMap.clear();
2987 myIdsOnBoundary.clear();
2988 myReverseConnectivity.clear();
2990 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2991 myElements.reserve( theFaces.size() );
2993 int ind1 = 0; // lowest point index for a face
2998 // SMESH_MeshEditor editor( theMesh );
3000 // apply to each face in theFaces set
3001 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
3002 for ( ; face != theFaces.end(); ++face )
3004 // int curShapeId = editor.FindShape( *face );
3005 // if ( curShapeId != shapeID ) {
3006 // if ( curShapeId )
3007 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
3010 // shapeID = curShapeId;
3013 if ( shape.IsNull() )
3014 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
3016 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
3018 MESSAGE( "Failed on " << *face );
3021 myElements.push_back( *face );
3023 // store computed points belonging to elements
3024 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3025 for ( ; ll != myElemPointIDs.end(); ++ll )
3027 myElemXYZIDs.push_back(TElemDef());
3028 TElemDef& xyzIds = myElemXYZIDs.back();
3029 TElemDef& pIds = *ll;
3030 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3031 int pIndex = *id + ind1;
3032 xyzIds.push_back( pIndex );
3033 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3034 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3037 // put points on links to myIdsOnBoundary,
3038 // they will be used to sew new elements on adjacent refined elements
3039 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3040 for ( int i = 0; i < nbNodes; i++ )
3042 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3043 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3044 const SMDS_MeshNode* n2 = myOrderedNodes[( i+1 ) % nbNodes ];
3045 // make a link and a node set
3046 TNodeSet linkSet, node1Set;
3047 linkSet.insert( n1 );
3048 linkSet.insert( n2 );
3049 node1Set.insert( n1 );
3050 list< TPoint* >::iterator p = linkPoints.begin();
3052 // map the first link point to n1
3053 int nId = ( *p - &myPoints[0] ) + ind1;
3054 myXYZIdToNodeMap[ nId ] = n1;
3055 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3056 groups.push_back(list< int > ());
3057 groups.back().push_back( nId );
3059 // add the linkSet to the map
3060 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3061 groups.push_back(list< int > ());
3062 list< int >& indList = groups.back();
3063 // add points to the map excluding the end points
3064 for ( p++; *p != linkPoints.back(); p++ )
3065 indList.push_back( ( *p - &myPoints[0] ) + ind1 );
3067 ind1 += myPoints.size();
3070 return !myElemXYZIDs.empty();
3073 //=======================================================================
3075 //purpose : Compute nodes coordinates applying
3076 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3077 // will be mapped into <theNode000Index>-th node. The
3078 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3080 //=======================================================================
3082 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3083 const int theNode000Index,
3084 const int theNode001Index)
3086 if ( !IsLoaded() ) {
3087 MESSAGE( "Pattern not loaded" );
3088 return setErrorCode( ERR_APPL_NOT_LOADED );
3091 // bind ID to points
3092 if ( !findBoundaryPoints() )
3095 // check that there are no holes in a pattern
3096 if (myNbKeyPntInBoundary.size() > 1 ) {
3097 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3102 myElemXYZIDs.clear();
3103 myXYZIdToNodeMap.clear();
3105 myIdsOnBoundary.clear();
3106 myReverseConnectivity.clear();
3108 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3109 myElements.reserve( theVolumes.size() );
3111 // to find point index
3112 map< TPoint*, int > pointIndex;
3113 for ( size_t i = 0; i < myPoints.size(); i++ )
3114 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3116 int ind1 = 0; // lowest point index for an element
3118 // apply to each element in theVolumes set
3119 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3120 for ( ; vol != theVolumes.end(); ++vol )
3122 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3123 MESSAGE( "Failed on " << *vol );
3126 myElements.push_back( *vol );
3128 // store computed points belonging to elements
3129 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3130 for ( ; ll != myElemPointIDs.end(); ++ll )
3132 myElemXYZIDs.push_back(TElemDef());
3133 TElemDef& xyzIds = myElemXYZIDs.back();
3134 TElemDef& pIds = *ll;
3135 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3136 int pIndex = *id + ind1;
3137 xyzIds.push_back( pIndex );
3138 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3139 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3142 // put points on edges and faces to myIdsOnBoundary,
3143 // they will be used to sew new elements on adjacent refined elements
3144 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3146 // make a set of sub-points
3148 vector< int > subIDs;
3149 if ( SMESH_Block::IsVertexID( Id )) {
3150 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3152 else if ( SMESH_Block::IsEdgeID( Id )) {
3153 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3154 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3155 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3158 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3159 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3160 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3161 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3162 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3163 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3164 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3165 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3168 list< TPoint* > & points = getShapePoints( Id );
3169 list< TPoint* >::iterator p = points.begin();
3170 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3171 groups.push_back(list< int > ());
3172 list< int >& indList = groups.back();
3173 for ( ; p != points.end(); p++ )
3174 indList.push_back( pointIndex[ *p ] + ind1 );
3175 if ( subNodes.size() == 1 ) // vertex case
3176 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3178 ind1 += myPoints.size();
3181 return !myElemXYZIDs.empty();
3184 //=======================================================================
3186 //purpose : Create a pattern from the mesh built on <theBlock>
3187 //=======================================================================
3189 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3190 const TopoDS_Shell& theBlock,
3195 myToKeepNodes = theKeepNodes;
3196 SMESHDS_SubMesh * aSubMesh;
3198 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3200 // load shapes in myShapeIDMap
3202 TopoDS_Vertex v1, v2;
3203 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3204 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3207 int nbNodes = 0, shapeID;
3208 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3210 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3211 aSubMesh = getSubmeshWithElements( theMesh, S );
3213 nbNodes += aSubMesh->NbNodes();
3215 myPoints.resize( nbNodes );
3217 // load U of points on edges
3218 TNodePointIDMap nodePointIDMap;
3220 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3222 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3223 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3224 aSubMesh = getSubmeshWithElements( theMesh, S );
3225 if ( ! aSubMesh ) continue;
3226 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3227 if ( !nIt->more() ) continue;
3229 // store a node and a point
3230 while ( nIt->more() ) {
3231 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3232 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3234 nodePointIDMap.insert( make_pair( node, iPoint ));
3235 if ( block.IsVertexID( shapeID ))
3236 myKeyPointIDs.push_back( iPoint );
3237 TPoint* p = & myPoints[ iPoint++ ];
3238 shapePoints.push_back( p );
3239 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3240 p->myInitXYZ.SetCoord( 0,0,0 );
3242 list< TPoint* >::iterator pIt = shapePoints.begin();
3245 switch ( S.ShapeType() )
3250 for ( ; pIt != shapePoints.end(); pIt++ ) {
3251 double * coef = block.GetShapeCoef( shapeID );
3252 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3253 if ( coef[ iCoord - 1] > 0 )
3254 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3256 if ( S.ShapeType() == TopAbs_VERTEX )
3259 const TopoDS_Edge& edge = TopoDS::Edge( S );
3261 BRep_Tool::Range( edge, f, l );
3262 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3263 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3264 pIt = shapePoints.begin();
3265 nIt = aSubMesh->GetNodes();
3266 for ( ; nIt->more(); pIt++ )
3268 const SMDS_MeshNode* node = nIt->next();
3269 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3271 const SMDS_EdgePosition* epos =
3272 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3273 double u = ( epos->GetUParameter() - f ) / ( l - f );
3274 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3279 for ( ; pIt != shapePoints.end(); pIt++ )
3281 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3282 MESSAGE( "!block.ComputeParameters()" );
3283 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3287 } // loop on block sub-shapes
3291 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3294 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3295 while ( elemIt->more() ) {
3296 const SMDS_MeshElement* elem = elemIt->next();
3297 myElemPointIDs.push_back( TElemDef() );
3298 TElemDef& elemPoints = myElemPointIDs.back();
3299 int nbNodes = elem->NbCornerNodes();
3300 for ( int i = 0;i < nbNodes; ++i )
3301 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3305 myIsBoundaryPointsFound = true;
3307 if ( myToKeepNodes )
3309 myInNodes.resize( nodePointIDMap.size() );
3310 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
3311 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
3312 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
3315 return setErrorCode( ERR_OK );
3318 //=======================================================================
3319 //function : getSubmeshWithElements
3320 //purpose : return submesh containing elements bound to theBlock in theMesh
3321 //=======================================================================
3323 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3324 const TopoDS_Shape& theShape)
3326 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3327 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3330 if ( theShape.ShapeType() == TopAbs_SHELL )
3332 // look for submesh of VOLUME
3333 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3334 for (; it.More(); it.Next()) {
3335 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3336 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3344 //=======================================================================
3346 //purpose : Compute nodes coordinates applying
3347 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3348 // will be mapped into <theVertex000>. The (0,0,1)
3349 // fifth key-point will be mapped into <theVertex001>.
3350 //=======================================================================
3352 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3353 const TopoDS_Vertex& theVertex000,
3354 const TopoDS_Vertex& theVertex001)
3356 if (!findBoundaryPoints() || // bind ID to points
3357 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3360 SMESH_Block block; // bind ID to shape
3361 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3362 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3364 // compute XYZ of points on shapes
3366 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3368 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3369 list< TPoint* >::iterator pIt = shapePoints.begin();
3370 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3371 switch ( S.ShapeType() )
3373 case TopAbs_VERTEX: {
3375 for ( ; pIt != shapePoints.end(); pIt++ )
3376 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3381 for ( ; pIt != shapePoints.end(); pIt++ )
3382 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3387 for ( ; pIt != shapePoints.end(); pIt++ )
3388 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3392 for ( ; pIt != shapePoints.end(); pIt++ )
3393 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3395 } // loop on block sub-shapes
3397 myIsComputed = true;
3399 return setErrorCode( ERR_OK );
3402 //=======================================================================
3404 //purpose : Compute nodes coordinates applying
3405 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3406 // will be mapped into <theNode000Index>-th node. The
3407 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3409 //=======================================================================
3411 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3412 const int theNode000Index,
3413 const int theNode001Index)
3415 if (!findBoundaryPoints()) // bind ID to points
3418 SMESH_Block block; // bind ID to shape
3419 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3420 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3421 // compute XYZ of points on shapes
3423 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3425 list< TPoint* > & shapePoints = getShapePoints( ID );
3426 list< TPoint* >::iterator pIt = shapePoints.begin();
3428 if ( block.IsVertexID( ID ))
3429 for ( ; pIt != shapePoints.end(); pIt++ ) {
3430 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3432 else if ( block.IsEdgeID( ID ))
3433 for ( ; pIt != shapePoints.end(); pIt++ ) {
3434 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3436 else if ( block.IsFaceID( ID ))
3437 for ( ; pIt != shapePoints.end(); pIt++ ) {
3438 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3441 for ( ; pIt != shapePoints.end(); pIt++ )
3442 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3443 } // loop on block sub-shapes
3445 myIsComputed = true;
3447 return setErrorCode( ERR_OK );
3450 //=======================================================================
3451 //function : mergePoints
3452 //purpose : Merge XYZ on edges and/or faces.
3453 //=======================================================================
3455 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3457 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3458 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3460 list<list< int > >& groups = idListIt->second;
3461 if ( groups.size() < 2 )
3465 const TNodeSet& nodes = idListIt->first;
3466 double tol2 = 1.e-10;
3467 if ( nodes.size() > 1 ) {
3469 TNodeSet::const_iterator n = nodes.begin();
3470 for ( ; n != nodes.end(); ++n )
3471 box.Add( gp_Pnt( SMESH_TNodeXYZ( *n )));
3472 double x, y, z, X, Y, Z;
3473 box.Get( x, y, z, X, Y, Z );
3474 gp_Pnt p( x, y, z ), P( X, Y, Z );
3475 tol2 = 1.e-4 * p.SquareDistance( P );
3478 // to unite groups on link
3479 bool unite = ( uniteGroups && nodes.size() == 2 );
3480 map< double, int > distIndMap;
3481 const SMDS_MeshNode* node = *nodes.begin();
3482 gp_Pnt P = SMESH_TNodeXYZ( node );
3484 // compare points, replace indices
3486 list< int >::iterator ind1, ind2;
3487 list< list< int > >::iterator grpIt1, grpIt2;
3488 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3490 list< int >& indices1 = *grpIt1;
3492 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3494 list< int >& indices2 = *grpIt2;
3495 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3497 gp_XYZ& p1 = myXYZ[ *ind1 ];
3498 ind2 = indices2.begin();
3499 while ( ind2 != indices2.end() )
3501 gp_XYZ& p2 = myXYZ[ *ind2 ];
3502 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3503 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3505 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3506 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3507 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3508 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3510 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3511 myXYZ[ *ind2 ] = undefinedXYZ();
3512 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3514 ind2 = indices2.erase( ind2 );
3521 if ( unite ) { // sort indices using distIndMap
3522 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3524 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3525 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3526 distIndMap.insert( make_pair( dist, *ind1 ));
3530 if ( unite ) { // put all sorted indices into the first group
3531 list< int >& g = groups.front();
3533 map< double, int >::iterator dist_ind = distIndMap.begin();
3534 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3535 g.push_back( dist_ind->second );
3537 } // loop on myIdsOnBoundary
3540 //=======================================================================
3541 //function : makePolyElements
3542 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3543 //=======================================================================
3545 void SMESH_Pattern::
3546 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3547 const bool toCreatePolygons,
3548 const bool toCreatePolyedrs)
3550 myPolyElemXYZIDs.clear();
3551 myPolyElems.clear();
3552 myPolyElems.reserve( myIdsOnBoundary.size() );
3554 // make a set of refined elements
3555 TIDSortedElemSet elemSet, avoidSet( myElements.begin(), myElements.end() );
3557 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3559 if ( toCreatePolygons )
3561 int lastFreeId = myXYZ.size();
3563 // loop on links of refined elements
3564 indListIt = myIdsOnBoundary.begin();
3565 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3567 const TNodeSet & linkNodes = indListIt->first;
3568 if ( linkNodes.size() != 2 )
3569 continue; // skip face
3570 const SMDS_MeshNode* n1 = * linkNodes.begin();
3571 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3573 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3574 if ( idGroups.empty() || idGroups.front().empty() )
3577 // find not refined face having n1-n2 link
3581 const SMDS_MeshElement* face =
3582 SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3585 avoidSet.insert ( face );
3586 myPolyElems.push_back( face );
3588 // some links of <face> are split;
3589 // make list of xyz for <face>
3590 myPolyElemXYZIDs.push_back(TElemDef());
3591 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3592 // loop on links of a <face>
3593 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3594 int i = 0, nbNodes = face->NbNodes();
3595 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3596 while ( nIt->more() )
3597 nodes[ i++ ] = smdsNode( nIt->next() );
3598 nodes[ i ] = nodes[ 0 ];
3599 for ( i = 0; i < nbNodes; ++i )
3601 // look for point mapped on a link
3602 TNodeSet faceLinkNodes;
3603 faceLinkNodes.insert( nodes[ i ] );
3604 faceLinkNodes.insert( nodes[ i + 1 ] );
3605 if ( faceLinkNodes == linkNodes )
3606 nn_IdList = indListIt;
3608 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3609 // add face point ids
3610 faceNodeIds.push_back( ++lastFreeId );
3611 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3612 if ( nn_IdList != myIdsOnBoundary.end() )
3614 // there are points mapped on a link
3615 list< int >& mappedIds = nn_IdList->second.front();
3616 if ( isReversed( nodes[ i ], mappedIds ))
3617 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3619 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3621 } // loop on links of a <face>
3627 if ( myIs2D && idGroups.size() > 1 ) {
3629 // sew new elements on 2 refined elements sharing n1-n2 link
3631 list< int >& idsOnLink = idGroups.front();
3632 // temporarily add ids of link nodes to idsOnLink
3633 bool rev = isReversed( n1, idsOnLink );
3634 for ( int i = 0; i < 2; ++i )
3637 nodeSet.insert( i ? n2 : n1 );
3638 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3639 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3640 int nodeId = groups.front().front();
3642 if ( rev ) append = !append;
3644 idsOnLink.push_back( nodeId );
3646 idsOnLink.push_front( nodeId );
3648 list< int >::iterator id = idsOnLink.begin();
3649 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3651 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3652 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3653 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3655 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3656 // look for <id> in element definition
3657 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3658 ASSERT ( idDef != pIdList->end() );
3659 // look for 2 neighbour ids of <id> in element definition
3660 for ( int prev = 0; prev < 2; ++prev ) {
3661 TElemDef::iterator idDef2 = idDef;
3663 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3665 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3666 // look for idDef2 on a link starting from id
3667 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3668 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3669 // insert ids located on link between <id> and <id2>
3670 // into the element definition between idDef and idDef2
3672 for ( ; id2 != id; --id2 )
3673 pIdList->insert( idDef, *id2 );
3675 list< int >::iterator id1 = id;
3676 for ( ++id1, ++id2; id1 != id2; ++id1 )
3677 pIdList->insert( idDef2, *id1 );
3683 // remove ids of link nodes
3684 idsOnLink.pop_front();
3685 idsOnLink.pop_back();
3687 } // loop on myIdsOnBoundary
3688 } // if ( toCreatePolygons )
3690 if ( toCreatePolyedrs )
3692 // check volumes adjacent to the refined elements
3693 SMDS_VolumeTool volTool;
3694 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3695 for ( ; refinedElem != myElements.end(); ++refinedElem )
3697 // loop on nodes of refinedElem
3698 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3699 while ( nIt->more() ) {
3700 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3701 // loop on inverse elements of node
3702 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3703 while ( eIt->more() )
3705 const SMDS_MeshElement* elem = eIt->next();
3706 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3707 continue; // skip faces or refined elements
3708 // add polyhedron definition
3709 myPolyhedronQuantities.push_back(vector<int> ());
3710 myPolyElemXYZIDs.push_back(TElemDef());
3711 vector<int>& quantity = myPolyhedronQuantities.back();
3712 TElemDef & elemDef = myPolyElemXYZIDs.back();
3713 // get definitions of new elements on volume faces
3714 bool makePoly = false;
3715 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3717 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3718 volTool.NbFaceNodes( iF ),
3719 theNodes, elemDef, quantity))
3723 myPolyElems.push_back( elem );
3725 myPolyhedronQuantities.pop_back();
3726 myPolyElemXYZIDs.pop_back();
3734 //=======================================================================
3735 //function : getFacesDefinition
3736 //purpose : return faces definition for a volume face defined by theBndNodes
3737 //=======================================================================
3739 bool SMESH_Pattern::
3740 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3741 const int theNbBndNodes,
3742 const vector< const SMDS_MeshNode* >& theNodes,
3743 list< int >& theFaceDefs,
3744 vector<int>& theQuantity)
3746 bool makePoly = false;
3748 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3750 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3752 // make a set of all nodes on a face
3754 if ( !myIs2D ) { // for 2D, merge only edges
3755 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3756 if ( nn_IdList != myIdsOnBoundary.end() ) {
3757 list< int > & faceIds = nn_IdList->second.front();
3758 if ( !faceIds.empty() ) {
3760 ids.insert( faceIds.begin(), faceIds.end() );
3765 // add ids on links and bnd nodes
3766 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3767 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3768 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3770 // add id of iN-th bnd node
3772 nSet.insert( theBndNodes[ iN ] );
3773 nn_IdList = myIdsOnBoundary.find( nSet );
3774 int bndId = ++lastFreeId;
3775 if ( nn_IdList != myIdsOnBoundary.end() ) {
3776 bndId = nn_IdList->second.front().front();
3777 ids.insert( bndId );
3780 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3782 faceDef.push_back( bndId );
3783 // add ids on a link
3785 linkNodes.insert( theBndNodes[ iN ]);
3786 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3787 nn_IdList = myIdsOnBoundary.find( linkNodes );
3788 if ( nn_IdList != myIdsOnBoundary.end() ) {
3789 list< int > & linkIds = nn_IdList->second.front();
3790 if ( !linkIds.empty() )
3793 ids.insert( linkIds.begin(), linkIds.end() );
3794 if ( isReversed( theBndNodes[ iN ], linkIds ))
3795 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3797 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3802 // find faces definition of new volumes
3804 bool defsAdded = false;
3805 if ( !myIs2D ) { // for 2D, merge only edges
3806 SMDS_VolumeTool vol;
3807 set< TElemDef* > checkedVolDefs;
3808 set< int >::iterator id = ids.begin();
3809 for ( ; id != ids.end(); ++id )
3811 // definitions of volumes sharing id
3812 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3813 ASSERT( !defList.empty() );
3814 // loop on volume definitions
3815 list< TElemDef* >::iterator pIdList = defList.begin();
3816 for ( ; pIdList != defList.end(); ++pIdList)
3818 if ( !checkedVolDefs.insert( *pIdList ).second )
3819 continue; // skip already checked volume definition
3820 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3821 // loop on face defs of a volume
3822 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3823 if ( volType == SMDS_VolumeTool::UNKNOWN )
3825 int nbFaces = vol.NbFaces( volType );
3826 for ( int iF = 0; iF < nbFaces; ++iF )
3828 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3829 int iN, nbN = vol.NbFaceNodes( volType, iF );
3830 // check if all nodes of a faces are in <ids>
3832 for ( iN = 0; iN < nbN && all; ++iN ) {
3833 int nodeId = idVec[ nodeInds[ iN ]];
3834 all = ( ids.find( nodeId ) != ids.end() );
3837 // store a face definition
3838 for ( iN = 0; iN < nbN; ++iN ) {
3839 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3841 theQuantity.push_back( nbN );
3849 theQuantity.push_back( faceDef.size() );
3850 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3856 //=======================================================================
3857 //function : clearSubMesh
3859 //=======================================================================
3861 static bool clearSubMesh( SMESH_Mesh* theMesh,
3862 const TopoDS_Shape& theShape)
3864 bool removed = false;
3865 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3867 removed = !aSubMesh->IsEmpty();
3869 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3872 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3873 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3875 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3876 removed = eIt->more();
3877 while ( eIt->more() )
3878 aMeshDS->RemoveElement( eIt->next() );
3879 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3880 removed = removed || nIt->more();
3881 while ( nIt->more() )
3882 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3888 //=======================================================================
3889 //function : clearMesh
3890 //purpose : clear mesh elements existing on myShape in theMesh
3891 //=======================================================================
3893 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3896 if ( !myShape.IsNull() )
3898 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3899 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3900 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3902 clearSubMesh( theMesh, it.Value() );
3908 //=======================================================================
3909 //function : findExistingNodes
3910 //purpose : fills nodes vector with nodes existing on a given shape (IMP 22368)
3911 // Returns true if all nodes for all points on S are found
3912 //=======================================================================
3914 bool SMESH_Pattern::findExistingNodes( SMESH_Mesh* mesh,
3915 const TopoDS_Shape& S,
3916 const std::list< TPoint* > & points,
3917 vector< const SMDS_MeshNode* > & nodesVector)
3919 if ( S.IsNull() || points.empty() )
3922 SMESHDS_Mesh* aMeshDS = mesh->GetMeshDS();
3924 switch ( S.ShapeType() )
3928 int pIndex = points.back() - &myPoints[0];
3929 if ( !nodesVector[ pIndex ] )
3930 nodesVector[ pIndex ] = SMESH_Algo::VertexNode( TopoDS::Vertex( S ), aMeshDS );
3931 return nodesVector[ pIndex ];
3935 const TopoDS_Edge& edge = TopoDS::Edge( S );
3936 map< double, const SMDS_MeshNode* > paramsOfNodes;
3937 if ( !SMESH_Algo::GetSortedNodesOnEdge( aMeshDS, edge,
3938 /*ignoreMediumNodes=*/false,
3940 || paramsOfNodes.size() < 3 )
3942 // points on VERTEXes are included with wrong myU
3943 list< TPoint* >::const_reverse_iterator pItR = ++points.rbegin();
3944 list< TPoint* >::const_iterator pItF = ++points.begin();
3945 const bool isForward = ( (*pItF)->myU < (*pItR)->myU );
3946 map< double, const SMDS_MeshNode* >::iterator u2n = ++paramsOfNodes.begin();
3947 map< double, const SMDS_MeshNode* >::iterator u2nEnd = --paramsOfNodes.end();
3949 if ( paramsOfNodes.size() == points.size() )
3951 for ( ; u2n != u2nEnd; ++u2n )
3953 p = ( isForward ? *pItF : *pItR );
3954 int pIndex = p - &myPoints[0];
3955 if ( !nodesVector [ pIndex ] )
3956 nodesVector [ pIndex ] = u2n->second;
3964 const double tolFact = 0.05;
3965 while ( u2n != u2nEnd && pItF != points.end() )
3967 const double u = u2n->first;
3968 const SMDS_MeshNode* n = u2n->second;
3969 const double tol = ( (++u2n)->first - u ) * tolFact;
3972 p = ( isForward ? *pItF : *pItR );
3973 if ( Abs( u - p->myU ) < tol )
3975 int pIndex = p - &myPoints[0];
3976 if ( !nodesVector [ pIndex ] )
3977 nodesVector [ pIndex ] = n;
3983 while ( p->myU < u && ( ++pItF, ++pItR != points.rend() ));
3987 } // case TopAbs_EDGE:
3990 } // switch ( S.ShapeType() )
3995 //=======================================================================
3996 //function : MakeMesh
3997 //purpose : Create nodes and elements in <theMesh> using nodes
3998 // coordinates computed by either of Apply...() methods
3999 //=======================================================================
4001 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
4002 const bool toCreatePolygons,
4003 const bool toCreatePolyedrs)
4005 if ( !myIsComputed )
4006 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
4008 mergePoints( toCreatePolygons );
4010 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4012 // clear elements and nodes existing on myShape
4015 bool onMeshElements = ( !myElements.empty() );
4017 // Create missing nodes
4019 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
4020 if ( onMeshElements )
4022 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
4023 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
4024 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
4025 nodesVector[ i_node->first ] = i_node->second;
4027 for ( size_t i = 0; i < myXYZ.size(); ++i ) {
4028 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
4029 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
4033 if ( theMesh->HasShapeToMesh() )
4035 // set nodes on EDGEs (IMP 22368)
4036 SMESH_MesherHelper helper( *theMesh );
4037 helper.ToFixNodeParameters( true );
4038 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
4039 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
4041 list<list< int > >& groups = idListIt->second;
4042 const TNodeSet& nodes = idListIt->first;
4043 if ( nodes.size() != 2 )
4044 continue; // not a link
4045 const SMDS_MeshNode* n1 = *nodes.begin();
4046 const SMDS_MeshNode* n2 = *nodes.rbegin();
4047 TopoDS_Shape S1 = helper.GetSubShapeByNode( n1, aMeshDS );
4048 TopoDS_Shape S2 = helper.GetSubShapeByNode( n2, aMeshDS );
4049 if ( S1.IsNull() || S1.ShapeType() < TopAbs_EDGE ||
4050 S2.IsNull() || S2.ShapeType() < TopAbs_EDGE )
4053 if ( S1.ShapeType() == TopAbs_EDGE )
4055 if ( S1 == S2 || helper.IsSubShape( S2, S1 ))
4058 else if ( S2.ShapeType() == TopAbs_EDGE )
4060 if ( helper.IsSubShape( S1, S2 ))
4065 S = helper.GetCommonAncestor( S1, S2, *theMesh, TopAbs_EDGE );
4069 const TopoDS_Edge & E = TopoDS::Edge( S );
4070 helper.SetSubShape( E );
4071 list<list< int > >::iterator g = groups.begin();
4072 for ( ; g != groups.end(); ++g )
4074 list< int >& ids = *g;
4075 list< int >::iterator id = ids.begin();
4076 for ( ; id != ids.end(); ++id )
4077 if ( nodesVector[ *id ] && nodesVector[ *id ]->getshapeId() < 1 )
4080 aMeshDS->SetNodeOnEdge( nodesVector[ *id ], E, u );
4081 helper.CheckNodeU( E, nodesVector[ *id ], u, 1e-7, true );
4086 } // if ( onMeshElements )
4090 nodesVector.resize( myPoints.size(), 0 );
4092 // loop on sub-shapes of myShape: create nodes
4093 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
4094 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
4096 list< TPoint* > & points = idPointIt->second;
4098 if ( !myShapeIDMap.IsEmpty() )
4099 S = myShapeIDMap( idPointIt->first );
4101 // find existing nodes on EDGEs and VERTEXes
4102 if ( findExistingNodes( theMesh, S, points, nodesVector ))
4105 list< TPoint* >::iterator pIt = points.begin();
4106 for ( ; pIt != points.end(); pIt++ )
4108 TPoint* point = *pIt;
4109 int pIndex = point - &myPoints[0];
4110 if ( nodesVector [ pIndex ] )
4112 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
4115 nodesVector [ pIndex ] = node;
4117 if ( !S.IsNull() ) {
4119 switch ( S.ShapeType() ) {
4120 case TopAbs_VERTEX: {
4121 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
4124 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
4127 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
4128 point->myUV.X(), point->myUV.Y() ); break;
4131 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
4140 if ( onMeshElements )
4142 // prepare data to create poly elements
4143 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
4146 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
4147 // sew old and new elements
4148 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
4152 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4155 aMeshDS->compactMesh();
4157 if ( myToKeepNodes )
4158 myOutNodes.swap( nodesVector );
4160 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4161 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4162 // for ( ; i_sm != sm.end(); i_sm++ )
4164 // cout << " SM " << i_sm->first << " ";
4165 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4166 // //SMDS_ElemIteratorPtr GetElements();
4167 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4168 // while ( nit->more() )
4169 // cout << nit->next()->GetID() << " ";
4172 return setErrorCode( ERR_OK );
4175 //=======================================================================
4176 //function : createElements
4177 //purpose : add elements to the mesh
4178 //=======================================================================
4180 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4181 const vector<const SMDS_MeshNode* >& theNodesVector,
4182 const list< TElemDef > & theElemNodeIDs,
4183 const vector<const SMDS_MeshElement*>& theElements)
4185 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4186 SMESH_MeshEditor editor( theMesh );
4188 bool onMeshElements = !theElements.empty();
4190 // shapes and groups theElements are on
4191 vector< int > shapeIDs;
4192 vector< list< SMESHDS_Group* > > groups;
4193 set< const SMDS_MeshNode* > shellNodes;
4194 if ( onMeshElements )
4196 shapeIDs.resize( theElements.size() );
4197 groups.resize( theElements.size() );
4198 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4199 set<SMESHDS_GroupBase*>::const_iterator grIt;
4200 for ( size_t i = 0; i < theElements.size(); i++ )
4202 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4203 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4204 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4205 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4206 groups[ i ].push_back( group );
4209 // get all nodes bound to shells because their SpacePosition is not set
4210 // by SMESHDS_Mesh::SetNodeInVolume()
4211 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4212 if ( !aMainShape.IsNull() ) {
4213 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4214 for ( ; shellExp.More(); shellExp.Next() )
4216 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4218 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4219 while ( nIt->more() )
4220 shellNodes.insert( nIt->next() );
4225 // nb new elements per a refined element
4226 int nbNewElemsPerOld = 1;
4227 if ( onMeshElements )
4228 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4232 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4233 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4234 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4236 const TElemDef & elemNodeInd = *enIt;
4238 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4239 TElemDef::const_iterator id = elemNodeInd.begin();
4241 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4242 if ( *id < (int) theNodesVector.size() )
4243 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4245 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4247 // dim of refined elem
4248 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4249 if ( onMeshElements ) {
4250 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4253 const SMDS_MeshElement* elem = 0;
4255 switch ( nbNodes ) {
4257 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4259 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4261 if ( !onMeshElements ) {// create a quadratic face
4262 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4263 nodes[4], nodes[5] ); break;
4264 } // else do not break but create a polygon
4266 if ( !onMeshElements ) {// create a quadratic face
4267 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4268 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4269 } // else do not break but create a polygon
4271 elem = aMeshDS->AddPolygonalFace( nodes );
4275 switch ( nbNodes ) {
4277 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4279 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4282 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4283 nodes[4], nodes[5] ); break;
4285 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4286 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4288 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4291 // set element on a shape
4292 if ( elem && onMeshElements ) // applied to mesh elements
4294 int shapeID = shapeIDs[ elemIndex ];
4295 if ( shapeID > 0 ) {
4296 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4297 // set nodes on a shape
4298 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4299 if ( S.ShapeType() == TopAbs_SOLID ) {
4300 TopoDS_Iterator shellIt( S );
4301 if ( shellIt.More() )
4302 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4304 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4305 while ( noIt->more() ) {
4306 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4307 if ( node->getshapeId() < 1 &&
4308 shellNodes.find( node ) == shellNodes.end() )
4310 if ( S.ShapeType() == TopAbs_FACE )
4311 aMeshDS->SetNodeOnFace( node, shapeID,
4312 Precision::Infinite(),// <- it's a sign that UV is not set
4313 Precision::Infinite());
4315 aMeshDS->SetNodeInVolume( node, shapeID );
4316 shellNodes.insert( node );
4321 // add elem in groups
4322 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4323 for ( ; g != groups[ elemIndex ].end(); ++g )
4324 (*g)->SMDSGroup().Add( elem );
4326 if ( elem && !myShape.IsNull() ) // applied to shape
4327 aMeshDS->SetMeshElementOnShape( elem, myShape );
4330 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4331 // so that operations with hypotheses will erase the mesh being built
4333 SMESH_subMesh * subMesh;
4334 if ( !myShape.IsNull() ) {
4335 subMesh = theMesh->GetSubMesh( myShape );
4337 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4339 if ( onMeshElements ) {
4340 list< int > elemIDs;
4341 for ( size_t i = 0; i < theElements.size(); i++ )
4343 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4345 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4347 elemIDs.push_back( theElements[ i ]->GetID() );
4349 // remove refined elements
4350 editor.Remove( elemIDs, false );
4354 //=======================================================================
4355 //function : isReversed
4356 //purpose : check xyz ids order in theIdsList taking into account
4357 // theFirstNode on a link
4358 //=======================================================================
4360 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4361 const list< int >& theIdsList) const
4363 if ( theIdsList.size() < 2 )
4366 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4368 list<int>::const_iterator id = theIdsList.begin();
4369 for ( int i = 0; i < 2; ++i, ++id ) {
4370 if ( *id < (int) myXYZ.size() )
4371 P[ i ] = myXYZ[ *id ];
4373 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4374 i_n = myXYZIdToNodeMap.find( *id );
4375 ASSERT( i_n != myXYZIdToNodeMap.end() );
4376 const SMDS_MeshNode* n = i_n->second;
4377 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4380 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4384 //=======================================================================
4385 //function : arrangeBoundaries
4386 //purpose : if there are several wires, arrange boundaryPoints so that
4387 // the outer wire goes first and fix inner wires orientation
4388 // update myKeyPointIDs to correspond to the order of key-points
4389 // in boundaries; sort internal boundaries by the nb of key-points
4390 //=======================================================================
4392 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4394 typedef list< list< TPoint* > >::iterator TListOfListIt;
4395 TListOfListIt bndIt;
4396 list< TPoint* >::iterator pIt;
4398 int nbBoundaries = boundaryList.size();
4399 if ( nbBoundaries > 1 )
4401 // sort boundaries by nb of key-points
4402 if ( nbBoundaries > 2 )
4404 // move boundaries in tmp list
4405 list< list< TPoint* > > tmpList;
4406 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4407 // make a map nb-key-points to boundary-position-in-tmpList,
4408 // boundary-positions get ordered in it
4409 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4410 TNbKpBndPosMap nbKpBndPosMap;
4411 bndIt = tmpList.begin();
4412 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4413 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4414 int nb = *nbKpIt * nbBoundaries;
4415 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4417 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4419 // move boundaries back to boundaryList
4420 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4421 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4422 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4423 TListOfListIt bndPos1 = bndPos2++;
4424 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4428 // Look for the outer boundary: the one with the point with the least X
4429 double leastX = DBL_MAX;
4430 TListOfListIt outerBndPos;
4431 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4433 list< TPoint* >& boundary = (*bndIt);
4434 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4436 TPoint* point = *pIt;
4437 if ( point->myInitXYZ.X() < leastX ) {
4438 leastX = point->myInitXYZ.X();
4439 outerBndPos = bndIt;
4444 if ( outerBndPos != boundaryList.begin() )
4445 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos );
4447 } // if nbBoundaries > 1
4449 // Check boundaries orientation and re-fill myKeyPointIDs
4451 set< TPoint* > keyPointSet;
4452 list< int >::iterator kpIt = myKeyPointIDs.begin();
4453 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4454 keyPointSet.insert( & myPoints[ *kpIt ]);
4455 myKeyPointIDs.clear();
4457 // update myNbKeyPntInBoundary also
4458 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4460 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4462 // find the point with the least X
4463 double leastX = DBL_MAX;
4464 list< TPoint* >::iterator xpIt;
4465 list< TPoint* >& boundary = (*bndIt);
4466 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4468 TPoint* point = *pIt;
4469 if ( point->myInitXYZ.X() < leastX ) {
4470 leastX = point->myInitXYZ.X();
4474 // find points next to the point with the least X
4475 TPoint* p = *xpIt, *pPrev, *pNext;
4476 if ( p == boundary.front() )
4477 pPrev = *(++boundary.rbegin());
4483 if ( p == boundary.back() )
4484 pNext = *(++boundary.begin());
4489 // vectors of boundary direction near <p>
4490 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4491 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4492 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4493 double yPrev = v1.Y() / sqrt( sqMag1 );
4494 double yNext = v2.Y() / sqrt( sqMag2 );
4495 double sumY = yPrev + yNext;
4497 if ( bndIt == boundaryList.begin() ) // outer boundary
4505 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4506 (*nbKpIt) = 0; // count nb of key-points again
4507 pIt = boundary.begin();
4508 for ( ; pIt != boundary.end(); pIt++)
4510 TPoint* point = *pIt;
4511 if ( keyPointSet.find( point ) == keyPointSet.end() )
4513 // find an index of a keypoint
4515 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4516 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4517 if ( &(*pVecIt) == point )
4519 myKeyPointIDs.push_back( index );
4522 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4525 } // loop on a list of boundaries
4527 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4530 //=======================================================================
4531 //function : findBoundaryPoints
4532 //purpose : if loaded from file, find points to map on edges and faces and
4533 // compute their parameters
4534 //=======================================================================
4536 bool SMESH_Pattern::findBoundaryPoints()
4538 if ( myIsBoundaryPointsFound ) return true;
4540 myNbKeyPntInBoundary.clear();
4544 set< TPoint* > pointsInElems;
4546 // Find free links of elements:
4547 // put links of all elements in a set and remove links encountered twice
4549 typedef pair< TPoint*, TPoint*> TLink;
4550 set< TLink > linkSet;
4551 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4552 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4554 TElemDef & elemPoints = *epIt;
4555 TElemDef::iterator pIt = elemPoints.begin();
4556 int prevP = elemPoints.back();
4557 for ( ; pIt != elemPoints.end(); pIt++ ) {
4558 TPoint* p1 = & myPoints[ prevP ];
4559 TPoint* p2 = & myPoints[ *pIt ];
4560 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4561 ASSERT( link.first != link.second );
4562 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4563 if ( !itUniq.second )
4564 linkSet.erase( itUniq.first );
4567 pointsInElems.insert( p1 );
4570 // Now linkSet contains only free links,
4571 // find the points order that they have in boundaries
4573 // 1. make a map of key-points
4574 set< TPoint* > keyPointSet;
4575 list< int >::iterator kpIt = myKeyPointIDs.begin();
4576 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4577 keyPointSet.insert( & myPoints[ *kpIt ]);
4579 // 2. chain up boundary points
4580 list< list< TPoint* > > boundaryList;
4581 boundaryList.push_back( list< TPoint* >() );
4582 list< TPoint* > * boundary = & boundaryList.back();
4584 TPoint *point1, *point2, *keypoint1;
4585 kpIt = myKeyPointIDs.begin();
4586 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4587 // loop on free links: look for the next point
4589 set< TLink >::iterator lIt = linkSet.begin();
4590 while ( lIt != linkSet.end() )
4592 if ( (*lIt).first == point1 )
4593 point2 = (*lIt).second;
4594 else if ( (*lIt).second == point1 )
4595 point2 = (*lIt).first;
4600 linkSet.erase( lIt );
4601 lIt = linkSet.begin();
4603 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4605 boundary->push_back( point2 );
4607 else // a key-point found
4609 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4611 if ( point2 != keypoint1 ) // its not the boundary end
4613 boundary->push_back( point2 );
4615 else // the boundary end reached
4617 boundary->push_front( keypoint1 );
4618 boundary->push_back( keypoint1 );
4619 myNbKeyPntInBoundary.push_back( iKeyPoint );
4620 if ( keyPointSet.empty() )
4621 break; // all boundaries containing key-points are found
4623 // prepare to search for the next boundary
4624 boundaryList.push_back( list< TPoint* >() );
4625 boundary = & boundaryList.back();
4626 point2 = keypoint1 = (*keyPointSet.begin());
4630 } // loop on the free links set
4632 if ( boundary->empty() ) {
4633 MESSAGE(" a separate key-point");
4634 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4637 // if there are several wires, arrange boundaryPoints so that
4638 // the outer wire goes first and fix inner wires orientation;
4639 // sort myKeyPointIDs to correspond to the order of key-points
4641 arrangeBoundaries( boundaryList );
4643 // Find correspondence shape ID - points,
4644 // compute points parameter on edge
4646 keyPointSet.clear();
4647 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4648 keyPointSet.insert( & myPoints[ *kpIt ]);
4650 set< TPoint* > edgePointSet; // to find in-face points
4651 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4652 int edgeID = myKeyPointIDs.size() + 1;
4654 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4655 for ( ; bndIt != boundaryList.end(); bndIt++ )
4657 boundary = & (*bndIt);
4658 double edgeLength = 0;
4659 list< TPoint* >::iterator pIt = boundary->begin();
4660 getShapePoints( edgeID ).push_back( *pIt );
4661 getShapePoints( vertexID++ ).push_back( *pIt );
4662 for ( pIt++; pIt != boundary->end(); pIt++)
4664 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4665 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4666 TPoint* point = *pIt;
4667 edgePointSet.insert( point );
4668 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4670 edgePoints.push_back( point );
4671 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4672 point->myInitU = edgeLength;
4676 // treat points on the edge which ends up: compute U [0,1]
4677 edgePoints.push_back( point );
4678 if ( edgePoints.size() > 2 ) {
4679 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4680 list< TPoint* >::iterator epIt = edgePoints.begin();
4681 for ( ; epIt != edgePoints.end(); epIt++ )
4682 (*epIt)->myInitU /= edgeLength;
4684 // begin the next edge treatment
4687 if ( point != boundary->front() ) { // not the first key-point again
4688 getShapePoints( edgeID ).push_back( point );
4689 getShapePoints( vertexID++ ).push_back( point );
4695 // find in-face points
4696 list< TPoint* > & facePoints = getShapePoints( edgeID );
4697 vector< TPoint >::iterator pVecIt = myPoints.begin();
4698 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4699 TPoint* point = &(*pVecIt);
4700 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4701 pointsInElems.find( point ) != pointsInElems.end())
4702 facePoints.push_back( point );
4709 // bind points to shapes according to point parameters
4710 vector< TPoint >::iterator pVecIt = myPoints.begin();
4711 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4712 TPoint* point = &(*pVecIt);
4713 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4714 getShapePoints( shapeID ).push_back( point );
4715 // detect key-points
4716 if ( SMESH_Block::IsVertexID( shapeID ))
4717 myKeyPointIDs.push_back( i );
4721 myIsBoundaryPointsFound = true;
4722 return myIsBoundaryPointsFound;
4725 //=======================================================================
4727 //purpose : clear fields
4728 //=======================================================================
4730 void SMESH_Pattern::Clear()
4732 myIsComputed = myIsBoundaryPointsFound = false;
4735 myKeyPointIDs.clear();
4736 myElemPointIDs.clear();
4737 myShapeIDToPointsMap.clear();
4738 myShapeIDMap.Clear();
4740 myNbKeyPntInBoundary.clear();
4743 myElemXYZIDs.clear();
4744 myXYZIdToNodeMap.clear();
4746 myOrderedNodes.clear();
4747 myPolyElems.clear();
4748 myPolyElemXYZIDs.clear();
4749 myPolyhedronQuantities.clear();
4750 myIdsOnBoundary.clear();
4751 myReverseConnectivity.clear();
4754 //================================================================================
4756 * \brief set ErrorCode and return true if it is Ok
4758 //================================================================================
4760 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4762 myErrorCode = theErrorCode;
4763 return myErrorCode == ERR_OK;
4766 //=======================================================================
4767 //function : setShapeToMesh
4768 //purpose : set a shape to be meshed. Return True if meshing is possible
4769 //=======================================================================
4771 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4773 if ( !IsLoaded() ) {
4774 MESSAGE( "Pattern not loaded" );
4775 return setErrorCode( ERR_APPL_NOT_LOADED );
4778 TopAbs_ShapeEnum aType = theShape.ShapeType();
4779 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4781 MESSAGE( "Pattern dimension mismatch" );
4782 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4785 // check if a face is closed
4786 int nbNodeOnSeamEdge = 0;
4788 TopTools_MapOfShape seamVertices;
4789 TopoDS_Face face = TopoDS::Face( theShape );
4790 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4791 for ( ; eExp.More() /*&& nbNodeOnSeamEdge == 0*/; eExp.Next() ) {
4792 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4793 if ( BRep_Tool::IsClosed(ee, face) ) {
4794 // seam edge and vertices encounter twice in theFace
4795 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4796 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4801 // check nb of vertices
4802 TopTools_IndexedMapOfShape vMap;
4803 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4804 if ( vMap.Extent() + nbNodeOnSeamEdge != (int)myKeyPointIDs.size() ) {
4805 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4806 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4809 myElements.clear(); // not refine elements
4810 myElemXYZIDs.clear();
4812 myShapeIDMap.Clear();
4817 //=======================================================================
4818 //function : GetMappedPoints
4819 //purpose : Return nodes coordinates computed by Apply() method
4820 //=======================================================================
4822 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4825 if ( !myIsComputed )
4828 if ( myElements.empty() ) { // applied to shape
4829 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4830 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4831 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4833 else { // applied to mesh elements
4834 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4835 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4836 for ( ; xyz != myXYZ.end(); ++xyz )
4837 if ( !isDefined( *xyz ))
4838 thePoints.push_back( definedXYZ );
4840 thePoints.push_back( & (*xyz) );
4842 return !thePoints.empty();
4846 //=======================================================================
4847 //function : GetPoints
4848 //purpose : Return nodes coordinates of the pattern
4849 //=======================================================================
4851 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4858 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4859 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4860 thePoints.push_back( & (*pVecIt).myInitXYZ );
4862 return ( thePoints.size() > 0 );
4865 //=======================================================================
4866 //function : getShapePoints
4867 //purpose : return list of points located on theShape
4868 //=======================================================================
4870 list< SMESH_Pattern::TPoint* > &
4871 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4874 if ( !myShapeIDMap.Contains( theShape ))
4875 aShapeID = myShapeIDMap.Add( theShape );
4877 aShapeID = myShapeIDMap.FindIndex( theShape );
4879 return myShapeIDToPointsMap[ aShapeID ];
4882 //=======================================================================
4883 //function : getShapePoints
4884 //purpose : return list of points located on the shape
4885 //=======================================================================
4887 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4889 return myShapeIDToPointsMap[ theShapeID ];
4892 //=======================================================================
4893 //function : DumpPoints
4895 //=======================================================================
4897 void SMESH_Pattern::DumpPoints() const
4900 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4901 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4902 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4906 //=======================================================================
4907 //function : TPoint()
4909 //=======================================================================
4911 SMESH_Pattern::TPoint::TPoint()
4914 myInitXYZ.SetCoord(0,0,0);
4915 myInitUV.SetCoord(0.,0.);
4917 myXYZ.SetCoord(0,0,0);
4918 myUV.SetCoord(0.,0.);
4923 //=======================================================================
4924 //function : operator <<
4926 //=======================================================================
4928 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4930 gp_XYZ xyz = p.myInitXYZ;
4931 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4932 gp_XY xy = p.myInitUV;
4933 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4934 double u = p.myInitU;
4935 OS << " u( " << u << " )) " << &p << endl;
4936 xyz = p.myXYZ.XYZ();
4937 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4939 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4941 OS << " u( " << u << " ))" << endl;