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_Utils.hxx>
79 #include "utilities.h"
83 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
85 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
90 //=======================================================================
93 //=======================================================================
95 inline int getInt( const char * theSring )
97 if ( *theSring < '0' || *theSring > '9' )
101 int val = strtol( theSring, &ptr, 10 );
102 if ( ptr == theSring ||
103 // there must not be neither '.' nor ',' nor 'E' ...
104 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0' && *ptr != '\r'))
110 //=======================================================================
111 //function : getDouble
113 //=======================================================================
115 inline double getDouble( const char * theSring )
118 return strtod( theSring, &ptr );
121 //=======================================================================
122 //function : readLine
123 //purpose : Put token starting positions in theFields until '\n' or '\0'
124 // Return the number of the found tokens
125 //=======================================================================
127 int readLine (list <const char*> & theFields,
128 const char* & theLineBeg,
129 const bool theClearFields )
131 if ( theClearFields )
136 /* switch ( symbol ) { */
137 /* case white-space: */
138 /* look for a non-space symbol; */
139 /* case string-end: */
142 /* case comment beginning: */
143 /* skip all till a line-end; */
145 /* put its position in theFields, skip till a white-space;*/
151 bool stopReading = false;
154 bool isNumber = false;
155 switch ( *theLineBeg )
157 case ' ': // white space
162 case '\n': // a line ends
163 stopReading = ( nbRead > 0 );
168 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
172 case '\0': // file ends
175 case '-': // real number
180 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
182 theFields.push_back( theLineBeg );
185 while (*theLineBeg != ' ' &&
186 *theLineBeg != '\n' &&
187 *theLineBeg != '\0');
191 return 0; // incorrect file format
197 } while ( !stopReading );
202 //=======================================================================
203 //function : isRealSeam
204 //purpose : return true if an EDGE encounters twice in a FACE
205 //=======================================================================
207 // bool isRealSeam( const TopoDS_Edge& e, const TopoDS_Face& f )
209 // if ( BRep_Tool::IsClosed( e, f ))
212 // for (TopExp_Explorer exp( f, TopAbs_EDGE ); exp.More(); exp.Next())
213 // if ( exp.Current().IsSame( e ))
220 //=======================================================================
222 //purpose : load VERTEXes and EDGEs in a map. Return nb loaded VERTEXes
223 //=======================================================================
225 int loadVE( const list< TopoDS_Edge > & eList,
226 TopTools_IndexedMapOfOrientedShape & map )
228 list< TopoDS_Edge >::const_iterator eIt = eList.begin();
231 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
234 map.Add( TopExp::FirstVertex( *eIt, true ));
235 bool added = ( nbV < map.Extent() );
236 if ( !added ) { // vertex encountered twice
237 // a seam vertex have two corresponding key points
238 map.Add( TopExp::FirstVertex( *eIt, true ).Reversed());
244 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
252 //=======================================================================
253 //function : SMESH_Pattern
255 //=======================================================================
257 SMESH_Pattern::SMESH_Pattern (): myToKeepNodes(false)
261 //=======================================================================
263 //purpose : Load a pattern from <theFile>
264 //=======================================================================
266 bool SMESH_Pattern::Load (const char* theFileContents)
268 Kernel_Utils::Localizer loc;
272 // ! This is a comment
273 // NB_POINTS ! 1 integer - the number of points in the pattern.
274 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
275 // X2 Y2 [Z2] ! the pattern dimension is defined by the number of coordinates
277 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
278 // ! elements description goes after all
279 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
284 const char* lineBeg = theFileContents;
285 list <const char*> fields;
286 const bool clearFields = true;
288 // NB_POINTS ! 1 integer - the number of points in the pattern.
290 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
291 MESSAGE("Error reading NB_POINTS");
292 return setErrorCode( ERR_READ_NB_POINTS );
294 int nbPoints = getInt( fields.front() );
296 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
298 // read the first point coordinates to define pattern dimension
299 int dim = readLine( fields, lineBeg, clearFields );
305 MESSAGE("Error reading points: wrong nb of coordinates");
306 return setErrorCode( ERR_READ_POINT_COORDS );
308 if ( nbPoints <= dim ) {
309 MESSAGE(" Too few points ");
310 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
313 // read the rest points
315 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
316 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
317 MESSAGE("Error reading points : wrong nb of coordinates ");
318 return setErrorCode( ERR_READ_POINT_COORDS );
320 // store point coordinates
321 myPoints.resize( nbPoints );
322 list <const char*>::iterator fIt = fields.begin();
323 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
325 TPoint & p = myPoints[ iPoint ];
326 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
328 double coord = getDouble( *fIt );
329 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
330 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
332 return setErrorCode( ERR_READ_3D_COORD );
334 p.myInitXYZ.SetCoord( iCoord, coord );
336 p.myInitUV.SetCoord( iCoord, coord );
340 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
343 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
344 MESSAGE("Error: missing key-points");
346 return setErrorCode( ERR_READ_NO_KEYPOINT );
349 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
351 int pointIndex = getInt( *fIt );
352 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
353 MESSAGE("Error: invalid point index " << pointIndex );
355 return setErrorCode( ERR_READ_BAD_INDEX );
357 if ( idSet.insert( pointIndex ).second ) // unique?
358 myKeyPointIDs.push_back( pointIndex );
362 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
364 while ( readLine( fields, lineBeg, clearFields ))
366 myElemPointIDs.push_back( TElemDef() );
367 TElemDef& elemPoints = myElemPointIDs.back();
368 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
370 int pointIndex = getInt( *fIt );
371 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
372 MESSAGE("Error: invalid point index " << pointIndex );
374 return setErrorCode( ERR_READ_BAD_INDEX );
376 elemPoints.push_back( pointIndex );
378 // check the nb of nodes in element
380 switch ( elemPoints.size() ) {
381 case 3: if ( !myIs2D ) Ok = false; break;
385 case 8: if ( myIs2D ) Ok = false; break;
389 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
391 return setErrorCode( ERR_READ_ELEM_POINTS );
394 if ( myElemPointIDs.empty() ) {
395 MESSAGE("Error: no elements");
397 return setErrorCode( ERR_READ_NO_ELEMS );
400 findBoundaryPoints(); // sort key-points
402 return setErrorCode( ERR_OK );
405 //=======================================================================
407 //purpose : Save the loaded pattern into the file <theFileName>
408 //=======================================================================
410 bool SMESH_Pattern::Save (ostream& theFile)
412 Kernel_Utils::Localizer loc;
415 MESSAGE(" Pattern not loaded ");
416 return setErrorCode( ERR_SAVE_NOT_LOADED );
419 theFile << "!!! SALOME Mesh Pattern file" << endl;
420 theFile << "!!!" << endl;
421 theFile << "!!! Nb of points:" << endl;
422 theFile << myPoints.size() << endl;
426 // theFile.width( 8 );
427 // theFile.setf(ios::fixed);// use 123.45 floating notation
428 // theFile.setf(ios::right);
429 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
430 // theFile.setf(ios::showpoint); // do not show trailing zeros
431 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
432 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
433 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
434 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
435 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
436 theFile << " !- " << i << endl; // point id to ease reading by a human being
440 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
441 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
442 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
443 theFile << " " << *kpIt;
444 if ( !myKeyPointIDs.empty() )
448 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
449 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
450 for ( ; epIt != myElemPointIDs.end(); epIt++ )
452 const TElemDef & elemPoints = *epIt;
453 TElemDef::const_iterator iIt = elemPoints.begin();
454 for ( ; iIt != elemPoints.end(); iIt++ )
455 theFile << " " << *iIt;
461 return setErrorCode( ERR_OK );
464 //=======================================================================
465 //function : sortBySize
466 //purpose : sort theListOfList by size
467 //=======================================================================
469 template<typename T> struct TSizeCmp {
470 bool operator ()( const list < T > & l1, const list < T > & l2 )
471 const { return l1.size() < l2.size(); }
474 template<typename T> void sortBySize( list< list < T > > & theListOfList )
476 if ( theListOfList.size() > 2 ) {
477 TSizeCmp< T > SizeCmp;
478 theListOfList.sort( SizeCmp );
482 //=======================================================================
485 //=======================================================================
487 static gp_XY project (const SMDS_MeshNode* theNode,
488 Extrema_GenExtPS & theProjectorPS)
490 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
491 theProjectorPS.Perform( P );
492 if ( !theProjectorPS.IsDone() ) {
493 MESSAGE( "SMESH_Pattern: point projection FAILED");
496 double u =0, v =0, minVal = DBL_MAX;
497 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
498 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
499 minVal = theProjectorPS.SquareDistance( i );
500 theProjectorPS.Point( i ).Parameter( u, v );
502 return gp_XY( u, v );
505 //=======================================================================
506 //function : areNodesBound
507 //purpose : true if all nodes of faces are bound to shapes
508 //=======================================================================
510 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
512 while ( faceItr->more() )
514 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
515 while ( nIt->more() )
517 const SMDS_MeshNode* node = smdsNode( nIt->next() );
518 if (node->getshapeId() <1) {
526 //=======================================================================
527 //function : isMeshBoundToShape
528 //purpose : return true if all 2d elements are bound to shape
529 // if aFaceSubmesh != NULL, then check faces bound to it
530 // else check all faces in aMeshDS
531 //=======================================================================
533 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
534 SMESHDS_SubMesh * aFaceSubmesh,
535 const bool isMainShape)
537 if ( isMainShape && aFaceSubmesh ) {
538 // check that all faces are bound to aFaceSubmesh
539 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
543 // check face nodes binding
544 if ( aFaceSubmesh ) {
545 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
546 return areNodesBound( fIt );
548 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
549 return areNodesBound( fIt );
552 //=======================================================================
554 //purpose : Create a pattern from the mesh built on <theFace>.
555 // <theProject>==true makes override nodes positions
556 // on <theFace> computed by mesher
557 //=======================================================================
559 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
560 const TopoDS_Face& theFace,
562 TopoDS_Vertex the1stVertex,
567 myToKeepNodes = theKeepNodes;
569 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
570 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
571 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
572 SMESH_MesherHelper helper( *theMesh );
573 helper.SetSubShape( theFace );
575 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
576 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
577 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
579 MESSAGE( "No elements bound to the face");
580 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
583 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
585 // check if face is closed
586 bool isClosed = helper.HasSeam();
587 list<TopoDS_Edge> eList;
588 list<TopoDS_Edge>::iterator elIt;
589 SMESH_Block::GetOrderedEdges( face, eList, myNbKeyPntInBoundary, the1stVertex );
591 // check that requested or needed projection is possible
592 bool isMainShape = theMesh->IsMainShape( face );
593 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
594 bool canProject = ( nbElems ? true : isMainShape );
596 canProject = false; // so far
598 if ( ( theProject || needProject ) && !canProject )
599 return setErrorCode( ERR_LOADF_CANT_PROJECT );
601 Extrema_GenExtPS projector;
602 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
603 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
606 TNodePointIDMap nodePointIDMap;
607 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
611 // ---------------------------------------------------------------
612 // The case where the submesh is projected to theFace
613 // ---------------------------------------------------------------
616 SMDS_ElemIteratorPtr fIt;
618 fIt = fSubMesh->GetElements();
620 fIt = aMeshDS->elementsIterator( SMDSAbs_Face );
622 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
623 while ( fIt->more() )
625 const SMDS_MeshElement* face = fIt->next();
626 myElemPointIDs.push_back( TElemDef() );
627 TElemDef& elemPoints = myElemPointIDs.back();
628 int nbNodes = face->NbCornerNodes();
629 for ( int i = 0;i < nbNodes; ++i )
631 const SMDS_MeshElement* node = face->GetNode( i );
632 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
633 if ( nIdIt->second == -1 )
634 nIdIt->second = iPoint++;
635 elemPoints.push_back( (*nIdIt).second );
638 myPoints.resize( iPoint );
640 // project all nodes of 2d elements to theFace
641 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
642 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
644 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
645 TPoint * p = & myPoints[ (*nIdIt).second ];
646 p->myInitUV = project( node, projector );
647 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
649 // find key-points: the points most close to UV of vertices
650 TopExp_Explorer vExp( face, TopAbs_VERTEX );
651 set<int> foundIndices;
652 for ( ; vExp.More(); vExp.Next() ) {
653 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
654 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
655 double minDist = DBL_MAX;
657 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
658 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
659 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
660 if ( dist < minDist ) {
665 if ( foundIndices.insert( index ).second ) // unique?
666 myKeyPointIDs.push_back( index );
668 myIsBoundaryPointsFound = false;
673 // ---------------------------------------------------------------------
674 // The case where a pattern is being made from the mesh built by mesher
675 // ---------------------------------------------------------------------
677 // Load shapes in the consequent order and count nb of points
679 loadVE( eList, myShapeIDMap );
680 myShapeIDMap.Add( face );
682 nbNodes += myShapeIDMap.Extent() - 1;
684 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
685 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
686 nbNodes += eSubMesh->NbNodes() + 1;
688 myPoints.resize( nbNodes );
690 // care of INTERNAL VERTEXes
691 TopExp_Explorer vExp( face, TopAbs_VERTEX, TopAbs_EDGE );
692 for ( ; vExp.More(); vExp.Next() )
694 const SMDS_MeshNode* node =
695 SMESH_Algo::VertexNode( TopoDS::Vertex( vExp.Current()), aMeshDS );
696 if ( !node || node->NbInverseElements( SMDSAbs_Face ) == 0 )
698 myPoints.resize( ++nbNodes );
699 list< TPoint* > & fPoints = getShapePoints( face );
700 nodePointIDMap.insert( make_pair( node, iPoint ));
701 TPoint* p = &myPoints[ iPoint++ ];
702 fPoints.push_back( p );
703 gp_XY uv = helper.GetNodeUV( face, node );
704 p->myInitUV.SetCoord( uv.X(), uv.Y() );
705 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
708 // Load U of points on edges
710 Bnd_Box2d edgesUVBox;
712 list<int>::iterator nbEinW = myNbKeyPntInBoundary.begin();
714 vector< TopoDS_Edge > eVec;
715 for ( elIt = eList.begin(); elIt != eList.end(); elIt++, iE++ )
717 if ( isClosed && ( iE == 0 || iE == *nbEinW ))
719 // new wire begins; put wire EDGEs in eVec
720 list<TopoDS_Edge>::iterator eEnd = elIt;
723 std::advance( eEnd, *nbEinW );
724 eVec.assign( elIt, eEnd );
727 TopoDS_Edge & edge = *elIt;
728 list< TPoint* > & ePoints = getShapePoints( edge );
730 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( edge, face, f, l );
731 bool isForward = ( edge.Orientation() == TopAbs_FORWARD );
733 TopoDS_Shape v1 = TopExp::FirstVertex( edge, true ); // always FORWARD
734 TopoDS_Shape v2 = TopExp::LastVertex( edge, true ); // always REVERSED
735 // to make adjacent edges share key-point, we make v2 FORWARD too
736 // (as we have different points for same shape with different orientation)
739 // on closed face we must have REVERSED some of seam vertices
741 if ( helper.IsSeamShape( edge ) ) {
742 if ( helper.IsRealSeam( edge ) && !isForward ) {
743 // reverse on reversed SEAM edge
748 else { // on CLOSED edge (i.e. having one vertex with different orientations)
749 for ( int is2 = 0; is2 < 2; ++is2 ) {
750 TopoDS_Shape & v = is2 ? v2 : v1;
751 if ( helper.IsRealSeam( v ) ) {
752 // reverse or not depending on orientation of adjacent seam
753 int iSeam = helper.WrapIndex( iE + ( is2 ? +1 : -1 ), eVec.size() );
754 if ( eVec[ iSeam ].Orientation() == TopAbs_REVERSED )
761 // the forward key-point
762 list< TPoint* > * vPoint = & getShapePoints( v1 );
763 if ( vPoint->empty() )
765 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v1 );
766 if ( vSubMesh && vSubMesh->NbNodes() ) {
767 myKeyPointIDs.push_back( iPoint );
768 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
769 const SMDS_MeshNode* node = nIt->next();
770 if ( v1.Orientation() == TopAbs_REVERSED )
771 closeNodePointIDMap.insert( make_pair( node, iPoint ));
773 nodePointIDMap.insert( make_pair( node, iPoint ));
775 TPoint* keyPoint = &myPoints[ iPoint++ ];
776 vPoint->push_back( keyPoint );
778 keyPoint->myInitUV = project( node, projector );
780 keyPoint->myInitUV = C2d->Value( isForward ? f : l ).XY();
781 keyPoint->myInitXYZ.SetCoord (keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0);
782 edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
785 if ( !vPoint->empty() )
786 ePoints.push_back( vPoint->front() );
789 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
790 if ( eSubMesh && eSubMesh->NbNodes() )
792 // loop on nodes of an edge: sort them by param on edge
793 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
794 TParamNodeMap paramNodeMap;
795 int nbMeduimNodes = 0;
796 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
797 while ( nIt->more() )
799 const SMDS_MeshNode* node = nIt->next();
800 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
804 const SMDS_EdgePosition* epos =
805 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
806 double u = epos->GetUParameter();
807 paramNodeMap.insert( make_pair( u, node ));
809 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes ) {
810 // wrong U on edge, project
812 BRepAdaptor_Curve aCurve( edge );
813 proj.Initialize( aCurve, f, l );
814 paramNodeMap.clear();
815 nIt = eSubMesh->GetNodes();
816 for ( int iNode = 0; nIt->more(); ++iNode ) {
817 const SMDS_MeshNode* node = nIt->next();
818 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
820 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
822 if ( proj.IsDone() ) {
823 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
824 if ( proj.IsMin( i )) {
825 u = proj.Point( i ).Parameter();
829 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
831 paramNodeMap.insert( make_pair( u, node ));
834 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
835 if ((int) paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
836 return setErrorCode(ERR_UNEXPECTED);
839 // put U in [0,1] so that the first key-point has U==0
840 bool isSeam = helper.IsRealSeam( edge );
842 TParamNodeMap::iterator unIt = paramNodeMap.begin();
843 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
844 while ( unIt != paramNodeMap.end() )
846 TPoint* p = & myPoints[ iPoint ];
847 ePoints.push_back( p );
848 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
849 if ( isSeam && !isForward )
850 closeNodePointIDMap.insert( make_pair( node, iPoint ));
852 nodePointIDMap.insert ( make_pair( node, iPoint ));
855 p->myInitUV = project( node, projector );
857 double u = isForward ? (*unIt).first : (*unRIt).first;
858 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
859 p->myInitUV = C2d->Value( u ).XY();
861 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
862 edgesUVBox.Add( gp_Pnt2d( p->myInitUV ));
867 // the reverse key-point
868 vPoint = & getShapePoints( v2 );
869 if ( vPoint->empty() )
871 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
872 if ( vSubMesh && vSubMesh->NbNodes() ) {
873 myKeyPointIDs.push_back( iPoint );
874 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
875 const SMDS_MeshNode* node = nIt->next();
876 if ( v2.Orientation() == TopAbs_REVERSED )
877 closeNodePointIDMap.insert( make_pair( node, iPoint ));
879 nodePointIDMap.insert( make_pair( node, iPoint ));
881 TPoint* keyPoint = &myPoints[ iPoint++ ];
882 vPoint->push_back( keyPoint );
884 keyPoint->myInitUV = project( node, projector );
886 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
887 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
888 edgesUVBox.Add( gp_Pnt2d( keyPoint->myInitUV ));
891 if ( !vPoint->empty() )
892 ePoints.push_back( vPoint->front() );
894 // compute U of edge-points
897 double totalDist = 0;
898 list< TPoint* >::iterator pIt = ePoints.begin();
899 TPoint* prevP = *pIt;
900 prevP->myInitU = totalDist;
901 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
903 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
904 p->myInitU = totalDist;
907 if ( totalDist > DBL_MIN)
908 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
910 p->myInitU /= totalDist;
913 } // loop on edges of a wire
915 // Load in-face points and elements
917 if ( fSubMesh && fSubMesh->NbElements() )
919 list< TPoint* > & fPoints = getShapePoints( face );
920 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
921 while ( nIt->more() )
923 const SMDS_MeshNode* node = nIt->next();
924 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
926 nodePointIDMap.insert( make_pair( node, iPoint ));
927 TPoint* p = &myPoints[ iPoint++ ];
928 fPoints.push_back( p );
929 if ( theProject || edgesUVBox.IsOut( p->myInitUV ) )
930 p->myInitUV = project( node, projector );
932 const SMDS_FacePosition* pos =
933 static_cast<const SMDS_FacePosition*>(node->GetPosition());
934 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
936 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
939 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
940 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
941 while ( elemIt->more() )
943 const SMDS_MeshElement* elem = elemIt->next();
944 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
945 myElemPointIDs.push_back( TElemDef() );
946 TElemDef& elemPoints = myElemPointIDs.back();
947 // find point indices corresponding to element nodes
948 while ( nIt->more() )
950 const SMDS_MeshNode* node = smdsNode( nIt->next() );
951 n_id = nodePointIDMap.find( node );
952 if ( n_id == nodePointIDMap.end() )
953 continue; // medium node
954 iPoint = n_id->second; // point index of interest
955 // for a node on a seam edge there are two points
956 if ( helper.IsRealSeam( node->getshapeId() ) &&
957 ( n_id = closeNodePointIDMap.find( node )) != not_found )
959 TPoint & p1 = myPoints[ iPoint ];
960 TPoint & p2 = myPoints[ n_id->second ];
961 // Select point closest to the rest nodes of element in UV space
962 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
963 const SMDS_MeshNode* notSeamNode = 0;
964 // find node not on a seam edge
965 while ( nIt2->more() && !notSeamNode ) {
966 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
967 if ( !helper.IsSeamShape( n->getshapeId() ))
970 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
971 double dist1 = uv.SquareDistance( p1.myInitUV );
972 double dist2 = uv.SquareDistance( p2.myInitUV );
974 iPoint = n_id->second;
976 elemPoints.push_back( iPoint );
980 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
982 myIsBoundaryPointsFound = true;
987 myInNodes.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
989 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
990 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
991 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
993 nIdIt = closeNodePointIDMap.begin();
994 for ( ; nIdIt != closeNodePointIDMap.end(); nIdIt++ )
995 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
998 // Assure that U range is proportional to V range
1001 vector< TPoint >::iterator pVecIt = myPoints.begin();
1002 for ( ; pVecIt != myPoints.end(); pVecIt++ )
1003 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
1004 double minU, minV, maxU, maxV;
1005 bndBox.Get( minU, minV, maxU, maxV );
1006 double dU = maxU - minU, dV = maxV - minV;
1007 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
1010 // define where is the problem, in the face or in the mesh
1011 TopExp_Explorer vExp( face, TopAbs_VERTEX );
1012 for ( ; vExp.More(); vExp.Next() ) {
1013 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
1016 bndBox.Get( minU, minV, maxU, maxV );
1017 dU = maxU - minU, dV = maxV - minV;
1018 if ( dU <= DBL_MIN || dV <= DBL_MIN )
1020 return setErrorCode( ERR_LOADF_NARROW_FACE );
1022 // mesh is projected onto a line, e.g.
1023 return setErrorCode( ERR_LOADF_CANT_PROJECT );
1025 double ratio = dU / dV, maxratio = 3, scale;
1027 if ( ratio > maxratio ) {
1028 scale = ratio / maxratio;
1031 else if ( ratio < 1./maxratio ) {
1032 scale = maxratio / ratio;
1037 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
1038 TPoint & p = *pVecIt;
1039 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
1040 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
1043 if ( myElemPointIDs.empty() ) {
1044 MESSAGE( "No elements bound to the face");
1045 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
1048 return setErrorCode( ERR_OK );
1051 //=======================================================================
1052 //function : computeUVOnEdge
1053 //purpose : compute coordinates of points on theEdge
1054 //=======================================================================
1056 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
1057 const list< TPoint* > & ePoints )
1059 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
1061 Handle(Geom2d_Curve) C2d =
1062 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1064 ePoints.back()->myInitU = 1.0;
1065 //ePoints.front()->myInitU = 0.0; //myUV = C2d->Value( isForward ? f : l ).XY();
1066 list< TPoint* >::const_iterator pIt = ePoints.begin();
1067 for ( pIt++; pIt != ePoints.end(); pIt++ )
1069 TPoint* point = *pIt;
1071 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1072 point->myU = ( f * ( 1 - du ) + l * du );
1074 point->myUV = C2d->Value( point->myU ).XY();
1078 //=======================================================================
1079 //function : intersectIsolines
1081 //=======================================================================
1083 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1084 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1088 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1089 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1090 resUV = 0.5 * ( loc1 + loc2 );
1091 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1092 // SKL 26.07.2007 for NPAL16567
1093 double d1 = (uv11-uv12).Modulus();
1094 double d2 = (uv21-uv22).Modulus();
1095 // double delta = d1*d2*1e-6; PAL17233
1096 double delta = min( d1, d2 ) / 10.;
1097 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1099 // double len1 = ( uv11 - uv12 ).Modulus();
1100 // double len2 = ( uv21 - uv22 ).Modulus();
1101 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1105 // gp_Lin2d line1( uv11, uv12 - uv11 );
1106 // gp_Lin2d line2( uv21, uv22 - uv21 );
1107 // double angle = Abs( line1.Angle( line2 ) );
1109 // IntAna2d_AnaIntersection inter;
1110 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1111 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1113 // gp_Pnt2d interUV = inter.Point(1).Value();
1114 // resUV += interUV.XY();
1115 // inter.Perform( line1, line2 );
1116 // interUV = inter.Point(1).Value();
1117 // resUV += interUV.XY();
1121 // if ( isDeformed ) {
1122 // MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1123 // ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1128 //=======================================================================
1129 //function : compUVByIsoIntersection
1131 //=======================================================================
1133 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1134 const gp_XY& theInitUV,
1136 bool & theIsDeformed )
1138 // compute UV by intersection of 2 iso lines
1139 //gp_Lin2d isoLine[2];
1140 gp_XY uv1[2], uv2[2];
1142 const double zero = DBL_MIN;
1143 for ( int iIso = 0; iIso < 2; iIso++ )
1145 // to build an iso line:
1146 // find 2 pairs of consequent edge-points such that the range of their
1147 // initial parameters encloses the in-face point initial parameter
1148 gp_XY UV[2], initUV[2];
1149 int nbUV = 0, iCoord = iIso + 1;
1150 double initParam = theInitUV.Coord( iCoord );
1152 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1153 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1155 const list< TPoint* > & bndPoints = * bndIt;
1156 TPoint* prevP = bndPoints.back(); // this is the first point
1157 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1158 bool coincPrev = false;
1159 // loop on the edge-points
1160 for ( ; pIt != bndPoints.end(); pIt++ )
1162 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1163 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1164 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1165 if (!coincPrev && // ignore if initParam coincides with prev point param
1166 sumOfDiff > zero && // ignore if both points coincide with initParam
1167 prevParamDiff * paramDiff <= zero )
1169 // find UV in parametric space of theFace
1170 double r = Abs(prevParamDiff) / sumOfDiff;
1171 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1174 // throw away uv most distant from <theInitUV>
1175 gp_XY vec0 = initUV[0] - theInitUV;
1176 gp_XY vec1 = initUV[1] - theInitUV;
1177 gp_XY vec = uvInit - theInitUV;
1178 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1179 double dist0 = vec0.SquareModulus();
1180 double dist1 = vec1.SquareModulus();
1181 double dist = vec .SquareModulus();
1182 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1183 i = ( dist0 < dist1 ? 1 : 0 );
1184 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1185 i = 3; // theInitUV must remain between
1189 initUV[ i ] = uvInit;
1190 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1192 coincPrev = ( Abs(paramDiff) <= zero );
1199 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1200 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1201 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1202 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1204 // an iso line should be normal to UV[0] - UV[1] direction
1205 // and be located at the same relative distance as from initial ends
1206 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1208 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1209 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1210 //isoLine[ iIso ] = iso.Normal( isoLoc );
1211 uv1[ iIso ] = UV[0];
1212 uv2[ iIso ] = UV[1];
1215 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1216 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1217 MESSAGE(" Can't intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1218 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1225 // ==========================================================
1226 // structure representing a node of a grid of iso-poly-lines
1227 // ==========================================================
1234 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1235 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1236 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1237 TIsoNode(double initU, double initV):
1238 myIsMovable(true), myInitUV( initU, initV ), myUV( 1e100, 1e100 )
1239 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1240 bool IsUVComputed() const
1241 { return myUV.X() != 1e100; }
1242 bool IsMovable() const
1243 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1244 void SetNotMovable()
1245 { myIsMovable = false; }
1246 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1247 { myBndNodes[ iDir + i * 2 ] = node; }
1248 TIsoNode* GetBoundaryNode(int iDir, int i)
1249 { return myBndNodes[ iDir + i * 2 ]; }
1250 void SetNext(TIsoNode* node, int iDir, int isForward)
1251 { myNext[ iDir + isForward * 2 ] = node; }
1252 TIsoNode* GetNext(int iDir, int isForward)
1253 { return myNext[ iDir + isForward * 2 ]; }
1256 //=======================================================================
1257 //function : getNextNode
1259 //=======================================================================
1261 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1263 TIsoNode* n = node->myNext[ dir ];
1264 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1265 n = 0;//node->myBndNodes[ dir ];
1266 // MESSAGE("getNextNode: use bnd for node "<<
1267 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1271 //=======================================================================
1272 //function : checkQuads
1273 //purpose : check if newUV destortes quadrangles around node,
1274 // and if ( crit == FIX_OLD ) fix newUV in this case
1275 //=======================================================================
1277 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1279 static bool checkQuads (const TIsoNode* node,
1281 const bool reversed,
1282 const int crit = FIX_OLD,
1283 double fixSize = 0.)
1285 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1286 int nbOldFix = 0, nbOldImpr = 0;
1287 double newBadRate = 0, oldBadRate = 0;
1288 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1289 int i, dir1 = 0, dir2 = 3;
1290 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1292 if ( dir2 > 3 ) dir2 = 0;
1294 // walking counterclockwise around a quad,
1295 // nodes are in the order: node, n[0], n[1], n[2]
1296 n[0] = getNextNode( node, dir1 );
1297 n[2] = getNextNode( node, dir2 );
1298 if ( !n[0] || !n[2] ) continue;
1299 n[1] = getNextNode( n[0], dir2 );
1300 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1301 bool isTriangle = ( !n[1] );
1303 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1305 // if ( fixSize != 0 ) {
1306 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1307 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1308 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1309 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1311 // check if a quadrangle is degenerated
1313 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1314 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1317 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1320 // find min size of the diagonal node-n[1]
1321 double minDiag = fixSize;
1322 if ( minDiag == 0. ) {
1323 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1324 if ( !isTriangle ) {
1325 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1326 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1328 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1329 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1332 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1333 // ( behind means "to the right of")
1335 // 1. newUV is not behind 01 and 12 dirs
1336 // 2. or newUV is not behind 02 dir and n[2] is convex
1337 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1338 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1339 gp_Vec2d moveVec[3], outVec[3];
1340 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1342 bool isDiag = ( i == 2 );
1343 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1347 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1349 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1351 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1353 gp_Vec2d newDir( n[i]->myUV, newUV );
1354 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1356 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1357 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1358 if ( crit == FIX_OLD ) {
1359 wasIn[i] = ( outDir * oldDir < 0 );
1360 wasOk[i] = ( outDir * oldDir < -minDiag );
1362 newBadRate += outDir * newDir;
1364 oldBadRate += outDir * oldDir;
1367 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1368 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1369 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1370 moveVec[i] = ( oldDist - minDiag ) * outDir;
1375 // check if n[2] is convex
1378 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1380 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1381 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1382 newIsOk = ( newIsOk && isNewOk );
1383 newIsIn = ( newIsIn && isNewIn );
1385 if ( crit != FIX_OLD ) {
1386 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1387 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1391 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1392 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1393 oldIsIn = ( oldIsIn && isOldIn );
1394 oldIsOk = ( oldIsOk && isOldIn );
1397 if ( !isOldIn ) { // node is outside a quadrangle
1398 // move newUV inside a quadrangle
1399 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1400 // node and newUV are outside: push newUV inside
1402 if ( convex || isTriangle ) {
1403 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1406 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1407 double outSize = out.Magnitude();
1408 if ( outSize > DBL_MIN )
1411 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1412 uv = n[1]->myUV - minDiag * out.XY();
1414 oldUVFixed[ nbOldFix++ ] = uv;
1415 //node->myUV = newUV;
1417 else if ( !isOldOk ) {
1418 // try to fix old UV: move node inside as less as possible
1419 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1420 gp_XY uv1, uv2 = node->myUV;
1421 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1423 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1424 while ( !isOldOk ) {
1425 // find the least moveVec
1427 double minMove2 = 1e100;
1428 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1430 if ( moveVec[i].Coord(1) < 1e100 ) {
1431 double move2 = moveVec[i].SquareMagnitude();
1432 if ( move2 < minMove2 ) {
1441 // move node to newUV
1442 uv1 = node->myUV + moveVec[ iMin ].XY();
1443 uv2 += moveVec[ iMin ].XY();
1444 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1445 // check if uv1 is ok
1446 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1447 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1448 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1450 oldUVImpr[ nbOldImpr++ ] = uv1;
1452 // check if uv2 is ok
1453 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1454 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1455 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1457 oldUVImpr[ nbOldImpr++ ] = uv2;
1462 } // loop on 4 quadrangles around <node>
1464 if ( crit == CHECK_NEW_OK )
1466 if ( crit == CHECK_NEW_IN )
1475 if ( oldIsIn && nbOldImpr ) {
1476 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1477 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1478 gp_XY uv = oldUVImpr[ 0 ];
1479 for ( int i = 1; i < nbOldImpr; i++ )
1480 uv += oldUVImpr[ i ];
1482 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1487 //MESSAGE(" Can't improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1490 if ( !oldIsIn && nbOldFix ) {
1491 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1492 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1493 gp_XY uv = oldUVFixed[ 0 ];
1494 for ( int i = 1; i < nbOldFix; i++ )
1495 uv += oldUVFixed[ i ];
1497 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1502 //MESSAGE(" Can't fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1505 if ( newIsIn && oldIsIn )
1506 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1507 else if ( !newIsIn )
1514 //=======================================================================
1515 //function : compUVByElasticIsolines
1516 //purpose : compute UV as nodes of iso-poly-lines consisting of
1517 // segments keeping relative size as in the pattern
1518 //=======================================================================
1519 //#define DEB_COMPUVBYELASTICISOLINES
1520 bool SMESH_Pattern::
1521 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1522 const list< TPoint* >& thePntToCompute)
1524 return false; // PAL17233
1525 //cout << "============================== KEY POINTS =============================="<<endl;
1526 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1527 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1528 // TPoint& p = myPoints[ *kpIt ];
1529 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1530 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1532 //cout << "=============================="<<endl;
1534 // Define parameters of iso-grid nodes in U and V dir
1536 set< double > paramSet[ 2 ];
1537 list< list< TPoint* > >::const_iterator pListIt;
1538 list< TPoint* >::const_iterator pIt;
1539 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1540 const list< TPoint* > & pList = * pListIt;
1541 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1542 paramSet[0].insert( (*pIt)->myInitUV.X() );
1543 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1546 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1547 paramSet[0].insert( (*pIt)->myInitUV.X() );
1548 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1550 // unite close parameters and split too long segments
1553 for ( iDir = 0; iDir < 2; iDir++ )
1555 set< double > & params = paramSet[ iDir ];
1556 double range = ( *params.rbegin() - *params.begin() );
1557 double toler = range / 1e6;
1558 tol[ iDir ] = toler;
1559 // double maxSegment = range / params.size() / 2.;
1561 // set< double >::iterator parIt = params.begin();
1562 // double prevPar = *parIt;
1563 // for ( parIt++; parIt != params.end(); parIt++ )
1565 // double segLen = (*parIt) - prevPar;
1566 // if ( segLen < toler )
1567 // ;//params.erase( prevPar ); // unite
1568 // else if ( segLen > maxSegment )
1569 // params.insert( prevPar + 0.5 * segLen ); // split
1570 // prevPar = (*parIt);
1574 // Make nodes of a grid of iso-poly-lines
1576 list < TIsoNode > nodes;
1577 typedef list < TIsoNode *> TIsoLine;
1578 map < double, TIsoLine > isoMap[ 2 ];
1580 set< double > & params0 = paramSet[ 0 ];
1581 set< double >::iterator par0It = params0.begin();
1582 for ( ; par0It != params0.end(); par0It++ )
1584 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1585 set< double > & params1 = paramSet[ 1 ];
1586 set< double >::iterator par1It = params1.begin();
1587 for ( ; par1It != params1.end(); par1It++ )
1589 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1590 isoLine0.push_back( & nodes.back() );
1591 isoMap[1][ *par1It ].push_back( & nodes.back() );
1595 // Compute intersections of boundaries with iso-lines:
1596 // only boundary nodes will have computed UV so far
1599 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1600 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1601 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1603 const list< TPoint* > & bndPoints = * bndIt;
1604 TPoint* prevP = bndPoints.back(); // this is the first point
1605 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1606 // loop on the edge-points
1607 for ( ; pIt != bndPoints.end(); pIt++ )
1609 TPoint* point = *pIt;
1610 for ( iDir = 0; iDir < 2; iDir++ )
1612 const int iCoord = iDir + 1;
1613 const int iOtherCoord = 2 - iDir;
1614 double par1 = prevP->myInitUV.Coord( iCoord );
1615 double par2 = point->myInitUV.Coord( iCoord );
1616 double parDif = par2 - par1;
1617 if ( Abs( parDif ) <= DBL_MIN )
1619 // find iso-lines intersecting a bounadry
1620 double toler = tol[ 1 - iDir ];
1621 double minPar = Min ( par1, par2 );
1622 double maxPar = Max ( par1, par2 );
1623 map < double, TIsoLine >& isos = isoMap[ iDir ];
1624 map < double, TIsoLine >::iterator isoIt = isos.begin();
1625 for ( ; isoIt != isos.end(); isoIt++ )
1627 double isoParam = (*isoIt).first;
1628 if ( isoParam < minPar || isoParam > maxPar )
1630 double r = ( isoParam - par1 ) / parDif;
1631 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1632 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1633 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1634 // find existing node with otherPar or insert a new one
1635 TIsoLine & isoLine = (*isoIt).second;
1637 TIsoLine::iterator nIt = isoLine.begin();
1638 for ( ; nIt != isoLine.end(); nIt++ ) {
1639 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1640 if ( nodePar >= otherPar )
1644 if ( Abs( nodePar - otherPar ) <= toler )
1645 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1647 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1648 node = & nodes.back();
1649 isoLine.insert( nIt, node );
1651 node->SetNotMovable();
1653 uvBnd.Add( gp_Pnt2d( uv ));
1654 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1656 gp_XY tgt( point->myUV - prevP->myUV );
1657 if ( ::IsEqual( r, 1. ))
1658 node->myDir[ 0 ] = tgt;
1659 else if ( ::IsEqual( r, 0. ))
1660 node->myDir[ 1 ] = tgt;
1662 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1663 // keep boundary nodes corresponding to boundary points
1664 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1665 if ( bndNodes.empty() || bndNodes.back() != node )
1666 bndNodes.push_back( node );
1667 } // loop on isolines
1668 } // loop on 2 directions
1670 } // loop on boundary points
1671 } // loop on boundaries
1673 // Define orientation
1675 // find the point with the least X
1676 double leastX = DBL_MAX;
1677 TIsoNode * leftNode;
1678 list < TIsoNode >::iterator nodeIt = nodes.begin();
1679 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1680 TIsoNode & node = *nodeIt;
1681 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1682 leastX = node.myUV.X();
1685 // if ( node.IsUVComputed() ) {
1686 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1687 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1688 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1689 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1692 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1693 //SCRUTE( reversed );
1695 // Prepare internal nodes:
1697 // 2. compute ratios
1698 // 3. find boundary nodes for each node
1699 // 4. remove nodes out of the boundary
1700 for ( iDir = 0; iDir < 2; iDir++ )
1702 const int iCoord = 2 - iDir; // coord changing along an isoline
1703 map < double, TIsoLine >& isos = isoMap[ iDir ];
1704 map < double, TIsoLine >::iterator isoIt = isos.begin();
1705 for ( ; isoIt != isos.end(); isoIt++ )
1707 TIsoLine & isoLine = (*isoIt).second;
1708 bool firstCompNodeFound = false;
1709 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1710 nPrevIt = nIt = nNextIt = isoLine.begin();
1712 nNextIt++; nNextIt++;
1713 while ( nIt != isoLine.end() )
1715 // 1. connect prev - cur
1716 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1717 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1718 firstCompNodeFound = true;
1719 lastCompNodePos = nPrevIt;
1721 if ( firstCompNodeFound ) {
1722 node->SetNext( prevNode, iDir, 0 );
1723 prevNode->SetNext( node, iDir, 1 );
1726 if ( nNextIt != isoLine.end() ) {
1727 double par1 = prevNode->myInitUV.Coord( iCoord );
1728 double par2 = node->myInitUV.Coord( iCoord );
1729 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1730 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1732 // 3. find boundary nodes
1733 if ( node->IsUVComputed() )
1734 lastCompNodePos = nIt;
1735 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1736 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1737 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1738 if ( (*nIt2)->IsUVComputed() )
1740 if ( nIt2 != isoLine.end() ) {
1742 node->SetBoundaryNode( bndNode1, iDir, 0 );
1743 node->SetBoundaryNode( bndNode2, iDir, 1 );
1744 // cout << "--------------------------------------------------"<<endl;
1745 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1746 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1747 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1748 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1749 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1750 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1753 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1754 node->SetBoundaryNode( 0, iDir, 0 );
1755 node->SetBoundaryNode( 0, iDir, 1 );
1759 if ( nNextIt != isoLine.end() ) nNextIt++;
1760 // 4. remove nodes out of the boundary
1761 if ( !firstCompNodeFound )
1762 isoLine.pop_front();
1763 } // loop on isoLine nodes
1765 // remove nodes after the boundary
1766 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1767 // (*nIt)->SetNotMovable();
1768 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1769 } // loop on isolines
1770 } // loop on 2 directions
1772 // Compute local isoline direction for internal nodes
1775 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1776 map < double, TIsoLine >::iterator isoIt = isos.begin();
1777 for ( ; isoIt != isos.end(); isoIt++ )
1779 TIsoLine & isoLine = (*isoIt).second;
1780 TIsoLine::iterator nIt = isoLine.begin();
1781 for ( ; nIt != isoLine.end(); nIt++ )
1783 TIsoNode* node = *nIt;
1784 if ( node->IsUVComputed() || !node->IsMovable() )
1786 gp_Vec2d aTgt[2], aNorm[2];
1789 for ( iDir = 0; iDir < 2; iDir++ )
1791 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1792 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1793 if ( !bndNode1 || !bndNode2 ) {
1797 const int iCoord = 2 - iDir; // coord changing along an isoline
1798 double par1 = bndNode1->myInitUV.Coord( iCoord );
1799 double par2 = node->myInitUV.Coord( iCoord );
1800 double par3 = bndNode2->myInitUV.Coord( iCoord );
1801 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1803 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1804 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1805 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1806 else tgt1.Reverse();
1807 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1809 if ( ratio[ iDir ] < 0.5 )
1810 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1812 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1814 aNorm[ iDir ].Reverse(); // along iDir isoline
1816 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1817 // maybe angle is more than |PI|
1818 if ( Abs( angle ) > PI / 2. ) {
1819 // check direction of the last but one perpendicular isoline
1820 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1821 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1822 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1823 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1824 if ( isoDir * tgt2 < 0 )
1826 double angle2 = tgt1.Angle( isoDir );
1827 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1828 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1829 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1830 //MESSAGE("REVERSE ANGLE");
1833 if ( Abs( angle2 ) > Abs( angle ) ||
1834 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1835 //MESSAGE("Add PI");
1836 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1837 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1838 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1839 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1840 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1841 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1844 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1848 for ( iDir = 0; iDir < 2; iDir++ )
1850 aTgt[iDir].Normalize();
1851 aNorm[1-iDir].Normalize();
1852 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1855 node->myDir[iDir] = //aTgt[iDir];
1856 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1858 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1859 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1860 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1861 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1863 } // loop on iso nodes
1864 } // loop on isolines
1866 // Find nodes to start computing UV from
1868 list< TIsoNode* > startNodes;
1869 list< TIsoNode* >::iterator nIt = bndNodes.end();
1870 TIsoNode* node = *(--nIt);
1871 TIsoNode* prevNode = *(--nIt);
1872 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1874 TIsoNode* nextNode = *nIt;
1875 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1876 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1877 double initAngle = initTgt1.Angle( initTgt2 );
1878 double angle = node->myDir[0].Angle( node->myDir[1] );
1879 if ( reversed ) angle = -angle;
1880 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1881 // find a close internal node
1882 TIsoNode* nClose = 0;
1883 list< TIsoNode* > testNodes;
1884 testNodes.push_back( node );
1885 list< TIsoNode* >::iterator it = testNodes.begin();
1886 for ( ; !nClose && it != testNodes.end(); it++ )
1888 for (int i = 0; i < 4; i++ )
1890 nClose = (*it)->myNext[ i ];
1892 if ( !nClose->IsUVComputed() )
1895 testNodes.push_back( nClose );
1901 startNodes.push_back( nClose );
1902 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1903 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1904 // "initAngle: " << initAngle << " angle: " << angle << endl;
1905 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1906 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1907 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1908 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1914 // Compute starting UV of internal nodes
1916 list < TIsoNode* > internNodes;
1917 bool needIteration = true;
1918 if ( startNodes.empty() ) {
1919 //MESSAGE( " Starting UV by compUVByIsoIntersection()");
1920 needIteration = false;
1921 map < double, TIsoLine >& isos = isoMap[ 0 ];
1922 map < double, TIsoLine >::iterator isoIt = isos.begin();
1923 for ( ; isoIt != isos.end(); isoIt++ )
1925 TIsoLine & isoLine = (*isoIt).second;
1926 TIsoLine::iterator nIt = isoLine.begin();
1927 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1929 TIsoNode* node = *nIt;
1930 if ( !node->IsUVComputed() && node->IsMovable() ) {
1931 internNodes.push_back( node );
1933 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1934 node->myUV, needIteration ))
1935 node->myUV = node->myInitUV;
1939 if ( needIteration )
1940 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1942 TIsoNode* node = *nIt, *nClose = 0;
1943 list< TIsoNode* > testNodes;
1944 testNodes.push_back( node );
1945 list< TIsoNode* >::iterator it = testNodes.begin();
1946 for ( ; !nClose && it != testNodes.end(); it++ )
1948 for (int i = 0; i < 4; i++ )
1950 nClose = (*it)->myNext[ i ];
1952 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1955 testNodes.push_back( nClose );
1961 startNodes.push_back( nClose );
1965 double aMin[2], aMax[2], step[2];
1966 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1967 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1968 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1969 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1970 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1972 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1974 TIsoNode *node = *nIt;
1975 if ( node->IsUVComputed() || !node->IsMovable() )
1977 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1978 int nbComp = 0, nbPrev = 0;
1979 for ( iDir = 0; iDir < 2; iDir++ )
1981 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1982 TIsoNode* n = node->GetNext( iDir, 0 );
1983 if ( n->IsUVComputed() )
1986 startNodes.push_back( n );
1987 n = node->GetNext( iDir, 1 );
1988 if ( n->IsUVComputed() )
1991 startNodes.push_back( n );
1993 prevNode1 = prevNode2;
1996 if ( prevNode1 ) nbPrev++;
1997 if ( prevNode2 ) nbPrev++;
2000 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
2001 double par = node->myInitUV.Coord( 2 - iDir );
2002 bool isEnd = ( prevPar > par );
2003 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
2004 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2005 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
2007 MESSAGE("Why we are here?");
2010 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
2011 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
2012 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
2013 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
2014 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
2015 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
2016 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
2017 //" par: " << prevPar << endl;
2018 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
2019 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
2021 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2022 gp_XY & uv1 = prevNode1->myUV;
2023 gp_XY & uv2 = prevNode2->myUV;
2024 // dir = ( uv2 - uv1 );
2025 // double len = dir.Modulus();
2026 // if ( len > DBL_MIN )
2027 // dir /= len * 0.5;
2028 double r = node->myRatio[ iDir ];
2029 newUV += uv1 * ( 1 - r ) + uv2 * r;
2032 newUV += prevNode1->myUV + dir * step[ iDir ];
2038 if ( !nbComp ) continue;
2041 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2043 // check if a quadrangle is not distorted
2045 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
2046 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
2047 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
2048 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
2052 internNodes.push_back( node );
2057 static int maxNbIter = 100;
2058 #ifdef DEB_COMPUVBYELASTICISOLINES
2060 bool useNbMoveNode = 0;
2061 static int maxNbNodeMove = 100;
2064 if ( !useNbMoveNode )
2065 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2070 if ( !needIteration) break;
2071 #ifdef DEB_COMPUVBYELASTICISOLINES
2072 if ( nbIter >= maxNbIter ) break;
2075 list < TIsoNode* >::iterator nIt = internNodes.begin();
2076 for ( ; nIt != internNodes.end(); nIt++ ) {
2077 #ifdef DEB_COMPUVBYELASTICISOLINES
2079 cout << nbNodeMove <<" =================================================="<<endl;
2081 TIsoNode * node = *nIt;
2085 for ( iDir = 0; iDir < 2; iDir++ )
2087 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2088 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2089 double r = node->myRatio[ iDir ];
2090 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2091 // line[ iDir ].SetLocation( loc[ iDir ] );
2092 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2095 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2096 // double locR[2] = { 0, 0 };
2097 for ( iDir = 0; iDir < 2; iDir++ )
2099 const int iCoord = 2 - iDir; // coord changing along an isoline
2100 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2101 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2102 if ( !bndNode1 || !bndNode2 ) {
2105 double par1 = bndNode1->myInitUV.Coord( iCoord );
2106 double par2 = node->myInitUV.Coord( iCoord );
2107 double par3 = bndNode2->myInitUV.Coord( iCoord );
2108 double r = ( par2 - par1 ) / ( par3 - par1 );
2109 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2110 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2112 //locR[0] = locR[1] = 0.25;
2113 // intersect the 2 lines and move a node
2114 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2115 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2117 // double intR = 1 - locR[0] - locR[1];
2118 // gp_XY newUV = inter.Point(1).Value().XY();
2119 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2120 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2122 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2123 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2124 // avoid parallel isolines intersection
2125 checkQuads( node, newUV, reversed );
2127 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2129 } // intersection found
2130 #ifdef DEB_COMPUVBYELASTICISOLINES
2131 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2133 } // loop on internal nodes
2134 #ifdef DEB_COMPUVBYELASTICISOLINES
2135 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2137 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2139 //MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2141 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2142 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2143 #ifndef DEB_COMPUVBYELASTICISOLINES
2148 // Set computed UV to points
2150 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2151 TPoint* point = *pIt;
2152 //gp_XY oldUV = point->myUV;
2153 double minDist = DBL_MAX;
2154 list < TIsoNode >::iterator nIt = nodes.begin();
2155 for ( ; nIt != nodes.end(); nIt++ ) {
2156 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2157 if ( dist < minDist ) {
2159 point->myUV = (*nIt).myUV;
2168 //=======================================================================
2169 //function : setFirstEdge
2170 //purpose : choose the best first edge of theWire; return the summary distance
2171 // between point UV computed by isolines intersection and
2172 // eventual UV got from edge p-curves
2173 //=======================================================================
2175 //#define DBG_SETFIRSTEDGE
2176 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2178 int iE, nbEdges = theWire.size();
2182 // Transform UVs computed by iso to fit bnd box of a wire
2184 // max nb of points on an edge
2186 int eID = theFirstEdgeID;
2187 for ( iE = 0; iE < nbEdges; iE++ )
2188 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2190 // compute bnd boxes
2191 TopoDS_Face face = TopoDS::Face( myShape );
2192 Bnd_Box2d bndBox, eBndBox;
2193 eID = theFirstEdgeID;
2194 list< TopoDS_Edge >::iterator eIt;
2195 list< TPoint* >::iterator pIt;
2196 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2198 // UV by isos stored in TPoint.myXYZ
2199 list< TPoint* > & ePoints = getShapePoints( eID++ );
2200 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2202 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2204 // UV by an edge p-curve
2206 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2207 double dU = ( l - f ) / ( maxNbPnt - 1 );
2208 for ( int i = 0; i < maxNbPnt; i++ )
2209 eBndBox.Add( C2d->Value( f + i * dU ));
2212 // transform UVs by isos
2213 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2214 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2215 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2216 #ifdef DBG_SETFIRSTEDGE
2217 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2218 << eMinPar[1] << " - " << eMaxPar[1] );
2220 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2222 double dMin = eMinPar[i] - minPar[i];
2223 double dMax = eMaxPar[i] - maxPar[i];
2224 double dPar = maxPar[i] - minPar[i];
2225 eID = theFirstEdgeID;
2226 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2228 list< TPoint* > & ePoints = getShapePoints( eID++ );
2229 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2231 double par = (*pIt)->myXYZ.Coord( iC );
2232 double r = ( par - minPar[i] ) / dPar;
2233 par += ( 1 - r ) * dMin + r * dMax;
2234 (*pIt)->myXYZ.SetCoord( iC, par );
2240 double minDist = DBL_MAX;
2241 for ( iE = 0 ; iE < nbEdges; iE++ )
2243 #ifdef DBG_SETFIRSTEDGE
2244 MESSAGE ( " VARIANT " << iE );
2246 // evaluate the distance between UV computed by the 2 methods:
2247 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2249 int eID = theFirstEdgeID;
2250 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2252 list< TPoint* > & ePoints = getShapePoints( eID++ );
2253 computeUVOnEdge( *eIt, ePoints );
2254 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2256 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2257 #ifdef DBG_SETFIRSTEDGE
2258 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2259 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2263 #ifdef DBG_SETFIRSTEDGE
2264 MESSAGE ( "dist -- " << dist );
2266 if ( dist < minDist ) {
2268 eBest = theWire.front();
2270 // check variant with another first edge
2271 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2273 // put the best first edge to the theWire front
2274 if ( eBest != theWire.front() ) {
2275 eIt = find ( theWire.begin(), theWire.end(), eBest );
2276 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2282 //=======================================================================
2283 //function : sortSameSizeWires
2284 //purpose : sort wires in theWireList from theFromWire until theToWire,
2285 // the wires are set in the order to correspond to the order
2286 // of boundaries; after sorting, edges in the wires are put
2287 // in a good order, point UVs on edges are computed and points
2288 // are appended to theEdgesPointsList
2289 //=======================================================================
2291 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2292 const TListOfEdgesList::iterator& theFromWire,
2293 const TListOfEdgesList::iterator& theToWire,
2294 const int theFirstEdgeID,
2295 list< list< TPoint* > >& theEdgesPointsList )
2297 TopoDS_Face F = TopoDS::Face( myShape );
2298 int iW, nbWires = 0;
2299 TListOfEdgesList::iterator wlIt = theFromWire;
2300 while ( wlIt++ != theToWire )
2303 // Recompute key-point UVs by isolines intersection,
2304 // compute CG of key-points for each wire and bnd boxes of GCs
2307 gp_XY orig( gp::Origin2d().XY() );
2308 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2309 Bnd_Box2d bndBox, vBndBox;
2310 int eID = theFirstEdgeID;
2311 list< TopoDS_Edge >::iterator eIt;
2312 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2314 list< TopoDS_Edge > & wire = *wlIt;
2315 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2317 list< TPoint* > & ePoints = getShapePoints( eID++ );
2318 TPoint* p = ePoints.front();
2319 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2320 MESSAGE("can't sortSameSizeWires()");
2323 gcVec[iW] += p->myUV;
2324 bndBox.Add( gp_Pnt2d( p->myUV ));
2325 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2326 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2327 vGcVec[iW] += vXY.XY();
2329 // keep the computed UV to compare against by setFirstEdge()
2330 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2332 gcVec[iW] /= nbWires;
2333 vGcVec[iW] /= nbWires;
2334 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2335 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2338 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2340 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2341 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2342 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2343 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2345 double dMin = vMinPar[i] - minPar[i];
2346 double dMax = vMaxPar[i] - maxPar[i];
2347 double dPar = maxPar[i] - minPar[i];
2348 if ( Abs( dPar ) <= DBL_MIN )
2350 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2351 double par = gcVec[iW].Coord( iC );
2352 double r = ( par - minPar[i] ) / dPar;
2353 par += ( 1 - r ) * dMin + r * dMax;
2354 gcVec[iW].SetCoord( iC, par );
2358 // Define boundary - wire correspondence by GC closeness
2360 TListOfEdgesList tmpWList;
2361 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2362 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2363 TIntWirePosMap bndIndWirePosMap;
2364 vector< bool > bndFound( nbWires, false );
2365 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2367 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2368 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2369 double minDist = DBL_MAX;
2370 gp_XY & wGc = vGcVec[ iW ];
2372 for ( int iB = 0; iB < nbWires; iB++ ) {
2373 if ( bndFound[ iB ] ) continue;
2374 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2375 if ( dist < minDist ) {
2380 bndFound[ bIndex ] = true;
2381 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2386 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2387 eID = theFirstEdgeID;
2388 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2390 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2391 list < TopoDS_Edge > & wire = ( *wirePos );
2393 // choose the best first edge of a wire
2394 setFirstEdge( wire, eID );
2396 // compute eventual UV and fill theEdgesPointsList
2397 theEdgesPointsList.push_back( list< TPoint* >() );
2398 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2399 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2401 list< TPoint* > & ePoints = getShapePoints( eID++ );
2402 computeUVOnEdge( *eIt, ePoints );
2403 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2405 // put wire back to theWireList
2407 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2413 //=======================================================================
2415 //purpose : Compute nodes coordinates applying
2416 // the loaded pattern to <theFace>. The first key-point
2417 // will be mapped into <theVertexOnKeyPoint1>
2418 //=======================================================================
2420 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2421 const TopoDS_Vertex& theVertexOnKeyPoint1,
2422 const bool theReverse)
2424 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2425 if ( !setShapeToMesh( face ))
2428 // find points on edges, it fills myNbKeyPntInBoundary
2429 if ( !findBoundaryPoints() )
2432 // Define the edges order so that the first edge starts at
2433 // theVertexOnKeyPoint1
2435 list< TopoDS_Edge > eList;
2436 list< int > nbVertexInWires;
2437 int nbWires = SMESH_Block::GetOrderedEdges( face, eList, nbVertexInWires, theVertexOnKeyPoint1);
2438 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2440 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2441 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2443 // check nb wires and edges
2444 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2445 l1.sort(); l2.sort();
2448 MESSAGE( "Wrong nb vertices in wires" );
2449 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2452 // here shapes get IDs, for the outer wire IDs are OK
2453 int nbVertices = loadVE( eList, myShapeIDMap );
2454 myShapeIDMap.Add( face );
2456 if ((int) myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2457 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2458 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2461 // points on edges to be used for UV computation of in-face points
2462 list< list< TPoint* > > edgesPointsList;
2463 edgesPointsList.push_back( list< TPoint* >() );
2464 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2465 list< TPoint* >::iterator pIt, pEnd;
2467 // compute UV of points on the outer wire
2468 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2469 list< TopoDS_Edge >::iterator elIt;
2470 for (iE = 0, elIt = eList.begin();
2471 iE < nbEdgesInOuterWire && elIt != eList.end();
2474 list< TPoint* > & ePoints = getShapePoints( *elIt );
2476 computeUVOnEdge( *elIt, ePoints );
2477 // collect on-edge points (excluding the last one)
2478 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2481 // If there are several wires, define the order of edges of inner wires:
2482 // compute UV of inner edge-points using 2 methods: the one for in-face points
2483 // and the one for on-edge points and then choose the best edge order
2484 // by the best correspondance of the 2 results
2487 // compute UV of inner edge-points using the method for in-face points
2488 // and divide eList into a list of separate wires
2490 list< list< TopoDS_Edge > > wireList;
2491 list<TopoDS_Edge>::iterator eIt = elIt;
2492 list<int>::iterator nbEIt = nbVertexInWires.begin();
2493 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2495 int nbEdges = *nbEIt;
2496 wireList.push_back( list< TopoDS_Edge >() );
2497 list< TopoDS_Edge > & wire = wireList.back();
2498 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2500 list< TPoint* > & ePoints = getShapePoints( *eIt );
2501 pIt = ePoints.begin();
2502 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2504 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2505 MESSAGE("can't Apply(face)");
2508 // keep the computed UV to compare against by setFirstEdge()
2509 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2511 wire.push_back( *eIt );
2514 // remove inner edges from eList
2515 eList.erase( elIt, eList.end() );
2517 // sort wireList by nb edges in a wire
2518 sortBySize< TopoDS_Edge > ( wireList );
2520 // an ID of the first edge of a boundary
2521 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2522 // if ( nbSeamShapes > 0 )
2523 // id1 += 2; // 2 vertices more
2525 // find points - edge correspondence for wires of unique size,
2526 // edge order within a wire should be defined only
2528 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2529 while ( wlIt != wireList.end() )
2531 list< TopoDS_Edge >& wire = (*wlIt);
2532 size_t nbEdges = wire.size();
2534 if ( wlIt != wireList.end() && (*wlIt).size() != nbEdges ) // a unique size wire
2536 // choose the best first edge of a wire
2537 setFirstEdge( wire, id1 );
2539 // compute eventual UV and collect on-edge points
2540 edgesPointsList.push_back( list< TPoint* >() );
2541 edgesPoints = & edgesPointsList.back();
2543 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2545 list< TPoint* > & ePoints = getShapePoints( eID++ );
2546 computeUVOnEdge( *eIt, ePoints );
2547 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2553 // find boundary - wire correspondence for several wires of same size
2555 id1 = nbVertices + nbEdgesInOuterWire + 1;
2556 wlIt = wireList.begin();
2557 while ( wlIt != wireList.end() )
2559 size_t nbSameSize = 0, nbEdges = (*wlIt).size();
2560 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2562 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2566 if ( nbSameSize > 0 )
2567 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2570 id1 += nbEdges * ( nbSameSize + 1 );
2573 // add well-ordered edges to eList
2575 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2577 list< TopoDS_Edge >& wire = (*wlIt);
2578 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2581 // re-fill myShapeIDMap - all shapes get good IDs
2583 myShapeIDMap.Clear();
2584 nbVertices = loadVE( eList, myShapeIDMap );
2585 myShapeIDMap.Add( face );
2587 } // there are inner wires
2589 // Set XYZ of on-vertex points
2591 // for ( int iV = 1; iV <= nbVertices; ++iV )
2593 // const TopoDS_Vertex& V = TopoDS::Vertex( myShapeIDMap( iV ));
2594 // list< TPoint* > & vPoints = getShapePoints( iV );
2595 // if ( !vPoints.empty() )
2597 // //vPoints.front()->myUV = BRep_Tool::Parameters( V, theFace ).XY();
2598 // vPoints.front()->myXYZ = BRep_Tool::Pnt( V );
2602 // Compute XYZ of on-edge points
2604 TopLoc_Location loc;
2605 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2607 BRepAdaptor_Curve C3d( *elIt );
2608 list< TPoint* > & ePoints = getShapePoints( iE++ );
2609 for ( pIt = ++ePoints.begin(), pEnd = ePoints.end(); pIt != pEnd; pIt++ )
2611 TPoint* point = *pIt;
2612 point->myXYZ = C3d.Value( point->myU );
2616 // Compute UV and XYZ of in-face points
2618 // try to use a simple algo
2619 list< TPoint* > & fPoints = getShapePoints( face );
2620 bool isDeformed = false;
2621 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2622 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2623 (*pIt)->myUV, isDeformed )) {
2624 MESSAGE("can't Apply(face)");
2627 // try to use a complex algo if it is a difficult case
2628 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2630 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2631 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2632 (*pIt)->myUV, isDeformed )) {
2633 MESSAGE("can't Apply(face)");
2638 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2639 const gp_Trsf & aTrsf = loc.Transformation();
2640 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2642 TPoint * point = *pIt;
2643 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2644 if ( !loc.IsIdentity() )
2645 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2648 myIsComputed = true;
2650 return setErrorCode( ERR_OK );
2653 //=======================================================================
2655 //purpose : Compute nodes coordinates applying
2656 // the loaded pattern to <theFace>. The first key-point
2657 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2658 //=======================================================================
2660 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2661 const int theNodeIndexOnKeyPoint1,
2662 const bool theReverse)
2664 // MESSAGE(" ::Apply(MeshFace) " );
2666 if ( !IsLoaded() ) {
2667 MESSAGE( "Pattern not loaded" );
2668 return setErrorCode( ERR_APPL_NOT_LOADED );
2671 // check nb of nodes
2672 const int nbFaceNodes = theFace->NbCornerNodes();
2673 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2674 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2675 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2678 // find points on edges, it fills myNbKeyPntInBoundary
2679 if ( !findBoundaryPoints() )
2682 // check that there are no holes in a pattern
2683 if (myNbKeyPntInBoundary.size() > 1 ) {
2684 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2687 // Define the nodes order
2689 list< const SMDS_MeshNode* > nodes;
2690 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2691 SMDS_NodeIteratorPtr noIt = theFace->nodeIterator();
2693 while ( noIt->more() && iSub < nbFaceNodes ) {
2694 const SMDS_MeshNode* node = noIt->next();
2695 nodes.push_back( node );
2696 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2699 if ( n != nodes.end() ) {
2701 if ( n != --nodes.end() )
2702 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2705 else if ( n != nodes.begin() )
2706 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2708 list< gp_XYZ > xyzList;
2709 myOrderedNodes.resize( nbFaceNodes );
2710 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2711 xyzList.push_back( SMESH_TNodeXYZ( *n ));
2712 myOrderedNodes[ iSub++] = *n;
2715 // Define a face plane
2717 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2718 gp_Pnt P ( *xyzIt++ );
2719 gp_Vec Vx( P, *xyzIt++ ), N;
2721 N = Vx ^ gp_Vec( P, *xyzIt++ );
2722 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2723 if ( N.SquareMagnitude() <= DBL_MIN )
2724 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2725 gp_Ax2 pos( P, N, Vx );
2727 // Compute UV of key-points on a plane
2728 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2730 gp_Vec vec ( pos.Location(), *xyzIt );
2731 TPoint* p = getShapePoints( iSub ).front();
2732 p->myUV.SetX( vec * pos.XDirection() );
2733 p->myUV.SetY( vec * pos.YDirection() );
2737 // points on edges to be used for UV computation of in-face points
2738 list< list< TPoint* > > edgesPointsList;
2739 edgesPointsList.push_back( list< TPoint* >() );
2740 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2741 list< TPoint* >::iterator pIt;
2743 // compute UV and XYZ of points on edges
2745 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2747 gp_XYZ& xyz1 = *xyzIt++;
2748 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2750 list< TPoint* > & ePoints = getShapePoints( iSub );
2751 ePoints.back()->myInitU = 1.0;
2752 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2753 while ( *pIt != ePoints.back() )
2756 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2757 gp_Vec vec ( pos.Location(), p->myXYZ );
2758 p->myUV.SetX( vec * pos.XDirection() );
2759 p->myUV.SetY( vec * pos.YDirection() );
2761 // collect on-edge points (excluding the last one)
2762 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2765 // Compute UV and XYZ of in-face points
2767 // try to use a simple algo to compute UV
2768 list< TPoint* > & fPoints = getShapePoints( iSub );
2769 bool isDeformed = false;
2770 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2771 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2772 (*pIt)->myUV, isDeformed )) {
2773 MESSAGE("can't Apply(face)");
2776 // try to use a complex algo if it is a difficult case
2777 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2779 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2780 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2781 (*pIt)->myUV, isDeformed )) {
2782 MESSAGE("can't Apply(face)");
2787 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2789 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2792 myIsComputed = true;
2794 return setErrorCode( ERR_OK );
2797 //=======================================================================
2799 //purpose : Compute nodes coordinates applying
2800 // the loaded pattern to <theFace>. The first key-point
2801 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2802 //=======================================================================
2804 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2805 const SMDS_MeshFace* theFace,
2806 const TopoDS_Shape& theSurface,
2807 const int theNodeIndexOnKeyPoint1,
2808 const bool theReverse)
2810 // MESSAGE(" ::Apply(MeshFace) " );
2811 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2812 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2814 const TopoDS_Face& face = TopoDS::Face( theSurface );
2815 TopLoc_Location loc;
2816 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2817 const gp_Trsf & aTrsf = loc.Transformation();
2819 if ( !IsLoaded() ) {
2820 MESSAGE( "Pattern not loaded" );
2821 return setErrorCode( ERR_APPL_NOT_LOADED );
2824 // check nb of nodes
2825 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2826 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2827 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2830 // find points on edges, it fills myNbKeyPntInBoundary
2831 if ( !findBoundaryPoints() )
2834 // check that there are no holes in a pattern
2835 if (myNbKeyPntInBoundary.size() > 1 ) {
2836 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2839 // Define the nodes order
2841 list< const SMDS_MeshNode* > nodes;
2842 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2843 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2845 while ( noIt->more() ) {
2846 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2847 nodes.push_back( node );
2848 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2851 if ( n != nodes.end() ) {
2853 if ( n != --nodes.end() )
2854 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2857 else if ( n != nodes.begin() )
2858 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2861 // find a node not on a seam edge, if necessary
2862 SMESH_MesherHelper helper( *theMesh );
2863 helper.SetSubShape( theSurface );
2864 const SMDS_MeshNode* inFaceNode = 0;
2865 if ( helper.GetNodeUVneedInFaceNode() )
2867 SMESH_MeshEditor editor( theMesh );
2868 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2869 int shapeID = editor.FindShape( *n );
2871 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2872 if ( !helper.IsSeamShape( shapeID ))
2877 // Set UV of key-points (i.e. of nodes of theFace )
2878 vector< gp_XY > keyUV( theFace->NbNodes() );
2879 myOrderedNodes.resize( theFace->NbNodes() );
2880 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2882 TPoint* p = getShapePoints( iSub ).front();
2883 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2884 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2886 keyUV[ iSub-1 ] = p->myUV;
2887 myOrderedNodes[ iSub-1 ] = *n;
2890 // points on edges to be used for UV computation of in-face points
2891 list< list< TPoint* > > edgesPointsList;
2892 edgesPointsList.push_back( list< TPoint* >() );
2893 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2894 list< TPoint* >::iterator pIt;
2896 // compute UV and XYZ of points on edges
2898 for ( size_t i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2900 gp_XY& uv1 = keyUV[ i ];
2901 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2903 list< TPoint* > & ePoints = getShapePoints( iSub );
2904 ePoints.back()->myInitU = 1.0;
2905 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2906 while ( *pIt != ePoints.back() )
2909 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2910 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2911 if ( !loc.IsIdentity() )
2912 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2914 // collect on-edge points (excluding the last one)
2915 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2918 // Compute UV and XYZ of in-face points
2920 // try to use a simple algo to compute UV
2921 list< TPoint* > & fPoints = getShapePoints( iSub );
2922 bool isDeformed = false;
2923 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2924 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2925 (*pIt)->myUV, isDeformed )) {
2926 MESSAGE("can't Apply(face)");
2929 // try to use a complex algo if it is a difficult case
2930 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2932 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2933 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2934 (*pIt)->myUV, isDeformed )) {
2935 MESSAGE("can't Apply(face)");
2940 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2942 TPoint * point = *pIt;
2943 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2944 if ( !loc.IsIdentity() )
2945 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2948 myIsComputed = true;
2950 return setErrorCode( ERR_OK );
2953 //=======================================================================
2954 //function : undefinedXYZ
2956 //=======================================================================
2958 static const gp_XYZ& undefinedXYZ()
2960 static gp_XYZ xyz( 1.e100, 0., 0. );
2964 //=======================================================================
2965 //function : isDefined
2967 //=======================================================================
2969 inline static bool isDefined(const gp_XYZ& theXYZ)
2971 return theXYZ.X() < 1.e100;
2974 //=======================================================================
2976 //purpose : Compute nodes coordinates applying
2977 // the loaded pattern to <theFaces>. The first key-point
2978 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2979 //=======================================================================
2981 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2982 std::set<const SMDS_MeshFace*>& theFaces,
2983 const int theNodeIndexOnKeyPoint1,
2984 const bool theReverse)
2986 MESSAGE(" ::Apply(set<MeshFace>) " );
2988 if ( !IsLoaded() ) {
2989 MESSAGE( "Pattern not loaded" );
2990 return setErrorCode( ERR_APPL_NOT_LOADED );
2993 // find points on edges, it fills myNbKeyPntInBoundary
2994 if ( !findBoundaryPoints() )
2997 // check that there are no holes in a pattern
2998 if (myNbKeyPntInBoundary.size() > 1 ) {
2999 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3004 myElemXYZIDs.clear();
3005 myXYZIdToNodeMap.clear();
3007 myIdsOnBoundary.clear();
3008 myReverseConnectivity.clear();
3010 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
3011 myElements.reserve( theFaces.size() );
3013 int ind1 = 0; // lowest point index for a face
3018 // SMESH_MeshEditor editor( theMesh );
3020 // apply to each face in theFaces set
3021 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
3022 for ( ; face != theFaces.end(); ++face )
3024 // int curShapeId = editor.FindShape( *face );
3025 // if ( curShapeId != shapeID ) {
3026 // if ( curShapeId )
3027 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
3030 // shapeID = curShapeId;
3033 if ( shape.IsNull() )
3034 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
3036 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
3038 MESSAGE( "Failed on " << *face );
3041 myElements.push_back( *face );
3043 // store computed points belonging to elements
3044 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3045 for ( ; ll != myElemPointIDs.end(); ++ll )
3047 myElemXYZIDs.push_back(TElemDef());
3048 TElemDef& xyzIds = myElemXYZIDs.back();
3049 TElemDef& pIds = *ll;
3050 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3051 int pIndex = *id + ind1;
3052 xyzIds.push_back( pIndex );
3053 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3054 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3057 // put points on links to myIdsOnBoundary,
3058 // they will be used to sew new elements on adjacent refined elements
3059 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3060 for ( int i = 0; i < nbNodes; i++ )
3062 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3063 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3064 const SMDS_MeshNode* n2 = myOrderedNodes[( i+1 ) % nbNodes ];
3065 // make a link and a node set
3066 TNodeSet linkSet, node1Set;
3067 linkSet.insert( n1 );
3068 linkSet.insert( n2 );
3069 node1Set.insert( n1 );
3070 list< TPoint* >::iterator p = linkPoints.begin();
3072 // map the first link point to n1
3073 int nId = ( *p - &myPoints[0] ) + ind1;
3074 myXYZIdToNodeMap[ nId ] = n1;
3075 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3076 groups.push_back(list< int > ());
3077 groups.back().push_back( nId );
3079 // add the linkSet to the map
3080 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3081 groups.push_back(list< int > ());
3082 list< int >& indList = groups.back();
3083 // add points to the map excluding the end points
3084 for ( p++; *p != linkPoints.back(); p++ )
3085 indList.push_back( ( *p - &myPoints[0] ) + ind1 );
3087 ind1 += myPoints.size();
3090 return !myElemXYZIDs.empty();
3093 //=======================================================================
3095 //purpose : Compute nodes coordinates applying
3096 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3097 // will be mapped into <theNode000Index>-th node. The
3098 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3100 //=======================================================================
3102 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3103 const int theNode000Index,
3104 const int theNode001Index)
3106 if ( !IsLoaded() ) {
3107 MESSAGE( "Pattern not loaded" );
3108 return setErrorCode( ERR_APPL_NOT_LOADED );
3111 // bind ID to points
3112 if ( !findBoundaryPoints() )
3115 // check that there are no holes in a pattern
3116 if (myNbKeyPntInBoundary.size() > 1 ) {
3117 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3122 myElemXYZIDs.clear();
3123 myXYZIdToNodeMap.clear();
3125 myIdsOnBoundary.clear();
3126 myReverseConnectivity.clear();
3128 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3129 myElements.reserve( theVolumes.size() );
3131 // to find point index
3132 map< TPoint*, int > pointIndex;
3133 for ( size_t i = 0; i < myPoints.size(); i++ )
3134 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3136 int ind1 = 0; // lowest point index for an element
3138 // apply to each element in theVolumes set
3139 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3140 for ( ; vol != theVolumes.end(); ++vol )
3142 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3143 MESSAGE( "Failed on " << *vol );
3146 myElements.push_back( *vol );
3148 // store computed points belonging to elements
3149 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3150 for ( ; ll != myElemPointIDs.end(); ++ll )
3152 myElemXYZIDs.push_back(TElemDef());
3153 TElemDef& xyzIds = myElemXYZIDs.back();
3154 TElemDef& pIds = *ll;
3155 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3156 int pIndex = *id + ind1;
3157 xyzIds.push_back( pIndex );
3158 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3159 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3162 // put points on edges and faces to myIdsOnBoundary,
3163 // they will be used to sew new elements on adjacent refined elements
3164 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3166 // make a set of sub-points
3168 vector< int > subIDs;
3169 if ( SMESH_Block::IsVertexID( Id )) {
3170 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3172 else if ( SMESH_Block::IsEdgeID( Id )) {
3173 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3174 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3175 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3178 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3179 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3180 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3181 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3182 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3183 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3184 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3185 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3188 list< TPoint* > & points = getShapePoints( Id );
3189 list< TPoint* >::iterator p = points.begin();
3190 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3191 groups.push_back(list< int > ());
3192 list< int >& indList = groups.back();
3193 for ( ; p != points.end(); p++ )
3194 indList.push_back( pointIndex[ *p ] + ind1 );
3195 if ( subNodes.size() == 1 ) // vertex case
3196 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3198 ind1 += myPoints.size();
3201 return !myElemXYZIDs.empty();
3204 //=======================================================================
3206 //purpose : Create a pattern from the mesh built on <theBlock>
3207 //=======================================================================
3209 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3210 const TopoDS_Shell& theBlock,
3215 myToKeepNodes = theKeepNodes;
3216 SMESHDS_SubMesh * aSubMesh;
3218 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3220 // load shapes in myShapeIDMap
3222 TopoDS_Vertex v1, v2;
3223 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3224 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3227 int nbNodes = 0, shapeID;
3228 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3230 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3231 aSubMesh = getSubmeshWithElements( theMesh, S );
3233 nbNodes += aSubMesh->NbNodes();
3235 myPoints.resize( nbNodes );
3237 // load U of points on edges
3238 TNodePointIDMap nodePointIDMap;
3240 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3242 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3243 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3244 aSubMesh = getSubmeshWithElements( theMesh, S );
3245 if ( ! aSubMesh ) continue;
3246 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3247 if ( !nIt->more() ) continue;
3249 // store a node and a point
3250 while ( nIt->more() ) {
3251 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3252 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3254 nodePointIDMap.insert( make_pair( node, iPoint ));
3255 if ( block.IsVertexID( shapeID ))
3256 myKeyPointIDs.push_back( iPoint );
3257 TPoint* p = & myPoints[ iPoint++ ];
3258 shapePoints.push_back( p );
3259 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3260 p->myInitXYZ.SetCoord( 0,0,0 );
3262 list< TPoint* >::iterator pIt = shapePoints.begin();
3265 switch ( S.ShapeType() )
3270 for ( ; pIt != shapePoints.end(); pIt++ ) {
3271 double * coef = block.GetShapeCoef( shapeID );
3272 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3273 if ( coef[ iCoord - 1] > 0 )
3274 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3276 if ( S.ShapeType() == TopAbs_VERTEX )
3279 const TopoDS_Edge& edge = TopoDS::Edge( S );
3281 BRep_Tool::Range( edge, f, l );
3282 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3283 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3284 pIt = shapePoints.begin();
3285 nIt = aSubMesh->GetNodes();
3286 for ( ; nIt->more(); pIt++ )
3288 const SMDS_MeshNode* node = nIt->next();
3289 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3291 const SMDS_EdgePosition* epos =
3292 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3293 double u = ( epos->GetUParameter() - f ) / ( l - f );
3294 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3299 for ( ; pIt != shapePoints.end(); pIt++ )
3301 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3302 MESSAGE( "!block.ComputeParameters()" );
3303 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3307 } // loop on block sub-shapes
3311 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3314 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3315 while ( elemIt->more() ) {
3316 const SMDS_MeshElement* elem = elemIt->next();
3317 myElemPointIDs.push_back( TElemDef() );
3318 TElemDef& elemPoints = myElemPointIDs.back();
3319 int nbNodes = elem->NbCornerNodes();
3320 for ( int i = 0;i < nbNodes; ++i )
3321 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3325 myIsBoundaryPointsFound = true;
3327 if ( myToKeepNodes )
3329 myInNodes.resize( nodePointIDMap.size() );
3330 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
3331 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
3332 myInNodes[ nIdIt->second ] = smdsNode( nIdIt->first );
3335 return setErrorCode( ERR_OK );
3338 //=======================================================================
3339 //function : getSubmeshWithElements
3340 //purpose : return submesh containing elements bound to theBlock in theMesh
3341 //=======================================================================
3343 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3344 const TopoDS_Shape& theShape)
3346 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3347 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3350 if ( theShape.ShapeType() == TopAbs_SHELL )
3352 // look for submesh of VOLUME
3353 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3354 for (; it.More(); it.Next()) {
3355 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3356 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3364 //=======================================================================
3366 //purpose : Compute nodes coordinates applying
3367 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3368 // will be mapped into <theVertex000>. The (0,0,1)
3369 // fifth key-point will be mapped into <theVertex001>.
3370 //=======================================================================
3372 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3373 const TopoDS_Vertex& theVertex000,
3374 const TopoDS_Vertex& theVertex001)
3376 if (!findBoundaryPoints() || // bind ID to points
3377 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3380 SMESH_Block block; // bind ID to shape
3381 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3382 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3384 // compute XYZ of points on shapes
3386 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3388 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3389 list< TPoint* >::iterator pIt = shapePoints.begin();
3390 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3391 switch ( S.ShapeType() )
3393 case TopAbs_VERTEX: {
3395 for ( ; pIt != shapePoints.end(); pIt++ )
3396 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3401 for ( ; pIt != shapePoints.end(); pIt++ )
3402 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3407 for ( ; pIt != shapePoints.end(); pIt++ )
3408 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3412 for ( ; pIt != shapePoints.end(); pIt++ )
3413 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3415 } // loop on block sub-shapes
3417 myIsComputed = true;
3419 return setErrorCode( ERR_OK );
3422 //=======================================================================
3424 //purpose : Compute nodes coordinates applying
3425 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3426 // will be mapped into <theNode000Index>-th node. The
3427 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3429 //=======================================================================
3431 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3432 const int theNode000Index,
3433 const int theNode001Index)
3435 if (!findBoundaryPoints()) // bind ID to points
3438 SMESH_Block block; // bind ID to shape
3439 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3440 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3441 // compute XYZ of points on shapes
3443 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3445 list< TPoint* > & shapePoints = getShapePoints( ID );
3446 list< TPoint* >::iterator pIt = shapePoints.begin();
3448 if ( block.IsVertexID( ID ))
3449 for ( ; pIt != shapePoints.end(); pIt++ ) {
3450 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3452 else if ( block.IsEdgeID( ID ))
3453 for ( ; pIt != shapePoints.end(); pIt++ ) {
3454 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3456 else if ( block.IsFaceID( ID ))
3457 for ( ; pIt != shapePoints.end(); pIt++ ) {
3458 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3461 for ( ; pIt != shapePoints.end(); pIt++ )
3462 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3463 } // loop on block sub-shapes
3465 myIsComputed = true;
3467 return setErrorCode( ERR_OK );
3470 //=======================================================================
3471 //function : mergePoints
3472 //purpose : Merge XYZ on edges and/or faces.
3473 //=======================================================================
3475 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3477 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3478 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3480 list<list< int > >& groups = idListIt->second;
3481 if ( groups.size() < 2 )
3485 const TNodeSet& nodes = idListIt->first;
3486 double tol2 = 1.e-10;
3487 if ( nodes.size() > 1 ) {
3489 TNodeSet::const_iterator n = nodes.begin();
3490 for ( ; n != nodes.end(); ++n )
3491 box.Add( gp_Pnt( SMESH_TNodeXYZ( *n )));
3492 double x, y, z, X, Y, Z;
3493 box.Get( x, y, z, X, Y, Z );
3494 gp_Pnt p( x, y, z ), P( X, Y, Z );
3495 tol2 = 1.e-4 * p.SquareDistance( P );
3498 // to unite groups on link
3499 bool unite = ( uniteGroups && nodes.size() == 2 );
3500 map< double, int > distIndMap;
3501 const SMDS_MeshNode* node = *nodes.begin();
3502 gp_Pnt P = SMESH_TNodeXYZ( node );
3504 // compare points, replace indices
3506 list< int >::iterator ind1, ind2;
3507 list< list< int > >::iterator grpIt1, grpIt2;
3508 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3510 list< int >& indices1 = *grpIt1;
3512 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3514 list< int >& indices2 = *grpIt2;
3515 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3517 gp_XYZ& p1 = myXYZ[ *ind1 ];
3518 ind2 = indices2.begin();
3519 while ( ind2 != indices2.end() )
3521 gp_XYZ& p2 = myXYZ[ *ind2 ];
3522 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3523 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3525 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3526 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3527 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3528 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3530 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3531 myXYZ[ *ind2 ] = undefinedXYZ();
3532 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3534 ind2 = indices2.erase( ind2 );
3541 if ( unite ) { // sort indices using distIndMap
3542 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3544 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3545 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3546 distIndMap.insert( make_pair( dist, *ind1 ));
3550 if ( unite ) { // put all sorted indices into the first group
3551 list< int >& g = groups.front();
3553 map< double, int >::iterator dist_ind = distIndMap.begin();
3554 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3555 g.push_back( dist_ind->second );
3557 } // loop on myIdsOnBoundary
3560 //=======================================================================
3561 //function : makePolyElements
3562 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3563 //=======================================================================
3565 void SMESH_Pattern::
3566 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3567 const bool toCreatePolygons,
3568 const bool toCreatePolyedrs)
3570 myPolyElemXYZIDs.clear();
3571 myPolyElems.clear();
3572 myPolyElems.reserve( myIdsOnBoundary.size() );
3574 // make a set of refined elements
3575 TIDSortedElemSet elemSet, avoidSet( myElements.begin(), myElements.end() );
3577 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3579 if ( toCreatePolygons )
3581 int lastFreeId = myXYZ.size();
3583 // loop on links of refined elements
3584 indListIt = myIdsOnBoundary.begin();
3585 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3587 const TNodeSet & linkNodes = indListIt->first;
3588 if ( linkNodes.size() != 2 )
3589 continue; // skip face
3590 const SMDS_MeshNode* n1 = * linkNodes.begin();
3591 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3593 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3594 if ( idGroups.empty() || idGroups.front().empty() )
3597 // find not refined face having n1-n2 link
3601 const SMDS_MeshElement* face =
3602 SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3605 avoidSet.insert ( face );
3606 myPolyElems.push_back( face );
3608 // some links of <face> are split;
3609 // make list of xyz for <face>
3610 myPolyElemXYZIDs.push_back(TElemDef());
3611 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3612 // loop on links of a <face>
3613 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3614 int i = 0, nbNodes = face->NbNodes();
3615 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3616 while ( nIt->more() )
3617 nodes[ i++ ] = smdsNode( nIt->next() );
3618 nodes[ i ] = nodes[ 0 ];
3619 for ( i = 0; i < nbNodes; ++i )
3621 // look for point mapped on a link
3622 TNodeSet faceLinkNodes;
3623 faceLinkNodes.insert( nodes[ i ] );
3624 faceLinkNodes.insert( nodes[ i + 1 ] );
3625 if ( faceLinkNodes == linkNodes )
3626 nn_IdList = indListIt;
3628 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3629 // add face point ids
3630 faceNodeIds.push_back( ++lastFreeId );
3631 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3632 if ( nn_IdList != myIdsOnBoundary.end() )
3634 // there are points mapped on a link
3635 list< int >& mappedIds = nn_IdList->second.front();
3636 if ( isReversed( nodes[ i ], mappedIds ))
3637 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3639 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3641 } // loop on links of a <face>
3647 if ( myIs2D && idGroups.size() > 1 ) {
3649 // sew new elements on 2 refined elements sharing n1-n2 link
3651 list< int >& idsOnLink = idGroups.front();
3652 // temporarily add ids of link nodes to idsOnLink
3653 bool rev = isReversed( n1, idsOnLink );
3654 for ( int i = 0; i < 2; ++i )
3657 nodeSet.insert( i ? n2 : n1 );
3658 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3659 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3660 int nodeId = groups.front().front();
3662 if ( rev ) append = !append;
3664 idsOnLink.push_back( nodeId );
3666 idsOnLink.push_front( nodeId );
3668 list< int >::iterator id = idsOnLink.begin();
3669 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3671 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3672 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3673 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3675 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3676 // look for <id> in element definition
3677 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3678 ASSERT ( idDef != pIdList->end() );
3679 // look for 2 neighbour ids of <id> in element definition
3680 for ( int prev = 0; prev < 2; ++prev ) {
3681 TElemDef::iterator idDef2 = idDef;
3683 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3685 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3686 // look for idDef2 on a link starting from id
3687 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3688 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3689 // insert ids located on link between <id> and <id2>
3690 // into the element definition between idDef and idDef2
3692 for ( ; id2 != id; --id2 )
3693 pIdList->insert( idDef, *id2 );
3695 list< int >::iterator id1 = id;
3696 for ( ++id1, ++id2; id1 != id2; ++id1 )
3697 pIdList->insert( idDef2, *id1 );
3703 // remove ids of link nodes
3704 idsOnLink.pop_front();
3705 idsOnLink.pop_back();
3707 } // loop on myIdsOnBoundary
3708 } // if ( toCreatePolygons )
3710 if ( toCreatePolyedrs )
3712 // check volumes adjacent to the refined elements
3713 SMDS_VolumeTool volTool;
3714 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3715 for ( ; refinedElem != myElements.end(); ++refinedElem )
3717 // loop on nodes of refinedElem
3718 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3719 while ( nIt->more() ) {
3720 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3721 // loop on inverse elements of node
3722 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3723 while ( eIt->more() )
3725 const SMDS_MeshElement* elem = eIt->next();
3726 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3727 continue; // skip faces or refined elements
3728 // add polyhedron definition
3729 myPolyhedronQuantities.push_back(vector<int> ());
3730 myPolyElemXYZIDs.push_back(TElemDef());
3731 vector<int>& quantity = myPolyhedronQuantities.back();
3732 TElemDef & elemDef = myPolyElemXYZIDs.back();
3733 // get definitions of new elements on volume faces
3734 bool makePoly = false;
3735 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3737 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3738 volTool.NbFaceNodes( iF ),
3739 theNodes, elemDef, quantity))
3743 myPolyElems.push_back( elem );
3745 myPolyhedronQuantities.pop_back();
3746 myPolyElemXYZIDs.pop_back();
3754 //=======================================================================
3755 //function : getFacesDefinition
3756 //purpose : return faces definition for a volume face defined by theBndNodes
3757 //=======================================================================
3759 bool SMESH_Pattern::
3760 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3761 const int theNbBndNodes,
3762 const vector< const SMDS_MeshNode* >& theNodes,
3763 list< int >& theFaceDefs,
3764 vector<int>& theQuantity)
3766 bool makePoly = false;
3768 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3770 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3772 // make a set of all nodes on a face
3774 if ( !myIs2D ) { // for 2D, merge only edges
3775 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3776 if ( nn_IdList != myIdsOnBoundary.end() ) {
3777 list< int > & faceIds = nn_IdList->second.front();
3778 if ( !faceIds.empty() ) {
3780 ids.insert( faceIds.begin(), faceIds.end() );
3785 // add ids on links and bnd nodes
3786 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3787 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3788 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3790 // add id of iN-th bnd node
3792 nSet.insert( theBndNodes[ iN ] );
3793 nn_IdList = myIdsOnBoundary.find( nSet );
3794 int bndId = ++lastFreeId;
3795 if ( nn_IdList != myIdsOnBoundary.end() ) {
3796 bndId = nn_IdList->second.front().front();
3797 ids.insert( bndId );
3800 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3802 faceDef.push_back( bndId );
3803 // add ids on a link
3805 linkNodes.insert( theBndNodes[ iN ]);
3806 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3807 nn_IdList = myIdsOnBoundary.find( linkNodes );
3808 if ( nn_IdList != myIdsOnBoundary.end() ) {
3809 list< int > & linkIds = nn_IdList->second.front();
3810 if ( !linkIds.empty() )
3813 ids.insert( linkIds.begin(), linkIds.end() );
3814 if ( isReversed( theBndNodes[ iN ], linkIds ))
3815 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3817 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3822 // find faces definition of new volumes
3824 bool defsAdded = false;
3825 if ( !myIs2D ) { // for 2D, merge only edges
3826 SMDS_VolumeTool vol;
3827 set< TElemDef* > checkedVolDefs;
3828 set< int >::iterator id = ids.begin();
3829 for ( ; id != ids.end(); ++id )
3831 // definitions of volumes sharing id
3832 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3833 ASSERT( !defList.empty() );
3834 // loop on volume definitions
3835 list< TElemDef* >::iterator pIdList = defList.begin();
3836 for ( ; pIdList != defList.end(); ++pIdList)
3838 if ( !checkedVolDefs.insert( *pIdList ).second )
3839 continue; // skip already checked volume definition
3840 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3841 // loop on face defs of a volume
3842 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3843 if ( volType == SMDS_VolumeTool::UNKNOWN )
3845 int nbFaces = vol.NbFaces( volType );
3846 for ( int iF = 0; iF < nbFaces; ++iF )
3848 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3849 int iN, nbN = vol.NbFaceNodes( volType, iF );
3850 // check if all nodes of a faces are in <ids>
3852 for ( iN = 0; iN < nbN && all; ++iN ) {
3853 int nodeId = idVec[ nodeInds[ iN ]];
3854 all = ( ids.find( nodeId ) != ids.end() );
3857 // store a face definition
3858 for ( iN = 0; iN < nbN; ++iN ) {
3859 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3861 theQuantity.push_back( nbN );
3869 theQuantity.push_back( faceDef.size() );
3870 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3876 //=======================================================================
3877 //function : clearSubMesh
3879 //=======================================================================
3881 static bool clearSubMesh( SMESH_Mesh* theMesh,
3882 const TopoDS_Shape& theShape)
3884 bool removed = false;
3885 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3887 removed = !aSubMesh->IsEmpty();
3889 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3892 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3893 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3895 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3896 removed = eIt->more();
3897 while ( eIt->more() )
3898 aMeshDS->RemoveElement( eIt->next() );
3899 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3900 removed = removed || nIt->more();
3901 while ( nIt->more() )
3902 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3908 //=======================================================================
3909 //function : clearMesh
3910 //purpose : clear mesh elements existing on myShape in theMesh
3911 //=======================================================================
3913 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3916 if ( !myShape.IsNull() )
3918 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3919 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3920 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3922 clearSubMesh( theMesh, it.Value() );
3928 //=======================================================================
3929 //function : findExistingNodes
3930 //purpose : fills nodes vector with nodes existing on a given shape (IMP 22368)
3931 // Returns true if all nodes for all points on S are found
3932 //=======================================================================
3934 bool SMESH_Pattern::findExistingNodes( SMESH_Mesh* mesh,
3935 const TopoDS_Shape& S,
3936 const std::list< TPoint* > & points,
3937 vector< const SMDS_MeshNode* > & nodesVector)
3939 if ( S.IsNull() || points.empty() )
3942 SMESHDS_Mesh* aMeshDS = mesh->GetMeshDS();
3944 switch ( S.ShapeType() )
3948 int pIndex = points.back() - &myPoints[0];
3949 if ( !nodesVector[ pIndex ] )
3950 nodesVector[ pIndex ] = SMESH_Algo::VertexNode( TopoDS::Vertex( S ), aMeshDS );
3951 return nodesVector[ pIndex ];
3955 const TopoDS_Edge& edge = TopoDS::Edge( S );
3956 map< double, const SMDS_MeshNode* > paramsOfNodes;
3957 if ( !SMESH_Algo::GetSortedNodesOnEdge( aMeshDS, edge,
3958 /*ignoreMediumNodes=*/false,
3960 || paramsOfNodes.size() < 3 )
3962 // points on VERTEXes are included with wrong myU
3963 list< TPoint* >::const_reverse_iterator pItR = ++points.rbegin();
3964 list< TPoint* >::const_iterator pItF = ++points.begin();
3965 const bool isForward = ( (*pItF)->myU < (*pItR)->myU );
3966 map< double, const SMDS_MeshNode* >::iterator u2n = ++paramsOfNodes.begin();
3967 map< double, const SMDS_MeshNode* >::iterator u2nEnd = --paramsOfNodes.end();
3969 if ( paramsOfNodes.size() == points.size() )
3971 for ( ; u2n != u2nEnd; ++u2n )
3973 p = ( isForward ? *pItF : *pItR );
3974 int pIndex = p - &myPoints[0];
3975 if ( !nodesVector [ pIndex ] )
3976 nodesVector [ pIndex ] = u2n->second;
3984 const double tolFact = 0.05;
3985 while ( u2n != u2nEnd && pItF != points.end() )
3987 const double u = u2n->first;
3988 const SMDS_MeshNode* n = u2n->second;
3989 const double tol = ( (++u2n)->first - u ) * tolFact;
3992 p = ( isForward ? *pItF : *pItR );
3993 if ( Abs( u - p->myU ) < tol )
3995 int pIndex = p - &myPoints[0];
3996 if ( !nodesVector [ pIndex ] )
3997 nodesVector [ pIndex ] = n;
4003 while ( p->myU < u && ( ++pItF, ++pItR != points.rend() ));
4007 } // case TopAbs_EDGE:
4010 } // switch ( S.ShapeType() )
4015 //=======================================================================
4016 //function : MakeMesh
4017 //purpose : Create nodes and elements in <theMesh> using nodes
4018 // coordinates computed by either of Apply...() methods
4019 //=======================================================================
4021 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
4022 const bool toCreatePolygons,
4023 const bool toCreatePolyedrs)
4025 if ( !myIsComputed )
4026 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
4028 mergePoints( toCreatePolygons );
4030 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4032 // clear elements and nodes existing on myShape
4035 bool onMeshElements = ( !myElements.empty() );
4037 // Create missing nodes
4039 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
4040 if ( onMeshElements )
4042 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
4043 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
4044 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
4045 nodesVector[ i_node->first ] = i_node->second;
4047 for ( size_t i = 0; i < myXYZ.size(); ++i ) {
4048 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
4049 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
4053 if ( theMesh->HasShapeToMesh() )
4055 // set nodes on EDGEs (IMP 22368)
4056 SMESH_MesherHelper helper( *theMesh );
4057 helper.ToFixNodeParameters( true );
4058 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
4059 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
4061 list<list< int > >& groups = idListIt->second;
4062 const TNodeSet& nodes = idListIt->first;
4063 if ( nodes.size() != 2 )
4064 continue; // not a link
4065 const SMDS_MeshNode* n1 = *nodes.begin();
4066 const SMDS_MeshNode* n2 = *nodes.rbegin();
4067 TopoDS_Shape S1 = helper.GetSubShapeByNode( n1, aMeshDS );
4068 TopoDS_Shape S2 = helper.GetSubShapeByNode( n2, aMeshDS );
4069 if ( S1.IsNull() || S1.ShapeType() < TopAbs_EDGE ||
4070 S2.IsNull() || S2.ShapeType() < TopAbs_EDGE )
4073 if ( S1.ShapeType() == TopAbs_EDGE )
4075 if ( S1 == S2 || helper.IsSubShape( S2, S1 ))
4078 else if ( S2.ShapeType() == TopAbs_EDGE )
4080 if ( helper.IsSubShape( S1, S2 ))
4085 S = helper.GetCommonAncestor( S1, S2, *theMesh, TopAbs_EDGE );
4089 const TopoDS_Edge & E = TopoDS::Edge( S );
4090 helper.SetSubShape( E );
4091 list<list< int > >::iterator g = groups.begin();
4092 for ( ; g != groups.end(); ++g )
4094 list< int >& ids = *g;
4095 list< int >::iterator id = ids.begin();
4096 for ( ; id != ids.end(); ++id )
4097 if ( nodesVector[ *id ] && nodesVector[ *id ]->getshapeId() < 1 )
4100 aMeshDS->SetNodeOnEdge( nodesVector[ *id ], E, u );
4101 helper.CheckNodeU( E, nodesVector[ *id ], u, 1e-7, true );
4106 } // if ( onMeshElements )
4110 nodesVector.resize( myPoints.size(), 0 );
4112 // loop on sub-shapes of myShape: create nodes
4113 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
4114 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
4116 list< TPoint* > & points = idPointIt->second;
4118 if ( !myShapeIDMap.IsEmpty() )
4119 S = myShapeIDMap( idPointIt->first );
4121 // find existing nodes on EDGEs and VERTEXes
4122 if ( findExistingNodes( theMesh, S, points, nodesVector ))
4125 list< TPoint* >::iterator pIt = points.begin();
4126 for ( ; pIt != points.end(); pIt++ )
4128 TPoint* point = *pIt;
4129 int pIndex = point - &myPoints[0];
4130 if ( nodesVector [ pIndex ] )
4132 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
4135 nodesVector [ pIndex ] = node;
4137 if ( !S.IsNull() ) {
4139 switch ( S.ShapeType() ) {
4140 case TopAbs_VERTEX: {
4141 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
4144 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
4147 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
4148 point->myUV.X(), point->myUV.Y() ); break;
4151 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
4160 if ( onMeshElements )
4162 // prepare data to create poly elements
4163 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
4166 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
4167 // sew old and new elements
4168 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
4172 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4175 aMeshDS->compactMesh();
4177 if ( myToKeepNodes )
4178 myOutNodes.swap( nodesVector );
4180 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4181 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4182 // for ( ; i_sm != sm.end(); i_sm++ )
4184 // cout << " SM " << i_sm->first << " ";
4185 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4186 // //SMDS_ElemIteratorPtr GetElements();
4187 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4188 // while ( nit->more() )
4189 // cout << nit->next()->GetID() << " ";
4192 return setErrorCode( ERR_OK );
4195 //=======================================================================
4196 //function : createElements
4197 //purpose : add elements to the mesh
4198 //=======================================================================
4200 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4201 const vector<const SMDS_MeshNode* >& theNodesVector,
4202 const list< TElemDef > & theElemNodeIDs,
4203 const vector<const SMDS_MeshElement*>& theElements)
4205 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4206 SMESH_MeshEditor editor( theMesh );
4208 bool onMeshElements = !theElements.empty();
4210 // shapes and groups theElements are on
4211 vector< int > shapeIDs;
4212 vector< list< SMESHDS_Group* > > groups;
4213 set< const SMDS_MeshNode* > shellNodes;
4214 if ( onMeshElements )
4216 shapeIDs.resize( theElements.size() );
4217 groups.resize( theElements.size() );
4218 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4219 set<SMESHDS_GroupBase*>::const_iterator grIt;
4220 for ( size_t i = 0; i < theElements.size(); i++ )
4222 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4223 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4224 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4225 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4226 groups[ i ].push_back( group );
4229 // get all nodes bound to shells because their SpacePosition is not set
4230 // by SMESHDS_Mesh::SetNodeInVolume()
4231 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4232 if ( !aMainShape.IsNull() ) {
4233 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4234 for ( ; shellExp.More(); shellExp.Next() )
4236 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4238 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4239 while ( nIt->more() )
4240 shellNodes.insert( nIt->next() );
4245 // nb new elements per a refined element
4246 int nbNewElemsPerOld = 1;
4247 if ( onMeshElements )
4248 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4252 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4253 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4254 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4256 const TElemDef & elemNodeInd = *enIt;
4258 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4259 TElemDef::const_iterator id = elemNodeInd.begin();
4261 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4262 if ( *id < (int) theNodesVector.size() )
4263 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4265 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4267 // dim of refined elem
4268 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4269 if ( onMeshElements ) {
4270 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4273 const SMDS_MeshElement* elem = 0;
4275 switch ( nbNodes ) {
4277 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4279 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4281 if ( !onMeshElements ) {// create a quadratic face
4282 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4283 nodes[4], nodes[5] ); break;
4284 } // else do not break but create a polygon
4286 if ( !onMeshElements ) {// create a quadratic face
4287 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4288 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4289 } // else do not break but create a polygon
4291 elem = aMeshDS->AddPolygonalFace( nodes );
4295 switch ( nbNodes ) {
4297 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4299 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4302 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4303 nodes[4], nodes[5] ); break;
4305 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4306 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4308 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4311 // set element on a shape
4312 if ( elem && onMeshElements ) // applied to mesh elements
4314 int shapeID = shapeIDs[ elemIndex ];
4315 if ( shapeID > 0 ) {
4316 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4317 // set nodes on a shape
4318 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4319 if ( S.ShapeType() == TopAbs_SOLID ) {
4320 TopoDS_Iterator shellIt( S );
4321 if ( shellIt.More() )
4322 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4324 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4325 while ( noIt->more() ) {
4326 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4327 if ( node->getshapeId() < 1 &&
4328 shellNodes.find( node ) == shellNodes.end() )
4330 if ( S.ShapeType() == TopAbs_FACE )
4331 aMeshDS->SetNodeOnFace( node, shapeID,
4332 Precision::Infinite(),// <- it's a sign that UV is not set
4333 Precision::Infinite());
4335 aMeshDS->SetNodeInVolume( node, shapeID );
4336 shellNodes.insert( node );
4341 // add elem in groups
4342 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4343 for ( ; g != groups[ elemIndex ].end(); ++g )
4344 (*g)->SMDSGroup().Add( elem );
4346 if ( elem && !myShape.IsNull() ) // applied to shape
4347 aMeshDS->SetMeshElementOnShape( elem, myShape );
4350 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4351 // so that operations with hypotheses will erase the mesh being built
4353 SMESH_subMesh * subMesh;
4354 if ( !myShape.IsNull() ) {
4355 subMesh = theMesh->GetSubMesh( myShape );
4357 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4359 if ( onMeshElements ) {
4360 list< int > elemIDs;
4361 for ( size_t i = 0; i < theElements.size(); i++ )
4363 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4365 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4367 elemIDs.push_back( theElements[ i ]->GetID() );
4369 // remove refined elements
4370 editor.Remove( elemIDs, false );
4374 //=======================================================================
4375 //function : isReversed
4376 //purpose : check xyz ids order in theIdsList taking into account
4377 // theFirstNode on a link
4378 //=======================================================================
4380 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4381 const list< int >& theIdsList) const
4383 if ( theIdsList.size() < 2 )
4386 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4388 list<int>::const_iterator id = theIdsList.begin();
4389 for ( int i = 0; i < 2; ++i, ++id ) {
4390 if ( *id < (int) myXYZ.size() )
4391 P[ i ] = myXYZ[ *id ];
4393 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4394 i_n = myXYZIdToNodeMap.find( *id );
4395 ASSERT( i_n != myXYZIdToNodeMap.end() );
4396 const SMDS_MeshNode* n = i_n->second;
4397 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4400 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4404 //=======================================================================
4405 //function : arrangeBoundaries
4406 //purpose : if there are several wires, arrange boundaryPoints so that
4407 // the outer wire goes first and fix inner wires orientation
4408 // update myKeyPointIDs to correspond to the order of key-points
4409 // in boundaries; sort internal boundaries by the nb of key-points
4410 //=======================================================================
4412 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4414 typedef list< list< TPoint* > >::iterator TListOfListIt;
4415 TListOfListIt bndIt;
4416 list< TPoint* >::iterator pIt;
4418 int nbBoundaries = boundaryList.size();
4419 if ( nbBoundaries > 1 )
4421 // sort boundaries by nb of key-points
4422 if ( nbBoundaries > 2 )
4424 // move boundaries in tmp list
4425 list< list< TPoint* > > tmpList;
4426 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4427 // make a map nb-key-points to boundary-position-in-tmpList,
4428 // boundary-positions get ordered in it
4429 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4430 TNbKpBndPosMap nbKpBndPosMap;
4431 bndIt = tmpList.begin();
4432 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4433 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4434 int nb = *nbKpIt * nbBoundaries;
4435 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4437 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4439 // move boundaries back to boundaryList
4440 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4441 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4442 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4443 TListOfListIt bndPos1 = bndPos2++;
4444 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4448 // Look for the outer boundary: the one with the point with the least X
4449 double leastX = DBL_MAX;
4450 TListOfListIt outerBndPos;
4451 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4453 list< TPoint* >& boundary = (*bndIt);
4454 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4456 TPoint* point = *pIt;
4457 if ( point->myInitXYZ.X() < leastX ) {
4458 leastX = point->myInitXYZ.X();
4459 outerBndPos = bndIt;
4464 if ( outerBndPos != boundaryList.begin() )
4465 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos );
4467 } // if nbBoundaries > 1
4469 // Check boundaries orientation and re-fill myKeyPointIDs
4471 set< TPoint* > keyPointSet;
4472 list< int >::iterator kpIt = myKeyPointIDs.begin();
4473 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4474 keyPointSet.insert( & myPoints[ *kpIt ]);
4475 myKeyPointIDs.clear();
4477 // update myNbKeyPntInBoundary also
4478 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4480 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4482 // find the point with the least X
4483 double leastX = DBL_MAX;
4484 list< TPoint* >::iterator xpIt;
4485 list< TPoint* >& boundary = (*bndIt);
4486 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4488 TPoint* point = *pIt;
4489 if ( point->myInitXYZ.X() < leastX ) {
4490 leastX = point->myInitXYZ.X();
4494 // find points next to the point with the least X
4495 TPoint* p = *xpIt, *pPrev, *pNext;
4496 if ( p == boundary.front() )
4497 pPrev = *(++boundary.rbegin());
4503 if ( p == boundary.back() )
4504 pNext = *(++boundary.begin());
4509 // vectors of boundary direction near <p>
4510 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4511 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4512 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4513 double yPrev = v1.Y() / sqrt( sqMag1 );
4514 double yNext = v2.Y() / sqrt( sqMag2 );
4515 double sumY = yPrev + yNext;
4517 if ( bndIt == boundaryList.begin() ) // outer boundary
4525 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4526 (*nbKpIt) = 0; // count nb of key-points again
4527 pIt = boundary.begin();
4528 for ( ; pIt != boundary.end(); pIt++)
4530 TPoint* point = *pIt;
4531 if ( keyPointSet.find( point ) == keyPointSet.end() )
4533 // find an index of a keypoint
4535 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4536 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4537 if ( &(*pVecIt) == point )
4539 myKeyPointIDs.push_back( index );
4542 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4545 } // loop on a list of boundaries
4547 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4550 //=======================================================================
4551 //function : findBoundaryPoints
4552 //purpose : if loaded from file, find points to map on edges and faces and
4553 // compute their parameters
4554 //=======================================================================
4556 bool SMESH_Pattern::findBoundaryPoints()
4558 if ( myIsBoundaryPointsFound ) return true;
4560 myNbKeyPntInBoundary.clear();
4564 set< TPoint* > pointsInElems;
4566 // Find free links of elements:
4567 // put links of all elements in a set and remove links encountered twice
4569 typedef pair< TPoint*, TPoint*> TLink;
4570 set< TLink > linkSet;
4571 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4572 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4574 TElemDef & elemPoints = *epIt;
4575 TElemDef::iterator pIt = elemPoints.begin();
4576 int prevP = elemPoints.back();
4577 for ( ; pIt != elemPoints.end(); pIt++ ) {
4578 TPoint* p1 = & myPoints[ prevP ];
4579 TPoint* p2 = & myPoints[ *pIt ];
4580 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4581 ASSERT( link.first != link.second );
4582 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4583 if ( !itUniq.second )
4584 linkSet.erase( itUniq.first );
4587 pointsInElems.insert( p1 );
4590 // Now linkSet contains only free links,
4591 // find the points order that they have in boundaries
4593 // 1. make a map of key-points
4594 set< TPoint* > keyPointSet;
4595 list< int >::iterator kpIt = myKeyPointIDs.begin();
4596 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4597 keyPointSet.insert( & myPoints[ *kpIt ]);
4599 // 2. chain up boundary points
4600 list< list< TPoint* > > boundaryList;
4601 boundaryList.push_back( list< TPoint* >() );
4602 list< TPoint* > * boundary = & boundaryList.back();
4604 TPoint *point1, *point2, *keypoint1;
4605 kpIt = myKeyPointIDs.begin();
4606 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4607 // loop on free links: look for the next point
4609 set< TLink >::iterator lIt = linkSet.begin();
4610 while ( lIt != linkSet.end() )
4612 if ( (*lIt).first == point1 )
4613 point2 = (*lIt).second;
4614 else if ( (*lIt).second == point1 )
4615 point2 = (*lIt).first;
4620 linkSet.erase( lIt );
4621 lIt = linkSet.begin();
4623 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4625 boundary->push_back( point2 );
4627 else // a key-point found
4629 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4631 if ( point2 != keypoint1 ) // its not the boundary end
4633 boundary->push_back( point2 );
4635 else // the boundary end reached
4637 boundary->push_front( keypoint1 );
4638 boundary->push_back( keypoint1 );
4639 myNbKeyPntInBoundary.push_back( iKeyPoint );
4640 if ( keyPointSet.empty() )
4641 break; // all boundaries containing key-points are found
4643 // prepare to search for the next boundary
4644 boundaryList.push_back( list< TPoint* >() );
4645 boundary = & boundaryList.back();
4646 point2 = keypoint1 = (*keyPointSet.begin());
4650 } // loop on the free links set
4652 if ( boundary->empty() ) {
4653 MESSAGE(" a separate key-point");
4654 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4657 // if there are several wires, arrange boundaryPoints so that
4658 // the outer wire goes first and fix inner wires orientation;
4659 // sort myKeyPointIDs to correspond to the order of key-points
4661 arrangeBoundaries( boundaryList );
4663 // Find correspondence shape ID - points,
4664 // compute points parameter on edge
4666 keyPointSet.clear();
4667 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4668 keyPointSet.insert( & myPoints[ *kpIt ]);
4670 set< TPoint* > edgePointSet; // to find in-face points
4671 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4672 int edgeID = myKeyPointIDs.size() + 1;
4674 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4675 for ( ; bndIt != boundaryList.end(); bndIt++ )
4677 boundary = & (*bndIt);
4678 double edgeLength = 0;
4679 list< TPoint* >::iterator pIt = boundary->begin();
4680 getShapePoints( edgeID ).push_back( *pIt );
4681 getShapePoints( vertexID++ ).push_back( *pIt );
4682 for ( pIt++; pIt != boundary->end(); pIt++)
4684 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4685 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4686 TPoint* point = *pIt;
4687 edgePointSet.insert( point );
4688 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4690 edgePoints.push_back( point );
4691 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4692 point->myInitU = edgeLength;
4696 // treat points on the edge which ends up: compute U [0,1]
4697 edgePoints.push_back( point );
4698 if ( edgePoints.size() > 2 ) {
4699 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4700 list< TPoint* >::iterator epIt = edgePoints.begin();
4701 for ( ; epIt != edgePoints.end(); epIt++ )
4702 (*epIt)->myInitU /= edgeLength;
4704 // begin the next edge treatment
4707 if ( point != boundary->front() ) { // not the first key-point again
4708 getShapePoints( edgeID ).push_back( point );
4709 getShapePoints( vertexID++ ).push_back( point );
4715 // find in-face points
4716 list< TPoint* > & facePoints = getShapePoints( edgeID );
4717 vector< TPoint >::iterator pVecIt = myPoints.begin();
4718 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4719 TPoint* point = &(*pVecIt);
4720 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4721 pointsInElems.find( point ) != pointsInElems.end())
4722 facePoints.push_back( point );
4729 // bind points to shapes according to point parameters
4730 vector< TPoint >::iterator pVecIt = myPoints.begin();
4731 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4732 TPoint* point = &(*pVecIt);
4733 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4734 getShapePoints( shapeID ).push_back( point );
4735 // detect key-points
4736 if ( SMESH_Block::IsVertexID( shapeID ))
4737 myKeyPointIDs.push_back( i );
4741 myIsBoundaryPointsFound = true;
4742 return myIsBoundaryPointsFound;
4745 //=======================================================================
4747 //purpose : clear fields
4748 //=======================================================================
4750 void SMESH_Pattern::Clear()
4752 myIsComputed = myIsBoundaryPointsFound = false;
4755 myKeyPointIDs.clear();
4756 myElemPointIDs.clear();
4757 myShapeIDToPointsMap.clear();
4758 myShapeIDMap.Clear();
4760 myNbKeyPntInBoundary.clear();
4763 myElemXYZIDs.clear();
4764 myXYZIdToNodeMap.clear();
4766 myOrderedNodes.clear();
4767 myPolyElems.clear();
4768 myPolyElemXYZIDs.clear();
4769 myPolyhedronQuantities.clear();
4770 myIdsOnBoundary.clear();
4771 myReverseConnectivity.clear();
4774 //================================================================================
4776 * \brief set ErrorCode and return true if it is Ok
4778 //================================================================================
4780 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4782 myErrorCode = theErrorCode;
4783 return myErrorCode == ERR_OK;
4786 //=======================================================================
4787 //function : setShapeToMesh
4788 //purpose : set a shape to be meshed. Return True if meshing is possible
4789 //=======================================================================
4791 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4793 if ( !IsLoaded() ) {
4794 MESSAGE( "Pattern not loaded" );
4795 return setErrorCode( ERR_APPL_NOT_LOADED );
4798 TopAbs_ShapeEnum aType = theShape.ShapeType();
4799 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4801 MESSAGE( "Pattern dimension mismatch" );
4802 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4805 // check if a face is closed
4806 int nbNodeOnSeamEdge = 0;
4808 TopTools_MapOfShape seamVertices;
4809 TopoDS_Face face = TopoDS::Face( theShape );
4810 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4811 for ( ; eExp.More() /*&& nbNodeOnSeamEdge == 0*/; eExp.Next() ) {
4812 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4813 if ( BRep_Tool::IsClosed(ee, face) ) {
4814 // seam edge and vertices encounter twice in theFace
4815 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4816 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4821 // check nb of vertices
4822 TopTools_IndexedMapOfShape vMap;
4823 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4824 if ( vMap.Extent() + nbNodeOnSeamEdge != (int)myKeyPointIDs.size() ) {
4825 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4826 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4829 myElements.clear(); // not refine elements
4830 myElemXYZIDs.clear();
4832 myShapeIDMap.Clear();
4837 //=======================================================================
4838 //function : GetMappedPoints
4839 //purpose : Return nodes coordinates computed by Apply() method
4840 //=======================================================================
4842 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4845 if ( !myIsComputed )
4848 if ( myElements.empty() ) { // applied to shape
4849 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4850 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4851 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4853 else { // applied to mesh elements
4854 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4855 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4856 for ( ; xyz != myXYZ.end(); ++xyz )
4857 if ( !isDefined( *xyz ))
4858 thePoints.push_back( definedXYZ );
4860 thePoints.push_back( & (*xyz) );
4862 return !thePoints.empty();
4866 //=======================================================================
4867 //function : GetPoints
4868 //purpose : Return nodes coordinates of the pattern
4869 //=======================================================================
4871 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4878 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4879 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4880 thePoints.push_back( & (*pVecIt).myInitXYZ );
4882 return ( thePoints.size() > 0 );
4885 //=======================================================================
4886 //function : getShapePoints
4887 //purpose : return list of points located on theShape
4888 //=======================================================================
4890 list< SMESH_Pattern::TPoint* > &
4891 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4894 if ( !myShapeIDMap.Contains( theShape ))
4895 aShapeID = myShapeIDMap.Add( theShape );
4897 aShapeID = myShapeIDMap.FindIndex( theShape );
4899 return myShapeIDToPointsMap[ aShapeID ];
4902 //=======================================================================
4903 //function : getShapePoints
4904 //purpose : return list of points located on the shape
4905 //=======================================================================
4907 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4909 return myShapeIDToPointsMap[ theShapeID ];
4912 //=======================================================================
4913 //function : DumpPoints
4915 //=======================================================================
4917 void SMESH_Pattern::DumpPoints() const
4920 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4921 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4922 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4926 //=======================================================================
4927 //function : TPoint()
4929 //=======================================================================
4931 SMESH_Pattern::TPoint::TPoint()
4934 myInitXYZ.SetCoord(0,0,0);
4935 myInitUV.SetCoord(0.,0.);
4937 myXYZ.SetCoord(0,0,0);
4938 myUV.SetCoord(0.,0.);
4943 //=======================================================================
4944 //function : operator <<
4946 //=======================================================================
4948 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4950 gp_XYZ xyz = p.myInitXYZ;
4951 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4952 gp_XY xy = p.myInitUV;
4953 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4954 double u = p.myInitU;
4955 OS << " u( " << u << " )) " << &p << endl;
4956 xyz = p.myXYZ.XYZ();
4957 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4959 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4961 OS << " u( " << u << " ))" << endl;