1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_Pattern.hxx
24 // Created : Mon Aug 2 10:30:00 2004
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_Pattern.hxx"
29 #include "SMDS_EdgePosition.hxx"
30 #include "SMDS_FacePosition.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshFace.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESHDS_Group.hxx"
36 #include "SMESHDS_Mesh.hxx"
37 #include "SMESHDS_SubMesh.hxx"
38 #include "SMESH_Block.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MeshAlgos.hxx"
41 #include "SMESH_MesherHelper.hxx"
42 #include "SMESH_subMesh.hxx"
44 #include <BRepAdaptor_Curve.hxx>
45 #include <BRepTools.hxx>
46 #include <BRepTools_WireExplorer.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_Box.hxx>
49 #include <Bnd_Box2d.hxx>
51 #include <Extrema_ExtPC.hxx>
52 #include <Extrema_GenExtPS.hxx>
53 #include <Extrema_POnSurf.hxx>
54 #include <Geom2d_Curve.hxx>
55 #include <GeomAdaptor_Surface.hxx>
56 #include <Geom_Curve.hxx>
57 #include <Geom_Surface.hxx>
58 #include <Precision.hxx>
59 #include <TopAbs_ShapeEnum.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <TopLoc_Location.hxx>
63 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopoDS_Edge.hxx>
66 #include <TopoDS_Face.hxx>
67 #include <TopoDS_Iterator.hxx>
68 #include <TopoDS_Shell.hxx>
69 #include <TopoDS_Vertex.hxx>
70 #include <TopoDS_Wire.hxx>
72 #include <gp_Lin2d.hxx>
73 #include <gp_Pnt2d.hxx>
74 #include <gp_Trsf.hxx>
78 #include <Basics_OCCTVersion.hxx>
80 #include <Basics_Utils.hxx>
81 #include "utilities.h"
85 typedef map< const SMDS_MeshElement*, int > TNodePointIDMap;
87 #define smdsNode( elem ) static_cast<const SMDS_MeshNode*>( elem )
92 //=======================================================================
95 //=======================================================================
97 inline int getInt( const char * theSring )
99 if ( *theSring < '0' || *theSring > '9' )
103 int val = strtol( theSring, &ptr, 10 );
104 if ( ptr == theSring ||
105 // there must not be neither '.' nor ',' nor 'E' ...
106 (*ptr != ' ' && *ptr != '\n' && *ptr != '\0'))
112 //=======================================================================
113 //function : getDouble
115 //=======================================================================
117 inline double getDouble( const char * theSring )
120 return strtod( theSring, &ptr );
123 //=======================================================================
124 //function : readLine
125 //purpose : Put token starting positions in theFields until '\n' or '\0'
126 // Return the number of the found tokens
127 //=======================================================================
129 int readLine (list <const char*> & theFields,
130 const char* & theLineBeg,
131 const bool theClearFields )
133 if ( theClearFields )
138 /* switch ( symbol ) { */
139 /* case white-space: */
140 /* look for a non-space symbol; */
141 /* case string-end: */
144 /* case comment beginning: */
145 /* skip all till a line-end; */
147 /* put its position in theFields, skip till a white-space;*/
153 bool stopReading = false;
156 bool isNumber = false;
157 switch ( *theLineBeg )
159 case ' ': // white space
164 case '\n': // a line ends
165 stopReading = ( nbRead > 0 );
170 while ( *theLineBeg != '\n' && *theLineBeg != '\0' );
174 case '\0': // file ends
177 case '-': // real number
182 isNumber = isNumber || ( *theLineBeg >= '0' && *theLineBeg <= '9' );
184 theFields.push_back( theLineBeg );
187 while (*theLineBeg != ' ' &&
188 *theLineBeg != '\n' &&
189 *theLineBeg != '\0');
193 return 0; // incorrect file format
199 } while ( !stopReading );
204 //=======================================================================
205 //function : isRealSeam
206 //purpose : return true if an EDGE encounters twice in a FACE
207 //=======================================================================
209 // bool isRealSeam( const TopoDS_Edge& e, const TopoDS_Face& f )
211 // if ( BRep_Tool::IsClosed( e, f ))
214 // for (TopExp_Explorer exp( f, TopAbs_EDGE ); exp.More(); exp.Next())
215 // if ( exp.Current().IsSame( e ))
222 //=======================================================================
224 //purpose : load VERTEXes and EDGEs in a map. Return nb loaded VERTEXes
225 //=======================================================================
227 int loadVE( const list< TopoDS_Edge > & eList,
228 TopTools_IndexedMapOfOrientedShape & map )
230 list< TopoDS_Edge >::const_iterator eIt = eList.begin();
233 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
236 map.Add( TopExp::FirstVertex( *eIt, true ));
237 bool added = ( nbV < map.Extent() );
238 if ( !added ) { // vertex encountered twice
239 // a seam vertex have two corresponding key points
240 map.Add( TopExp::FirstVertex( *eIt, true ).Reversed());
246 for ( eIt = eList.begin(); eIt != eList.end(); eIt++ )
254 //=======================================================================
255 //function : SMESH_Pattern
257 //=======================================================================
259 SMESH_Pattern::SMESH_Pattern ()
263 //=======================================================================
265 //purpose : Load a pattern from <theFile>
266 //=======================================================================
268 bool SMESH_Pattern::Load (const char* theFileContents)
270 MESSAGE("Load( file ) ");
272 Kernel_Utils::Localizer loc;
276 // ! This is a comment
277 // NB_POINTS ! 1 integer - the number of points in the pattern.
278 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
279 // X2 Y2 [Z2] ! the pattern dimention is defined by the number of coordinates
281 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
282 // ! elements description goes after all
283 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
288 const char* lineBeg = theFileContents;
289 list <const char*> fields;
290 const bool clearFields = true;
292 // NB_POINTS ! 1 integer - the number of points in the pattern.
294 if ( readLine( fields, lineBeg, clearFields ) != 1 ) {
295 MESSAGE("Error reading NB_POINTS");
296 return setErrorCode( ERR_READ_NB_POINTS );
298 int nbPoints = getInt( fields.front() );
300 // X1 Y1 [Z1] ! 2 or 3 reals - nodes coordinates within 2D or 3D domain:
302 // read the first point coordinates to define pattern dimention
303 int dim = readLine( fields, lineBeg, clearFields );
309 MESSAGE("Error reading points: wrong nb of coordinates");
310 return setErrorCode( ERR_READ_POINT_COORDS );
312 if ( nbPoints <= dim ) {
313 MESSAGE(" Too few points ");
314 return setErrorCode( ERR_READ_TOO_FEW_POINTS );
317 // read the rest points
319 for ( iPoint = 1; iPoint < nbPoints; iPoint++ )
320 if ( readLine( fields, lineBeg, !clearFields ) != dim ) {
321 MESSAGE("Error reading points : wrong nb of coordinates ");
322 return setErrorCode( ERR_READ_POINT_COORDS );
324 // store point coordinates
325 myPoints.resize( nbPoints );
326 list <const char*>::iterator fIt = fields.begin();
327 for ( iPoint = 0; iPoint < nbPoints; iPoint++ )
329 TPoint & p = myPoints[ iPoint ];
330 for ( int iCoord = 1; iCoord <= dim; iCoord++, fIt++ )
332 double coord = getDouble( *fIt );
333 if ( !myIs2D && ( coord < 0.0 || coord > 1.0 )) {
334 MESSAGE("Error reading 3D points, value should be in [0,1]: " << coord);
336 return setErrorCode( ERR_READ_3D_COORD );
338 p.myInitXYZ.SetCoord( iCoord, coord );
340 p.myInitUV.SetCoord( iCoord, coord );
344 // [ ID1 ID2 ... IDn ] ! Indices of key-points for a 2D pattern (only).
347 if ( readLine( fields, lineBeg, clearFields ) == 0 ) {
348 MESSAGE("Error: missing key-points");
350 return setErrorCode( ERR_READ_NO_KEYPOINT );
353 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
355 int pointIndex = getInt( *fIt );
356 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
357 MESSAGE("Error: invalid point index " << pointIndex );
359 return setErrorCode( ERR_READ_BAD_INDEX );
361 if ( idSet.insert( pointIndex ).second ) // unique?
362 myKeyPointIDs.push_back( pointIndex );
366 // ID1 ID2 ... IDn ! 2-4 or 4-8 integers - nodal connectivity of a 2D or 3D element.
368 while ( readLine( fields, lineBeg, clearFields ))
370 myElemPointIDs.push_back( TElemDef() );
371 TElemDef& elemPoints = myElemPointIDs.back();
372 for ( fIt = fields.begin(); fIt != fields.end(); fIt++ )
374 int pointIndex = getInt( *fIt );
375 if ( pointIndex >= nbPoints || pointIndex < 0 ) {
376 MESSAGE("Error: invalid point index " << pointIndex );
378 return setErrorCode( ERR_READ_BAD_INDEX );
380 elemPoints.push_back( pointIndex );
382 // check the nb of nodes in element
384 switch ( elemPoints.size() ) {
385 case 3: if ( !myIs2D ) Ok = false; break;
389 case 8: if ( myIs2D ) Ok = false; break;
393 MESSAGE("Error: wrong nb of nodes in element " << elemPoints.size() );
395 return setErrorCode( ERR_READ_ELEM_POINTS );
398 if ( myElemPointIDs.empty() ) {
399 MESSAGE("Error: no elements");
401 return setErrorCode( ERR_READ_NO_ELEMS );
404 findBoundaryPoints(); // sort key-points
406 return setErrorCode( ERR_OK );
409 //=======================================================================
411 //purpose : Save the loaded pattern into the file <theFileName>
412 //=======================================================================
414 bool SMESH_Pattern::Save (ostream& theFile)
416 MESSAGE(" ::Save(file) " );
418 Kernel_Utils::Localizer loc;
421 MESSAGE(" Pattern not loaded ");
422 return setErrorCode( ERR_SAVE_NOT_LOADED );
425 theFile << "!!! SALOME Mesh Pattern file" << endl;
426 theFile << "!!!" << endl;
427 theFile << "!!! Nb of points:" << endl;
428 theFile << myPoints.size() << endl;
432 // theFile.width( 8 );
433 // theFile.setf(ios::fixed);// use 123.45 floating notation
434 // theFile.setf(ios::right);
435 // theFile.flags( theFile.flags() & ~ios::showpoint); // do not show trailing zeros
436 // theFile.setf(ios::showpoint); // do not show trailing zeros
437 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
438 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
439 const gp_XYZ & xyz = (*pVecIt).myInitXYZ;
440 theFile << " " << setw( width ) << xyz.X() << " " << setw( width ) << xyz.Y();
441 if ( !myIs2D ) theFile << " " << setw( width ) << xyz.Z();
442 theFile << " !- " << i << endl; // point id to ease reading by a human being
446 theFile << "!!! Indices of " << myKeyPointIDs.size() << " key-points:" << endl;
447 list< int >::const_iterator kpIt = myKeyPointIDs.begin();
448 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
449 theFile << " " << *kpIt;
450 if ( !myKeyPointIDs.empty() )
454 theFile << "!!! Indices of points of " << myElemPointIDs.size() << " elements:" << endl;
455 list<TElemDef >::const_iterator epIt = myElemPointIDs.begin();
456 for ( ; epIt != myElemPointIDs.end(); epIt++ )
458 const TElemDef & elemPoints = *epIt;
459 TElemDef::const_iterator iIt = elemPoints.begin();
460 for ( ; iIt != elemPoints.end(); iIt++ )
461 theFile << " " << *iIt;
467 return setErrorCode( ERR_OK );
470 //=======================================================================
471 //function : sortBySize
472 //purpose : sort theListOfList by size
473 //=======================================================================
475 template<typename T> struct TSizeCmp {
476 bool operator ()( const list < T > & l1, const list < T > & l2 )
477 const { return l1.size() < l2.size(); }
480 template<typename T> void sortBySize( list< list < T > > & theListOfList )
482 if ( theListOfList.size() > 2 ) {
483 TSizeCmp< T > SizeCmp;
484 theListOfList.sort( SizeCmp );
488 //=======================================================================
491 //=======================================================================
493 static gp_XY project (const SMDS_MeshNode* theNode,
494 Extrema_GenExtPS & theProjectorPS)
496 gp_Pnt P( theNode->X(), theNode->Y(), theNode->Z() );
497 theProjectorPS.Perform( P );
498 if ( !theProjectorPS.IsDone() ) {
499 MESSAGE( "SMESH_Pattern: point projection FAILED");
502 double u, v, minVal = DBL_MAX;
503 for ( int i = theProjectorPS.NbExt(); i > 0; i-- )
504 if ( theProjectorPS.SquareDistance( i ) < minVal ) {
505 minVal = theProjectorPS.SquareDistance( i );
506 theProjectorPS.Point( i ).Parameter( u, v );
508 return gp_XY( u, v );
511 //=======================================================================
512 //function : areNodesBound
513 //purpose : true if all nodes of faces are bound to shapes
514 //=======================================================================
516 template <class TFaceIterator> bool areNodesBound( TFaceIterator & faceItr )
518 while ( faceItr->more() )
520 SMDS_ElemIteratorPtr nIt = faceItr->next()->nodesIterator();
521 while ( nIt->more() )
523 const SMDS_MeshNode* node = smdsNode( nIt->next() );
524 if (node->getshapeId() <1) {
532 //=======================================================================
533 //function : isMeshBoundToShape
534 //purpose : return true if all 2d elements are bound to shape
535 // if aFaceSubmesh != NULL, then check faces bound to it
536 // else check all faces in aMeshDS
537 //=======================================================================
539 static bool isMeshBoundToShape(SMESHDS_Mesh * aMeshDS,
540 SMESHDS_SubMesh * aFaceSubmesh,
541 const bool isMainShape)
544 // check that all faces are bound to aFaceSubmesh
545 if ( aMeshDS->NbFaces() != aFaceSubmesh->NbElements() )
549 // check face nodes binding
550 if ( aFaceSubmesh ) {
551 SMDS_ElemIteratorPtr fIt = aFaceSubmesh->GetElements();
552 return areNodesBound( fIt );
554 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
555 return areNodesBound( fIt );
558 //=======================================================================
560 //purpose : Create a pattern from the mesh built on <theFace>.
561 // <theProject>==true makes override nodes positions
562 // on <theFace> computed by mesher
563 //=======================================================================
565 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
566 const TopoDS_Face& theFace,
568 TopoDS_Vertex the1stVertex)
570 MESSAGE(" ::Load(face) " );
574 SMESHDS_Mesh * aMeshDS = theMesh->GetMeshDS();
575 SMESHDS_SubMesh * fSubMesh = aMeshDS->MeshElements( theFace );
576 const bool isQuadMesh = aMeshDS->GetMeshInfo().NbFaces( ORDER_QUADRATIC );
577 SMESH_MesherHelper helper( *theMesh );
578 helper.SetSubShape( theFace );
580 int nbNodes = ( !fSubMesh ? 0 : fSubMesh->NbNodes() );
581 int nbElems = ( !fSubMesh ? 0 : fSubMesh->NbElements() );
582 if ( nbElems == 0 && aMeshDS->NbFaces() == 0 )
584 MESSAGE( "No elements bound to the face");
585 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
588 TopoDS_Face face = TopoDS::Face( theFace.Oriented( TopAbs_FORWARD ));
590 // check if face is closed
591 bool isClosed = helper.HasSeam();
592 list<TopoDS_Edge> eList;
593 list<TopoDS_Edge>::iterator elIt;
594 SMESH_Block::GetOrderedEdges( face, eList, myNbKeyPntInBoundary, the1stVertex );
596 // check that requested or needed projection is possible
597 bool isMainShape = theMesh->IsMainShape( face );
598 bool needProject = !isMeshBoundToShape( aMeshDS, fSubMesh, isMainShape );
599 bool canProject = ( nbElems ? true : isMainShape );
601 canProject = false; // so far
603 if ( ( theProject || needProject ) && !canProject )
604 return setErrorCode( ERR_LOADF_CANT_PROJECT );
606 Extrema_GenExtPS projector;
607 GeomAdaptor_Surface aSurface( BRep_Tool::Surface( face ));
608 if ( theProject || needProject )
609 projector.Initialize( aSurface, 20,20, 1e-5,1e-5 );
612 TNodePointIDMap nodePointIDMap;
613 TNodePointIDMap closeNodePointIDMap; // for nodes on seam edges
617 MESSAGE("Project the submesh");
618 // ---------------------------------------------------------------
619 // The case where the submesh is projected to theFace
620 // ---------------------------------------------------------------
623 list< const SMDS_MeshElement* > faces;
625 SMDS_ElemIteratorPtr fIt = fSubMesh->GetElements();
626 while ( fIt->more() ) {
627 const SMDS_MeshElement* f = fIt->next();
628 if ( f && f->GetType() == SMDSAbs_Face )
629 faces.push_back( f );
633 SMDS_FaceIteratorPtr fIt = aMeshDS->facesIterator();
634 while ( fIt->more() )
635 faces.push_back( fIt->next() );
638 // put nodes of all faces into the nodePointIDMap and fill myElemPointIDs
639 list< const SMDS_MeshElement* >::iterator fIt = faces.begin();
640 for ( ; fIt != faces.end(); ++fIt )
642 myElemPointIDs.push_back( TElemDef() );
643 TElemDef& elemPoints = myElemPointIDs.back();
644 int nbNodes = (*fIt)->NbCornerNodes();
645 for ( int i = 0;i < nbNodes; ++i )
647 const SMDS_MeshElement* node = (*fIt)->GetNode( i );
648 TNodePointIDMap::iterator nIdIt = nodePointIDMap.insert( make_pair( node, -1 )).first;
649 if ( nIdIt->second == -1 )
651 elemPoints.push_back( iPoint );
652 nIdIt->second = iPoint++;
655 elemPoints.push_back( (*nIdIt).second );
658 myPoints.resize( iPoint );
660 // project all nodes of 2d elements to theFace
661 TNodePointIDMap::iterator nIdIt = nodePointIDMap.begin();
662 for ( ; nIdIt != nodePointIDMap.end(); nIdIt++ )
664 const SMDS_MeshNode* node = smdsNode( (*nIdIt).first );
665 TPoint * p = & myPoints[ (*nIdIt).second ];
666 p->myInitUV = project( node, projector );
667 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
669 // find key-points: the points most close to UV of vertices
670 TopExp_Explorer vExp( face, TopAbs_VERTEX );
671 set<int> foundIndices;
672 for ( ; vExp.More(); vExp.Next() ) {
673 const TopoDS_Vertex v = TopoDS::Vertex( vExp.Current() );
674 gp_Pnt2d uv = BRep_Tool::Parameters( v, face );
675 double minDist = DBL_MAX;
677 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
678 for ( iPoint = 0; pVecIt != myPoints.end(); pVecIt++, iPoint++ ) {
679 double dist = uv.SquareDistance( (*pVecIt).myInitUV );
680 if ( dist < minDist ) {
685 if ( foundIndices.insert( index ).second ) // unique?
686 myKeyPointIDs.push_back( index );
688 myIsBoundaryPointsFound = false;
693 // ---------------------------------------------------------------------
694 // The case where a pattern is being made from the mesh built by mesher
695 // ---------------------------------------------------------------------
697 // Load shapes in the consequent order and count nb of points
699 loadVE( eList, myShapeIDMap );
700 myShapeIDMap.Add( face );
702 nbNodes += myShapeIDMap.Extent() - 1;
704 for ( elIt = eList.begin(); elIt != eList.end(); elIt++ )
705 if ( SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( *elIt ))
706 nbNodes += eSubMesh->NbNodes() + 1;
708 myPoints.resize( nbNodes );
710 // Load U of points on edges
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 EDGEs in eVec
720 list<TopoDS_Edge>::iterator eEnd = elIt;
721 std::advance( eEnd, *nbEinW );
722 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 orienation)
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 orienations)
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);
784 if ( !vPoint->empty() )
785 ePoints.push_back( vPoint->front() );
788 SMESHDS_SubMesh * eSubMesh = aMeshDS->MeshElements( edge );
789 if ( eSubMesh && eSubMesh->NbNodes() )
791 // loop on nodes of an edge: sort them by param on edge
792 typedef map < double, const SMDS_MeshNode* > TParamNodeMap;
793 TParamNodeMap paramNodeMap;
794 int nbMeduimNodes = 0;
795 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
796 while ( nIt->more() )
798 const SMDS_MeshNode* node = nIt->next();
799 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face )) {
803 const SMDS_EdgePosition* epos =
804 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
805 double u = epos->GetUParameter();
806 paramNodeMap.insert( make_pair( u, node ));
808 if ( paramNodeMap.size() != eSubMesh->NbNodes() ) {
809 // wrong U on edge, project
811 BRepAdaptor_Curve aCurve( edge );
812 proj.Initialize( aCurve, f, l );
813 paramNodeMap.clear();
814 nIt = eSubMesh->GetNodes();
815 for ( int iNode = 0; nIt->more(); ++iNode ) {
816 const SMDS_MeshNode* node = nIt->next();
817 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
819 proj.Perform( gp_Pnt( node->X(), node->Y(), node->Z()));
821 if ( proj.IsDone() ) {
822 for ( int i = 1, nb = proj.NbExt(); i <= nb; ++i )
823 if ( proj.IsMin( i )) {
824 u = proj.Point( i ).Parameter();
828 u = isForward ? iNode : eSubMesh->NbNodes() - iNode;
830 paramNodeMap.insert( make_pair( u, node ));
833 //rnv : To fix the bug IPAL21999 Pattern Mapping - New - collapse of pattern mesh
834 if ( paramNodeMap.size() != eSubMesh->NbNodes() - nbMeduimNodes )
835 return setErrorCode(ERR_UNEXPECTED);
838 // put U in [0,1] so that the first key-point has U==0
839 bool isSeam = helper.IsRealSeam( edge );
841 TParamNodeMap::iterator unIt = paramNodeMap.begin();
842 TParamNodeMap::reverse_iterator unRIt = paramNodeMap.rbegin();
843 while ( unIt != paramNodeMap.end() )
845 TPoint* p = & myPoints[ iPoint ];
846 ePoints.push_back( p );
847 const SMDS_MeshNode* node = isForward ? (*unIt).second : (*unRIt).second;
848 if ( isSeam && !isForward )
849 closeNodePointIDMap.insert( make_pair( node, iPoint ));
851 nodePointIDMap.insert ( make_pair( node, iPoint ));
854 p->myInitUV = project( node, projector );
856 double u = isForward ? (*unIt).first : (*unRIt).first;
857 p->myInitU = isForward ? (( u - f ) / du ) : ( 1.0 - ( u - f ) / du );
858 p->myInitUV = C2d->Value( u ).XY();
860 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
865 // the reverse key-point
866 vPoint = & getShapePoints( v2 );
867 if ( vPoint->empty() )
869 SMESHDS_SubMesh * vSubMesh = aMeshDS->MeshElements( v2 );
870 if ( vSubMesh && vSubMesh->NbNodes() ) {
871 myKeyPointIDs.push_back( iPoint );
872 SMDS_NodeIteratorPtr nIt = vSubMesh->GetNodes();
873 const SMDS_MeshNode* node = nIt->next();
874 if ( v2.Orientation() == TopAbs_REVERSED )
875 closeNodePointIDMap.insert( make_pair( node, iPoint ));
877 nodePointIDMap.insert( make_pair( node, iPoint ));
879 TPoint* keyPoint = &myPoints[ iPoint++ ];
880 vPoint->push_back( keyPoint );
882 keyPoint->myInitUV = project( node, projector );
884 keyPoint->myInitUV = C2d->Value( isForward ? l : f ).XY();
885 keyPoint->myInitXYZ.SetCoord( keyPoint->myInitUV.X(), keyPoint->myInitUV.Y(), 0 );
888 if ( !vPoint->empty() )
889 ePoints.push_back( vPoint->front() );
891 // compute U of edge-points
894 double totalDist = 0;
895 list< TPoint* >::iterator pIt = ePoints.begin();
896 TPoint* prevP = *pIt;
897 prevP->myInitU = totalDist;
898 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
900 totalDist += ( p->myInitUV - prevP->myInitUV ).Modulus();
901 p->myInitU = totalDist;
904 if ( totalDist > DBL_MIN)
905 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
907 p->myInitU /= totalDist;
910 } // loop on edges of a wire
912 // Load in-face points and elements
914 if ( fSubMesh && fSubMesh->NbElements() )
916 list< TPoint* > & fPoints = getShapePoints( face );
917 SMDS_NodeIteratorPtr nIt = fSubMesh->GetNodes();
918 while ( nIt->more() )
920 const SMDS_MeshNode* node = nIt->next();
921 if ( isQuadMesh && helper.IsMedium( node, SMDSAbs_Face ))
923 nodePointIDMap.insert( make_pair( node, iPoint ));
924 TPoint* p = &myPoints[ iPoint++ ];
925 fPoints.push_back( p );
927 p->myInitUV = project( node, projector );
929 const SMDS_FacePosition* pos =
930 static_cast<const SMDS_FacePosition*>(node->GetPosition());
931 p->myInitUV.SetCoord( pos->GetUParameter(), pos->GetVParameter() );
933 p->myInitXYZ.SetCoord( p->myInitUV.X(), p->myInitUV.Y(), 0 );
936 TNodePointIDMap::iterator n_id, not_found = closeNodePointIDMap.end();
937 SMDS_ElemIteratorPtr elemIt = fSubMesh->GetElements();
938 while ( elemIt->more() )
940 const SMDS_MeshElement* elem = elemIt->next();
941 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
942 myElemPointIDs.push_back( TElemDef() );
943 TElemDef& elemPoints = myElemPointIDs.back();
944 // find point indices corresponding to element nodes
945 while ( nIt->more() )
947 const SMDS_MeshNode* node = smdsNode( nIt->next() );
948 n_id = nodePointIDMap.find( node );
949 if ( n_id == nodePointIDMap.end() )
950 continue; // medium node
951 iPoint = n_id->second; // point index of interest
952 // for a node on a seam edge there are two points
953 if ( helper.IsRealSeam( node->getshapeId() ) &&
954 ( n_id = closeNodePointIDMap.find( node )) != not_found )
956 TPoint & p1 = myPoints[ iPoint ];
957 TPoint & p2 = myPoints[ n_id->second ];
958 // Select point closest to the rest nodes of element in UV space
959 SMDS_ElemIteratorPtr nIt2 = elem->nodesIterator();
960 const SMDS_MeshNode* notSeamNode = 0;
961 // find node not on a seam edge
962 while ( nIt2->more() && !notSeamNode ) {
963 const SMDS_MeshNode* n = smdsNode( nIt2->next() );
964 if ( !helper.IsSeamShape( n->getshapeId() ))
967 gp_Pnt2d uv = helper.GetNodeUV( theFace, node, notSeamNode );
968 double dist1 = uv.SquareDistance( p1.myInitUV );
969 double dist2 = uv.SquareDistance( p2.myInitUV );
971 iPoint = n_id->second;
973 elemPoints.push_back( iPoint );
977 myPoints.resize( nodePointIDMap.size() + closeNodePointIDMap.size() );
979 myIsBoundaryPointsFound = true;
982 // Assure that U range is proportional to V range
985 vector< TPoint >::iterator pVecIt = myPoints.begin();
986 for ( ; pVecIt != myPoints.end(); pVecIt++ )
987 bndBox.Add( gp_Pnt2d( (*pVecIt).myInitUV ));
988 double minU, minV, maxU, maxV;
989 bndBox.Get( minU, minV, maxU, maxV );
990 double dU = maxU - minU, dV = maxV - minV;
991 if ( dU <= DBL_MIN || dV <= DBL_MIN ) {
994 // define where is the problem, in the face or in the mesh
995 TopExp_Explorer vExp( face, TopAbs_VERTEX );
996 for ( ; vExp.More(); vExp.Next() ) {
997 gp_Pnt2d uv = BRep_Tool::Parameters( TopoDS::Vertex( vExp.Current() ), face );
1000 bndBox.Get( minU, minV, maxU, maxV );
1001 dU = maxU - minU, dV = maxV - minV;
1002 if ( dU <= DBL_MIN || dV <= DBL_MIN )
1004 return setErrorCode( ERR_LOADF_NARROW_FACE );
1006 // mesh is projected onto a line, e.g.
1007 return setErrorCode( ERR_LOADF_CANT_PROJECT );
1009 double ratio = dU / dV, maxratio = 3, scale;
1011 if ( ratio > maxratio ) {
1012 scale = ratio / maxratio;
1015 else if ( ratio < 1./maxratio ) {
1016 scale = maxratio / ratio;
1021 for ( pVecIt = myPoints.begin(); pVecIt != myPoints.end(); pVecIt++ ) {
1022 TPoint & p = *pVecIt;
1023 p.myInitUV.SetCoord( iCoord, p.myInitUV.Coord( iCoord ) * scale );
1024 p.myInitXYZ.SetCoord( p.myInitUV.X(), p.myInitUV.Y(), 0 );
1027 if ( myElemPointIDs.empty() ) {
1028 MESSAGE( "No elements bound to the face");
1029 return setErrorCode( ERR_LOAD_EMPTY_SUBMESH );
1032 return setErrorCode( ERR_OK );
1035 //=======================================================================
1036 //function : computeUVOnEdge
1037 //purpose : compute coordinates of points on theEdge
1038 //=======================================================================
1040 void SMESH_Pattern::computeUVOnEdge (const TopoDS_Edge& theEdge,
1041 const list< TPoint* > & ePoints )
1043 bool isForward = ( theEdge.Orientation() == TopAbs_FORWARD );
1045 Handle(Geom2d_Curve) C2d =
1046 BRep_Tool::CurveOnSurface( theEdge, TopoDS::Face( myShape ), f, l );
1048 ePoints.back()->myInitU = 1.0;
1049 //ePoints.front()->myInitU = 0.0; //myUV = C2d->Value( isForward ? f : l ).XY();
1050 list< TPoint* >::const_iterator pIt = ePoints.begin();
1051 for ( pIt++; pIt != ePoints.end(); pIt++ )
1053 TPoint* point = *pIt;
1055 double du = ( isForward ? point->myInitU : 1 - point->myInitU );
1056 point->myU = ( f * ( 1 - du ) + l * du );
1058 point->myUV = C2d->Value( point->myU ).XY();
1062 //=======================================================================
1063 //function : intersectIsolines
1065 //=======================================================================
1067 static bool intersectIsolines(const gp_XY& uv11, const gp_XY& uv12, const double r1,
1068 const gp_XY& uv21, const gp_XY& uv22, const double r2,
1072 gp_XY loc1 = uv11 * ( 1 - r1 ) + uv12 * r1;
1073 gp_XY loc2 = uv21 * ( 1 - r2 ) + uv22 * r2;
1074 resUV = 0.5 * ( loc1 + loc2 );
1075 //isDeformed = ( loc1 - loc2 ).SquareModulus() > 1e-8;
1076 // SKL 26.07.2007 for NPAL16567
1077 double d1 = (uv11-uv12).Modulus();
1078 double d2 = (uv21-uv22).Modulus();
1079 // double delta = d1*d2*1e-6; PAL17233
1080 double delta = min( d1, d2 ) / 10.;
1081 isDeformed = ( loc1 - loc2 ).SquareModulus() > delta * delta;
1083 // double len1 = ( uv11 - uv12 ).Modulus();
1084 // double len2 = ( uv21 - uv22 ).Modulus();
1085 // resUV = loc1 * len2 / ( len1 + len2 ) + loc2 * len1 / ( len1 + len2 );
1089 // gp_Lin2d line1( uv11, uv12 - uv11 );
1090 // gp_Lin2d line2( uv21, uv22 - uv21 );
1091 // double angle = Abs( line1.Angle( line2 ) );
1093 // IntAna2d_AnaIntersection inter;
1094 // inter.Perform( line1.Normal( loc1 ), line2.Normal( loc2 ) );
1095 // if ( inter.IsDone() && inter.NbPoints() == 1 )
1097 // gp_Pnt2d interUV = inter.Point(1).Value();
1098 // resUV += interUV.XY();
1099 // inter.Perform( line1, line2 );
1100 // interUV = inter.Point(1).Value();
1101 // resUV += interUV.XY();
1106 MESSAGE("intersectIsolines(), d1 = " << d1 << ", d2 = " << d2 << ", delta = " << delta <<
1107 ", " << (loc1 - loc2).SquareModulus() << " > " << delta * delta);
1112 //=======================================================================
1113 //function : compUVByIsoIntersection
1115 //=======================================================================
1117 bool SMESH_Pattern::compUVByIsoIntersection (const list< list< TPoint* > >& theBndPoints,
1118 const gp_XY& theInitUV,
1120 bool & theIsDeformed )
1122 // compute UV by intersection of 2 iso lines
1123 //gp_Lin2d isoLine[2];
1124 gp_XY uv1[2], uv2[2];
1126 const double zero = DBL_MIN;
1127 for ( int iIso = 0; iIso < 2; iIso++ )
1129 // to build an iso line:
1130 // find 2 pairs of consequent edge-points such that the range of their
1131 // initial parameters encloses the in-face point initial parameter
1132 gp_XY UV[2], initUV[2];
1133 int nbUV = 0, iCoord = iIso + 1;
1134 double initParam = theInitUV.Coord( iCoord );
1136 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1137 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1139 const list< TPoint* > & bndPoints = * bndIt;
1140 TPoint* prevP = bndPoints.back(); // this is the first point
1141 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1142 bool coincPrev = false;
1143 // loop on the edge-points
1144 for ( ; pIt != bndPoints.end(); pIt++ )
1146 double paramDiff = initParam - (*pIt)->myInitUV.Coord( iCoord );
1147 double prevParamDiff = initParam - prevP->myInitUV.Coord( iCoord );
1148 double sumOfDiff = Abs(prevParamDiff) + Abs(paramDiff);
1149 if (!coincPrev && // ignore if initParam coincides with prev point param
1150 sumOfDiff > zero && // ignore if both points coincide with initParam
1151 prevParamDiff * paramDiff <= zero )
1153 // find UV in parametric space of theFace
1154 double r = Abs(prevParamDiff) / sumOfDiff;
1155 gp_XY uvInit = (*pIt)->myInitUV * r + prevP->myInitUV * ( 1 - r );
1158 // throw away uv most distant from <theInitUV>
1159 gp_XY vec0 = initUV[0] - theInitUV;
1160 gp_XY vec1 = initUV[1] - theInitUV;
1161 gp_XY vec = uvInit - theInitUV;
1162 bool isBetween = ( vec0 * vec1 < 0 ); // is theInitUV between initUV[0] and initUV[1]
1163 double dist0 = vec0.SquareModulus();
1164 double dist1 = vec1.SquareModulus();
1165 double dist = vec .SquareModulus();
1166 if ( !isBetween || dist < dist0 || dist < dist1 ) {
1167 i = ( dist0 < dist1 ? 1 : 0 );
1168 if ( isBetween && vec.Dot( i ? vec1 : vec0 ) < 0 )
1169 i = 3; // theInitUV must remain between
1173 initUV[ i ] = uvInit;
1174 UV[ i ] = (*pIt)->myUV * r + prevP->myUV * ( 1 - r );
1176 coincPrev = ( Abs(paramDiff) <= zero );
1183 if ( nbUV < 2 || (UV[0]-UV[1]).SquareModulus() <= DBL_MIN*DBL_MIN ) {
1184 MESSAGE(" consequent edge-points not found, nb UV found: " << nbUV <<
1185 ", for point: " << theInitUV.X() <<" " << theInitUV.Y() );
1186 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1188 // an iso line should be normal to UV[0] - UV[1] direction
1189 // and be located at the same relative distance as from initial ends
1190 //gp_Lin2d iso( UV[0], UV[0] - UV[1] );
1192 (initUV[0]-theInitUV).Modulus() / (initUV[0]-initUV[1]).Modulus();
1193 //gp_Pnt2d isoLoc = UV[0] * ( 1 - r ) + UV[1] * r;
1194 //isoLine[ iIso ] = iso.Normal( isoLoc );
1195 uv1[ iIso ] = UV[0];
1196 uv2[ iIso ] = UV[1];
1199 if ( !intersectIsolines( uv1[0], uv2[0], ratio[0],
1200 uv1[1], uv2[1], ratio[1], theUV, theIsDeformed )) {
1201 MESSAGE(" Cant intersect isolines for a point "<<theInitUV.X()<<", "<<theInitUV.Y());
1202 return setErrorCode( ERR_APPLF_BAD_TOPOLOGY );
1209 // ==========================================================
1210 // structure representing a node of a grid of iso-poly-lines
1211 // ==========================================================
1218 gp_Dir2d myDir[2]; // boundary tangent dir for boundary nodes, iso dir for internal ones
1219 TIsoNode* myNext[4]; // order: (iDir=0,isForward=0), (1,0), (0,1), (1,1)
1220 TIsoNode* myBndNodes[4]; // order: (iDir=0,i=0), (1,0), (0,1), (1,1)
1221 TIsoNode(double initU, double initV):
1222 myInitUV( initU, initV ), myUV( 1e100, 1e100 ), myIsMovable(true)
1223 { myNext[0] = myNext[1] = myNext[2] = myNext[3] = 0; }
1224 bool IsUVComputed() const
1225 { return myUV.X() != 1e100; }
1226 bool IsMovable() const
1227 { return myIsMovable && myNext[0] && myNext[1] && myNext[2] && myNext[3]; }
1228 void SetNotMovable()
1229 { myIsMovable = false; }
1230 void SetBoundaryNode(TIsoNode* node, int iDir, int i)
1231 { myBndNodes[ iDir + i * 2 ] = node; }
1232 TIsoNode* GetBoundaryNode(int iDir, int i)
1233 { return myBndNodes[ iDir + i * 2 ]; }
1234 void SetNext(TIsoNode* node, int iDir, int isForward)
1235 { myNext[ iDir + isForward * 2 ] = node; }
1236 TIsoNode* GetNext(int iDir, int isForward)
1237 { return myNext[ iDir + isForward * 2 ]; }
1240 //=======================================================================
1241 //function : getNextNode
1243 //=======================================================================
1245 static inline TIsoNode* getNextNode(const TIsoNode* node, int dir )
1247 TIsoNode* n = node->myNext[ dir ];
1248 if ( n && !n->IsUVComputed()/* && node->IsMovable()*/ ) {
1249 n = 0;//node->myBndNodes[ dir ];
1250 // MESSAGE("getNextNode: use bnd for node "<<
1251 // node->myInitUV.X()<<" "<<node->myInitUV.Y());
1255 //=======================================================================
1256 //function : checkQuads
1257 //purpose : check if newUV destortes quadrangles around node,
1258 // and if ( crit == FIX_OLD ) fix newUV in this case
1259 //=======================================================================
1261 enum { CHECK_NEW_IN, CHECK_NEW_OK, FIX_OLD };
1263 static bool checkQuads (const TIsoNode* node,
1265 const bool reversed,
1266 const int crit = FIX_OLD,
1267 double fixSize = 0.)
1269 gp_XY oldUV = node->myUV, oldUVFixed[4], oldUVImpr[4];
1270 int nbOldFix = 0, nbOldImpr = 0;
1271 double newBadRate = 0, oldBadRate = 0;
1272 bool newIsOk = true, newIsIn = true, oldIsIn = true, oldIsOk = true;
1273 int i, dir1 = 0, dir2 = 3;
1274 for ( ; dir1 < 4; dir1++, dir2++ ) // loop on 4 quadrangles around <node>
1276 if ( dir2 > 3 ) dir2 = 0;
1278 // walking counterclockwise around a quad,
1279 // nodes are in the order: node, n[0], n[1], n[2]
1280 n[0] = getNextNode( node, dir1 );
1281 n[2] = getNextNode( node, dir2 );
1282 if ( !n[0] || !n[2] ) continue;
1283 n[1] = getNextNode( n[0], dir2 );
1284 if ( !n[1] ) n[1] = getNextNode( n[2], dir1 );
1285 bool isTriangle = ( !n[1] );
1287 TIsoNode* tmp = n[0]; n[0] = n[2]; n[2] = tmp;
1289 // if ( fixSize != 0 ) {
1290 // cout<<"NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1291 // cout<<"\t0: "<<n[0]->myInitUV.X()<<" "<<n[0]->myInitUV.Y()<<" UV: "<<n[0]->myUV.X()<<" "<<n[0]->myUV.Y()<<endl;
1292 // cout<<"\t1: "<<n[1]->myInitUV.X()<<" "<<n[1]->myInitUV.Y()<<" UV: "<<n[1]->myUV.X()<<" "<<n[1]->myUV.Y()<<endl;
1293 // cout<<"\t2: "<<n[2]->myInitUV.X()<<" "<<n[2]->myInitUV.Y()<<" UV: "<<n[2]->myUV.X()<<" "<<n[2]->myUV.Y()<<endl;
1295 // check if a quadrangle is degenerated
1297 ((( n[0]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN ) ||
1298 (( n[2]->myUV - n[1]->myUV ).SquareModulus() <= DBL_MIN )))
1301 ( n[0]->myUV - n[2]->myUV ).SquareModulus() <= DBL_MIN )
1304 // find min size of the diagonal node-n[1]
1305 double minDiag = fixSize;
1306 if ( minDiag == 0. ) {
1307 double maxLen2 = ( node->myUV - n[0]->myUV ).SquareModulus();
1308 if ( !isTriangle ) {
1309 maxLen2 = Max( maxLen2, ( n[0]->myUV - n[1]->myUV ).SquareModulus() );
1310 maxLen2 = Max( maxLen2, ( n[1]->myUV - n[2]->myUV ).SquareModulus() );
1312 maxLen2 = Max( maxLen2, ( n[2]->myUV - node->myUV ).SquareModulus() );
1313 minDiag = sqrt( maxLen2 ) * M_PI / 60.; // ~ maxLen * Sin( 3 deg )
1316 // check if newUV is behind 3 dirs: n[0]-n[1], n[1]-n[2] and n[0]-n[2]
1317 // ( behind means "to the right of")
1319 // 1. newUV is not behind 01 and 12 dirs
1320 // 2. or newUV is not behind 02 dir and n[2] is convex
1321 bool newIn[3] = { true, true, true }, newOk[3] = { true, true, true };
1322 bool wasIn[3] = { true, true, true }, wasOk[3] = { true, true, true };
1323 gp_Vec2d moveVec[3], outVec[3];
1324 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1326 bool isDiag = ( i == 2 );
1327 if ( isDiag && newOk[0] && newOk[1] && !isTriangle )
1331 sideDir = gp_Vec2d( n[0]->myUV, n[2]->myUV );
1333 sideDir = gp_Vec2d( n[i]->myUV, n[i+1]->myUV );
1335 gp_Vec2d outDir( sideDir.Y(), -sideDir.X() ); // to the right
1337 gp_Vec2d newDir( n[i]->myUV, newUV );
1338 gp_Vec2d oldDir( n[i]->myUV, oldUV );
1340 if ( newIsOk ) newOk[i] = ( outDir * newDir < -minDiag );
1341 if ( newIsIn ) newIn[i] = ( outDir * newDir < 0 );
1342 if ( crit == FIX_OLD ) {
1343 wasIn[i] = ( outDir * oldDir < 0 );
1344 wasOk[i] = ( outDir * oldDir < -minDiag );
1346 newBadRate += outDir * newDir;
1348 oldBadRate += outDir * oldDir;
1351 double oldDist = - outDir * oldDir;//, l2 = outDir * newDir;
1352 // double r = ( l1 - minDiag ) / ( l1 + l2 );
1353 // moveVec[i] = r * gp_Vec2d( node->myUV, newUV );
1354 moveVec[i] = ( oldDist - minDiag ) * outDir;
1359 // check if n[2] is convex
1362 convex = ( outVec[0] * gp_Vec2d( n[1]->myUV, n[2]->myUV ) < 0 );
1364 bool isNewOk = ( newOk[0] && newOk[1] ) || ( newOk[2] && convex );
1365 bool isNewIn = ( newIn[0] && newIn[1] ) || ( newIn[2] && convex );
1366 newIsOk = ( newIsOk && isNewOk );
1367 newIsIn = ( newIsIn && isNewIn );
1369 if ( crit != FIX_OLD ) {
1370 if ( crit == CHECK_NEW_OK && !newIsOk ) break;
1371 if ( crit == CHECK_NEW_IN && !newIsIn ) break;
1375 bool isOldIn = ( wasIn[0] && wasIn[1] ) || ( wasIn[2] && convex );
1376 bool isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1377 oldIsIn = ( oldIsIn && isOldIn );
1378 oldIsOk = ( oldIsOk && isOldIn );
1381 if ( !isOldIn ) { // node is outside a quadrangle
1382 // move newUV inside a quadrangle
1383 //MESSAGE("Quad "<< dir1 << " WAS IN " << wasIn[0]<<" "<<wasIn[1]<<" "<<wasIn[2]);
1384 // node and newUV are outside: push newUV inside
1386 if ( convex || isTriangle ) {
1387 uv = 0.5 * ( n[0]->myUV + n[2]->myUV ) - minDiag * outVec[2].XY();
1390 gp_Vec2d out = outVec[0].Normalized() + outVec[1].Normalized();
1391 double outSize = out.Magnitude();
1392 if ( outSize > DBL_MIN )
1395 out.SetCoord( -outVec[1].Y(), outVec[1].X() );
1396 uv = n[1]->myUV - minDiag * out.XY();
1398 oldUVFixed[ nbOldFix++ ] = uv;
1399 //node->myUV = newUV;
1401 else if ( !isOldOk ) {
1402 // try to fix old UV: move node inside as less as possible
1403 //MESSAGE("Quad "<< dir1 << " old is BAD, try to fix old, minDiag: "<< minDiag);
1404 gp_XY uv1, uv2 = node->myUV;
1405 for ( i = isTriangle ? 2 : 0; i < 3; i++ ) // mark not computed vectors
1407 moveVec[ i ].SetCoord( 1, 2e100); // not use this vector
1408 while ( !isOldOk ) {
1409 // find the least moveVec
1411 double minMove2 = 1e100;
1412 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1414 if ( moveVec[i].Coord(1) < 1e100 ) {
1415 double move2 = moveVec[i].SquareMagnitude();
1416 if ( move2 < minMove2 ) {
1425 // move node to newUV
1426 uv1 = node->myUV + moveVec[ iMin ].XY();
1427 uv2 += moveVec[ iMin ].XY();
1428 moveVec[ iMin ].SetCoord( 1, 2e100); // not use this vector more
1429 // check if uv1 is ok
1430 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1431 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv1 ) < -minDiag );
1432 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1434 oldUVImpr[ nbOldImpr++ ] = uv1;
1436 // check if uv2 is ok
1437 for ( i = isTriangle ? 2 : 0; i < 3; i++ )
1438 wasOk[i] = ( outVec[i] * gp_Vec2d( n[i]->myUV, uv2 ) < -minDiag );
1439 isOldOk = ( wasOk[0] && wasOk[1] ) || ( wasOk[2] && convex );
1441 oldUVImpr[ nbOldImpr++ ] = uv2;
1446 } // loop on 4 quadrangles around <node>
1448 if ( crit == CHECK_NEW_OK )
1450 if ( crit == CHECK_NEW_IN )
1459 if ( oldIsIn && nbOldImpr ) {
1460 // MESSAGE(" Try to improve UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1461 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1462 gp_XY uv = oldUVImpr[ 0 ];
1463 for ( int i = 1; i < nbOldImpr; i++ )
1464 uv += oldUVImpr[ i ];
1466 if ( checkQuads( node, uv, reversed, CHECK_NEW_OK )) {
1471 //MESSAGE(" Cant improve UV, uv: "<<uv.X()<<" "<<uv.Y());
1474 if ( !oldIsIn && nbOldFix ) {
1475 // MESSAGE(" Try to fix UV, init: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<
1476 // " uv: "<<oldUV.X()<<" "<<oldUV.Y() );
1477 gp_XY uv = oldUVFixed[ 0 ];
1478 for ( int i = 1; i < nbOldFix; i++ )
1479 uv += oldUVFixed[ i ];
1481 if ( checkQuads( node, uv, reversed, CHECK_NEW_IN )) {
1486 //MESSAGE(" Cant fix UV, uv: "<<uv.X()<<" "<<uv.Y());
1489 if ( newIsIn && oldIsIn )
1490 newUV = ( newBadRate < oldBadRate ) ? newUV : oldUV;
1491 else if ( !newIsIn )
1498 //=======================================================================
1499 //function : compUVByElasticIsolines
1500 //purpose : compute UV as nodes of iso-poly-lines consisting of
1501 // segments keeping relative size as in the pattern
1502 //=======================================================================
1503 //#define DEB_COMPUVBYELASTICISOLINES
1504 bool SMESH_Pattern::
1505 compUVByElasticIsolines(const list< list< TPoint* > >& theBndPoints,
1506 const list< TPoint* >& thePntToCompute)
1508 return false; // PAL17233
1509 //cout << "============================== KEY POINTS =============================="<<endl;
1510 // list< int >::iterator kpIt = myKeyPointIDs.begin();
1511 // for ( ; kpIt != myKeyPointIDs.end(); kpIt++ ) {
1512 // TPoint& p = myPoints[ *kpIt ];
1513 // cout << "INIT: " << p.myInitUV.X() << " " << p.myInitUV.Y() <<
1514 // " UV: " << p.myUV.X() << " " << p.myUV.Y() << endl;
1516 //cout << "=============================="<<endl;
1518 // Define parameters of iso-grid nodes in U and V dir
1520 set< double > paramSet[ 2 ];
1521 list< list< TPoint* > >::const_iterator pListIt;
1522 list< TPoint* >::const_iterator pIt;
1523 for ( pListIt = theBndPoints.begin(); pListIt != theBndPoints.end(); pListIt++ ) {
1524 const list< TPoint* > & pList = * pListIt;
1525 for ( pIt = pList.begin(); pIt != pList.end(); pIt++ ) {
1526 paramSet[0].insert( (*pIt)->myInitUV.X() );
1527 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1530 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
1531 paramSet[0].insert( (*pIt)->myInitUV.X() );
1532 paramSet[1].insert( (*pIt)->myInitUV.Y() );
1534 // unite close parameters and split too long segments
1537 for ( iDir = 0; iDir < 2; iDir++ )
1539 set< double > & params = paramSet[ iDir ];
1540 double range = ( *params.rbegin() - *params.begin() );
1541 double toler = range / 1e6;
1542 tol[ iDir ] = toler;
1543 // double maxSegment = range / params.size() / 2.;
1545 // set< double >::iterator parIt = params.begin();
1546 // double prevPar = *parIt;
1547 // for ( parIt++; parIt != params.end(); parIt++ )
1549 // double segLen = (*parIt) - prevPar;
1550 // if ( segLen < toler )
1551 // ;//params.erase( prevPar ); // unite
1552 // else if ( segLen > maxSegment )
1553 // params.insert( prevPar + 0.5 * segLen ); // split
1554 // prevPar = (*parIt);
1558 // Make nodes of a grid of iso-poly-lines
1560 list < TIsoNode > nodes;
1561 typedef list < TIsoNode *> TIsoLine;
1562 map < double, TIsoLine > isoMap[ 2 ];
1564 set< double > & params0 = paramSet[ 0 ];
1565 set< double >::iterator par0It = params0.begin();
1566 for ( ; par0It != params0.end(); par0It++ )
1568 TIsoLine & isoLine0 = isoMap[0][ *par0It ]; // vertical isoline with const U
1569 set< double > & params1 = paramSet[ 1 ];
1570 set< double >::iterator par1It = params1.begin();
1571 for ( ; par1It != params1.end(); par1It++ )
1573 nodes.push_back( TIsoNode( *par0It, *par1It ) );
1574 isoLine0.push_back( & nodes.back() );
1575 isoMap[1][ *par1It ].push_back( & nodes.back() );
1579 // Compute intersections of boundaries with iso-lines:
1580 // only boundary nodes will have computed UV so far
1583 list< list< TPoint* > >::const_iterator bndIt = theBndPoints.begin();
1584 list< TIsoNode* > bndNodes; // nodes corresponding to outer theBndPoints
1585 for ( ; bndIt != theBndPoints.end(); bndIt++ )
1587 const list< TPoint* > & bndPoints = * bndIt;
1588 TPoint* prevP = bndPoints.back(); // this is the first point
1589 list< TPoint* >::const_iterator pIt = bndPoints.begin();
1590 // loop on the edge-points
1591 for ( ; pIt != bndPoints.end(); pIt++ )
1593 TPoint* point = *pIt;
1594 for ( iDir = 0; iDir < 2; iDir++ )
1596 const int iCoord = iDir + 1;
1597 const int iOtherCoord = 2 - iDir;
1598 double par1 = prevP->myInitUV.Coord( iCoord );
1599 double par2 = point->myInitUV.Coord( iCoord );
1600 double parDif = par2 - par1;
1601 if ( Abs( parDif ) <= DBL_MIN )
1603 // find iso-lines intersecting a bounadry
1604 double toler = tol[ 1 - iDir ];
1605 double minPar = Min ( par1, par2 );
1606 double maxPar = Max ( par1, par2 );
1607 map < double, TIsoLine >& isos = isoMap[ iDir ];
1608 map < double, TIsoLine >::iterator isoIt = isos.begin();
1609 for ( ; isoIt != isos.end(); isoIt++ )
1611 double isoParam = (*isoIt).first;
1612 if ( isoParam < minPar || isoParam > maxPar )
1614 double r = ( isoParam - par1 ) / parDif;
1615 gp_XY uv = ( 1 - r ) * prevP->myUV + r * point->myUV;
1616 gp_XY initUV = ( 1 - r ) * prevP->myInitUV + r * point->myInitUV;
1617 double otherPar = initUV.Coord( iOtherCoord ); // along isoline
1618 // find existing node with otherPar or insert a new one
1619 TIsoLine & isoLine = (*isoIt).second;
1621 TIsoLine::iterator nIt = isoLine.begin();
1622 for ( ; nIt != isoLine.end(); nIt++ ) {
1623 nodePar = (*nIt)->myInitUV.Coord( iOtherCoord );
1624 if ( nodePar >= otherPar )
1628 if ( Abs( nodePar - otherPar ) <= toler )
1629 node = ( nIt == isoLine.end() ) ? isoLine.back() : (*nIt);
1631 nodes.push_back( TIsoNode( initUV.X(), initUV.Y() ) );
1632 node = & nodes.back();
1633 isoLine.insert( nIt, node );
1635 node->SetNotMovable();
1637 uvBnd.Add( gp_Pnt2d( uv ));
1638 // cout << "bnd: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<node->myUV.X()<<" "<<node->myUV.Y()<<endl;
1640 gp_XY tgt( point->myUV - prevP->myUV );
1641 if ( ::IsEqual( r, 1. ))
1642 node->myDir[ 0 ] = tgt;
1643 else if ( ::IsEqual( r, 0. ))
1644 node->myDir[ 1 ] = tgt;
1646 node->myDir[ 1 ] = node->myDir[ 0 ] = tgt;
1647 // keep boundary nodes corresponding to boundary points
1648 if ( bndIt == theBndPoints.begin() && ::IsEqual( r, 1. ))
1649 if ( bndNodes.empty() || bndNodes.back() != node )
1650 bndNodes.push_back( node );
1651 } // loop on isolines
1652 } // loop on 2 directions
1654 } // loop on boundary points
1655 } // loop on boundaries
1657 // Define orientation
1659 // find the point with the least X
1660 double leastX = DBL_MAX;
1661 TIsoNode * leftNode;
1662 list < TIsoNode >::iterator nodeIt = nodes.begin();
1663 for ( ; nodeIt != nodes.end(); nodeIt++ ) {
1664 TIsoNode & node = *nodeIt;
1665 if ( node.IsUVComputed() && node.myUV.X() < leastX ) {
1666 leastX = node.myUV.X();
1669 // if ( node.IsUVComputed() ) {
1670 // cout << "bndNode INIT: " << node.myInitUV.X()<<" "<<node.myInitUV.Y()<<" UV: "<<
1671 // node.myUV.X()<<" "<<node.myUV.Y()<<endl<<
1672 // " dir0: "<<node.myDir[0].X()<<" "<<node.myDir[0].Y() <<
1673 // " dir1: "<<node.myDir[1].X()<<" "<<node.myDir[1].Y() << endl;
1676 bool reversed = ( leftNode->myDir[0].Y() + leftNode->myDir[1].Y() > 0 );
1677 //SCRUTE( reversed );
1679 // Prepare internal nodes:
1681 // 2. compute ratios
1682 // 3. find boundary nodes for each node
1683 // 4. remove nodes out of the boundary
1684 for ( iDir = 0; iDir < 2; iDir++ )
1686 const int iCoord = 2 - iDir; // coord changing along an isoline
1687 map < double, TIsoLine >& isos = isoMap[ iDir ];
1688 map < double, TIsoLine >::iterator isoIt = isos.begin();
1689 for ( ; isoIt != isos.end(); isoIt++ )
1691 TIsoLine & isoLine = (*isoIt).second;
1692 bool firstCompNodeFound = false;
1693 TIsoLine::iterator lastCompNodePos, nPrevIt, nIt, nNextIt, nIt2;
1694 nPrevIt = nIt = nNextIt = isoLine.begin();
1696 nNextIt++; nNextIt++;
1697 while ( nIt != isoLine.end() )
1699 // 1. connect prev - cur
1700 TIsoNode* node = *nIt, * prevNode = *nPrevIt;
1701 if ( !firstCompNodeFound && prevNode->IsUVComputed() ) {
1702 firstCompNodeFound = true;
1703 lastCompNodePos = nPrevIt;
1705 if ( firstCompNodeFound ) {
1706 node->SetNext( prevNode, iDir, 0 );
1707 prevNode->SetNext( node, iDir, 1 );
1710 if ( nNextIt != isoLine.end() ) {
1711 double par1 = prevNode->myInitUV.Coord( iCoord );
1712 double par2 = node->myInitUV.Coord( iCoord );
1713 double par3 = (*nNextIt)->myInitUV.Coord( iCoord );
1714 node->myRatio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1716 // 3. find boundary nodes
1717 if ( node->IsUVComputed() )
1718 lastCompNodePos = nIt;
1719 else if ( firstCompNodeFound && nNextIt != isoLine.end() ) {
1720 TIsoNode* bndNode1 = *lastCompNodePos, *bndNode2 = 0;
1721 for ( nIt2 = nNextIt; nIt2 != isoLine.end(); nIt2++ )
1722 if ( (*nIt2)->IsUVComputed() )
1724 if ( nIt2 != isoLine.end() ) {
1726 node->SetBoundaryNode( bndNode1, iDir, 0 );
1727 node->SetBoundaryNode( bndNode2, iDir, 1 );
1728 // cout << "--------------------------------------------------"<<endl;
1729 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<<endl<<
1730 // " dir0: "<<bndNode1->myDir[0].X()<<" "<<bndNode1->myDir[0].Y() <<
1731 // " dir1: "<<bndNode1->myDir[1].X()<<" "<<bndNode1->myDir[1].Y() << endl;
1732 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl<<
1733 // " dir0: "<<bndNode2->myDir[0].X()<<" "<<bndNode2->myDir[0].Y() <<
1734 // " dir1: "<<bndNode2->myDir[1].X()<<" "<<bndNode2->myDir[1].Y() << endl;
1737 /// WHAT IN THIS CASE ????????????? MAY BE THIS, I AM NOT SURE :(
1738 node->SetBoundaryNode( 0, iDir, 0 );
1739 node->SetBoundaryNode( 0, iDir, 1 );
1743 if ( nNextIt != isoLine.end() ) nNextIt++;
1744 // 4. remove nodes out of the boundary
1745 if ( !firstCompNodeFound )
1746 isoLine.pop_front();
1747 } // loop on isoLine nodes
1749 // remove nodes after the boundary
1750 // for ( nIt = ++lastCompNodePos; nIt != isoLine.end(); nIt++ )
1751 // (*nIt)->SetNotMovable();
1752 isoLine.erase( ++lastCompNodePos, isoLine.end() );
1753 } // loop on isolines
1754 } // loop on 2 directions
1756 // Compute local isoline direction for internal nodes
1759 map < double, TIsoLine >& isos = isoMap[ 0 ]; // vertical isolines with const U
1760 map < double, TIsoLine >::iterator isoIt = isos.begin();
1761 for ( ; isoIt != isos.end(); isoIt++ )
1763 TIsoLine & isoLine = (*isoIt).second;
1764 TIsoLine::iterator nIt = isoLine.begin();
1765 for ( ; nIt != isoLine.end(); nIt++ )
1767 TIsoNode* node = *nIt;
1768 if ( node->IsUVComputed() || !node->IsMovable() )
1770 gp_Vec2d aTgt[2], aNorm[2];
1773 for ( iDir = 0; iDir < 2; iDir++ )
1775 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
1776 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
1777 if ( !bndNode1 || !bndNode2 ) {
1781 const int iCoord = 2 - iDir; // coord changing along an isoline
1782 double par1 = bndNode1->myInitUV.Coord( iCoord );
1783 double par2 = node->myInitUV.Coord( iCoord );
1784 double par3 = bndNode2->myInitUV.Coord( iCoord );
1785 ratio[ iDir ] = ( par2 - par1 ) / ( par3 - par1 );
1787 gp_Vec2d tgt1( bndNode1->myDir[0].XY() + bndNode1->myDir[1].XY() );
1788 gp_Vec2d tgt2( bndNode2->myDir[0].XY() + bndNode2->myDir[1].XY() );
1789 if ( bool( iDir ) == reversed ) tgt2.Reverse(); // along perpend. isoline
1790 else tgt1.Reverse();
1791 //cout<<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" | "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1793 if ( ratio[ iDir ] < 0.5 )
1794 aNorm[ iDir ] = gp_Vec2d( -tgt1.Y(), tgt1.X() ); // rotate tgt to the left
1796 aNorm[ iDir ] = gp_Vec2d( -tgt2.Y(), tgt2.X() );
1798 aNorm[ iDir ].Reverse(); // along iDir isoline
1800 double angle = tgt1.Angle( tgt2 ); // [-PI, PI]
1801 // maybe angle is more than |PI|
1802 if ( Abs( angle ) > PI / 2. ) {
1803 // check direction of the last but one perpendicular isoline
1804 TIsoNode* prevNode = bndNode2->GetNext( iDir, 0 );
1805 bndNode1 = prevNode->GetBoundaryNode( 1 - iDir, 0 );
1806 bndNode2 = prevNode->GetBoundaryNode( 1 - iDir, 1 );
1807 gp_Vec2d isoDir( bndNode1->myUV, bndNode2->myUV );
1808 if ( isoDir * tgt2 < 0 )
1810 double angle2 = tgt1.Angle( isoDir );
1811 //cout << " isoDir: "<< isoDir.X() <<" "<<isoDir.Y() << " ANGLE: "<< angle << " "<<angle2<<endl;
1812 if (angle2 * angle < 0 && // check the sign of an angle close to PI
1813 Abs ( Abs ( angle ) - PI ) <= PI / 180. ) {
1814 //MESSAGE("REVERSE ANGLE");
1817 if ( Abs( angle2 ) > Abs( angle ) ||
1818 ( angle2 * angle < 0 && Abs( angle2 ) > Abs( angle - angle2 ))) {
1819 //MESSAGE("Add PI");
1820 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1821 // cout <<"ISO: " << isoParam << " " << (*iso2It).first << endl;
1822 // cout << "bndNode1: " << bndNode1->myUV.X()<<" "<<bndNode1->myUV.Y()<< endl;
1823 // cout << "bndNode2: " << bndNode2->myUV.X()<<" "<<bndNode2->myUV.Y()<<endl;
1824 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1825 angle += ( angle < 0 ) ? 2. * PI : -2. * PI;
1828 aTgt[ iDir ] = tgt1.Rotated( angle * ratio[ iDir ] ).XY();
1832 for ( iDir = 0; iDir < 2; iDir++ )
1834 aTgt[iDir].Normalize();
1835 aNorm[1-iDir].Normalize();
1836 double r = Abs ( ratio[iDir] - 0.5 ) * 2.0; // [0,1] - distance from the middle
1839 node->myDir[iDir] = //aTgt[iDir];
1840 aNorm[1-iDir] * r + aTgt[iDir] * ( 1. - r );
1842 // cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1843 // cout <<" tgt: " << tgt1.X()<<" "<<tgt1.Y()<<" - "<< tgt2.X()<<" "<<tgt2.Y()<<endl;
1844 // cout << " isoDir: "<< node->myDir[0].X() <<" "<<node->myDir[0].Y()<<" | "
1845 // << node->myDir[1].X() <<" "<<node->myDir[1].Y()<<endl;
1847 } // loop on iso nodes
1848 } // loop on isolines
1850 // Find nodes to start computing UV from
1852 list< TIsoNode* > startNodes;
1853 list< TIsoNode* >::iterator nIt = bndNodes.end();
1854 TIsoNode* node = *(--nIt);
1855 TIsoNode* prevNode = *(--nIt);
1856 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1858 TIsoNode* nextNode = *nIt;
1859 gp_Vec2d initTgt1( prevNode->myInitUV, node->myInitUV );
1860 gp_Vec2d initTgt2( node->myInitUV, nextNode->myInitUV );
1861 double initAngle = initTgt1.Angle( initTgt2 );
1862 double angle = node->myDir[0].Angle( node->myDir[1] );
1863 if ( reversed ) angle = -angle;
1864 if ( initAngle > angle && initAngle - angle > M_PI / 2.1 ) {
1865 // find a close internal node
1866 TIsoNode* nClose = 0;
1867 list< TIsoNode* > testNodes;
1868 testNodes.push_back( node );
1869 list< TIsoNode* >::iterator it = testNodes.begin();
1870 for ( ; !nClose && it != testNodes.end(); it++ )
1872 for (int i = 0; i < 4; i++ )
1874 nClose = (*it)->myNext[ i ];
1876 if ( !nClose->IsUVComputed() )
1879 testNodes.push_back( nClose );
1885 startNodes.push_back( nClose );
1886 // cout << "START: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<" UV: "<<
1887 // node->myUV.X()<<" "<<node->myUV.Y()<<endl<<
1888 // "initAngle: " << initAngle << " angle: " << angle << endl;
1889 // cout <<" init tgt: " << initTgt1.X()<<" "<<initTgt1.Y()<<" | "<< initTgt2.X()<<" "<<initTgt2.Y()<<endl;
1890 // cout << " tgt: "<< node->myDir[ 0 ].X() <<" "<<node->myDir[ 0 ].Y()<<" | "<<
1891 // node->myDir[ 1 ].X() <<" "<<node->myDir[ 1 ].Y()<<endl;
1892 // cout << "CLOSE: "<<nClose->myInitUV.X()<<" "<<nClose->myInitUV.Y()<<endl;
1898 // Compute starting UV of internal nodes
1900 list < TIsoNode* > internNodes;
1901 bool needIteration = true;
1902 if ( startNodes.empty() ) {
1903 MESSAGE( " Starting UV by compUVByIsoIntersection()");
1904 needIteration = false;
1905 map < double, TIsoLine >& isos = isoMap[ 0 ];
1906 map < double, TIsoLine >::iterator isoIt = isos.begin();
1907 for ( ; isoIt != isos.end(); isoIt++ )
1909 TIsoLine & isoLine = (*isoIt).second;
1910 TIsoLine::iterator nIt = isoLine.begin();
1911 for ( ; !needIteration && nIt != isoLine.end(); nIt++ )
1913 TIsoNode* node = *nIt;
1914 if ( !node->IsUVComputed() && node->IsMovable() ) {
1915 internNodes.push_back( node );
1917 if ( !compUVByIsoIntersection(theBndPoints, node->myInitUV,
1918 node->myUV, needIteration ))
1919 node->myUV = node->myInitUV;
1923 if ( needIteration )
1924 for ( nIt = bndNodes.begin(); nIt != bndNodes.end(); nIt++ )
1926 TIsoNode* node = *nIt, *nClose = 0;
1927 list< TIsoNode* > testNodes;
1928 testNodes.push_back( node );
1929 list< TIsoNode* >::iterator it = testNodes.begin();
1930 for ( ; !nClose && it != testNodes.end(); it++ )
1932 for (int i = 0; i < 4; i++ )
1934 nClose = (*it)->myNext[ i ];
1936 if ( !nClose->IsUVComputed() && nClose->IsMovable() )
1939 testNodes.push_back( nClose );
1945 startNodes.push_back( nClose );
1949 double aMin[2], aMax[2], step[2];
1950 uvBnd.Get( aMin[0], aMin[1], aMax[0], aMax[1] );
1951 double minUvSize = Min ( aMax[0]-aMin[0], aMax[1]-aMin[1] );
1952 step[0] = minUvSize / paramSet[ 0 ].size() / 10;
1953 step[1] = minUvSize / paramSet[ 1 ].size() / 10;
1954 //cout << "STEPS: " << step[0] << " " << step[1]<< endl;
1956 for ( nIt = startNodes.begin(); nIt != startNodes.end(); nIt++ )
1958 TIsoNode *node = *nIt;
1959 if ( node->IsUVComputed() || !node->IsMovable() )
1961 gp_XY newUV( 0, 0 ), sumDir( 0, 0 );
1962 int nbComp = 0, nbPrev = 0;
1963 for ( iDir = 0; iDir < 2; iDir++ )
1965 TIsoNode* prevNode1 = 0, *prevNode2 = 0;
1966 TIsoNode* n = node->GetNext( iDir, 0 );
1967 if ( n->IsUVComputed() )
1970 startNodes.push_back( n );
1971 n = node->GetNext( iDir, 1 );
1972 if ( n->IsUVComputed() )
1975 startNodes.push_back( n );
1977 prevNode1 = prevNode2;
1980 if ( prevNode1 ) nbPrev++;
1981 if ( prevNode2 ) nbPrev++;
1984 double prevPar = prevNode1->myInitUV.Coord( 2 - iDir );
1985 double par = node->myInitUV.Coord( 2 - iDir );
1986 bool isEnd = ( prevPar > par );
1987 // dir = node->myDir[ 1 - iDir ].XY() * ( isEnd ? -1. : 1. );
1988 //cout << "__________"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
1989 TIsoNode* bndNode = node->GetBoundaryNode( iDir, isEnd );
1991 MESSAGE("Why we are here?");
1994 gp_XY tgt( bndNode->myDir[0].XY() + bndNode->myDir[1].XY() );
1995 dir.SetCoord( 1, tgt.Y() * ( reversed ? 1 : -1 ));
1996 dir.SetCoord( 2, tgt.X() * ( reversed ? -1 : 1 ));
1997 //cout << "bndNode UV: " << bndNode->myUV.X()<<" "<<bndNode->myUV.Y()<< endl;
1998 // cout << " tgt: "<< bndNode->myDir[ 0 ].X() <<" "<<bndNode->myDir[ 0 ].Y()<<" | "<<
1999 // bndNode->myDir[ 1 ].X() <<" "<<bndNode->myDir[ 1 ].Y()<<endl;
2000 //cout << "prevNode UV: " << prevNode1->myUV.X()<<" "<<prevNode1->myUV.Y()<<
2001 //" par: " << prevPar << endl;
2002 // cout <<" tgt: " << tgt.X()<<" "<<tgt.Y()<<endl;
2003 //cout << " DIR: "<< dir.X() <<" "<<dir.Y()<<endl;
2005 //cout << "____2next______"<<endl<< "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2006 gp_XY & uv1 = prevNode1->myUV;
2007 gp_XY & uv2 = prevNode2->myUV;
2008 // dir = ( uv2 - uv1 );
2009 // double len = dir.Modulus();
2010 // if ( len > DBL_MIN )
2011 // dir /= len * 0.5;
2012 double r = node->myRatio[ iDir ];
2013 newUV += uv1 * ( 1 - r ) + uv2 * r;
2016 newUV += prevNode1->myUV + dir * step[ iDir ];
2022 if ( !nbComp ) continue;
2025 //cout << "NODE: "<<node->myInitUV.X()<<" "<<node->myInitUV.Y()<<endl;
2027 // check if a quadrangle is not distorted
2029 //int crit = ( nbPrev == 4 ) ? FIX_OLD : CHECK_NEW_IN;
2030 if ( !checkQuads( node, newUV, reversed, FIX_OLD, step[0] + step[1] )) {
2031 //cout <<" newUV: " << node->myUV.X() << " "<<node->myUV.Y() << " nbPrev: "<<nbPrev<< endl;
2032 // cout << "_FIX_INIT_ fixedUV: " << newUV.X() << " "<<newUV.Y() << endl;
2036 internNodes.push_back( node );
2041 static int maxNbIter = 100;
2042 #ifdef DEB_COMPUVBYELASTICISOLINES
2044 bool useNbMoveNode = 0;
2045 static int maxNbNodeMove = 100;
2048 if ( !useNbMoveNode )
2049 maxNbIter = ( maxNbIter < 0 ) ? 100 : -1;
2054 if ( !needIteration) break;
2055 #ifdef DEB_COMPUVBYELASTICISOLINES
2056 if ( nbIter >= maxNbIter ) break;
2059 list < TIsoNode* >::iterator nIt = internNodes.begin();
2060 for ( ; nIt != internNodes.end(); nIt++ ) {
2061 #ifdef DEB_COMPUVBYELASTICISOLINES
2063 cout << nbNodeMove <<" =================================================="<<endl;
2065 TIsoNode * node = *nIt;
2069 for ( iDir = 0; iDir < 2; iDir++ )
2071 gp_XY & uv1 = node->GetNext( iDir, 0 )->myUV;
2072 gp_XY & uv2 = node->GetNext( iDir, 1 )->myUV;
2073 double r = node->myRatio[ iDir ];
2074 loc[ iDir ] = uv1 * ( 1 - r ) + uv2 * r;
2075 // line[ iDir ].SetLocation( loc[ iDir ] );
2076 // line[ iDir ].SetDirection( node->myDir[ iDir ] );
2079 bool ok = true; // <- stupid fix TO AVOID PB OF NODES WITH NULL BND NODES
2080 // double locR[2] = { 0, 0 };
2081 for ( iDir = 0; iDir < 2; iDir++ )
2083 const int iCoord = 2 - iDir; // coord changing along an isoline
2084 TIsoNode* bndNode1 = node->GetBoundaryNode( iDir, 0 );
2085 TIsoNode* bndNode2 = node->GetBoundaryNode( iDir, 1 );
2086 if ( !bndNode1 || !bndNode2 ) {
2089 double par1 = bndNode1->myInitUV.Coord( iCoord );
2090 double par2 = node->myInitUV.Coord( iCoord );
2091 double par3 = bndNode2->myInitUV.Coord( iCoord );
2092 double r = ( par2 - par1 ) / ( par3 - par1 );
2093 r = Abs ( r - 0.5 ) * 2.0; // [0,1] - distance from the middle
2094 // locR[ iDir ] = ( 1 - r * r ) * 0.25;
2096 //locR[0] = locR[1] = 0.25;
2097 // intersect the 2 lines and move a node
2098 //IntAna2d_AnaIntersection inter( line[0], line[1] );
2099 if ( ok /*inter.IsDone() && inter.NbPoints() ==*/ )
2101 // double intR = 1 - locR[0] - locR[1];
2102 // gp_XY newUV = inter.Point(1).Value().XY();
2103 // if ( !checkQuads( node, newUV, reversed, CHECK_NEW_IN ))
2104 // newUV = ( locR[0] * loc[0] + locR[1] * loc[1] ) / ( 1 - intR );
2106 // newUV = intR * newUV + locR[0] * loc[0] + locR[1] * loc[1];
2107 gp_XY newUV = 0.5 * ( loc[0] + loc[1] );
2108 // avoid parallel isolines intersection
2109 checkQuads( node, newUV, reversed );
2111 maxMove = Max( maxMove, ( newUV - node->myUV ).SquareModulus());
2113 } // intersection found
2114 #ifdef DEB_COMPUVBYELASTICISOLINES
2115 if (useNbMoveNode && ++nbNodeMove >= maxNbNodeMove ) break;
2117 } // loop on internal nodes
2118 #ifdef DEB_COMPUVBYELASTICISOLINES
2119 if (useNbMoveNode && nbNodeMove >= maxNbNodeMove ) break;
2121 } while ( maxMove > 1e-8 && nbIter++ < maxNbIter );
2123 MESSAGE( "compUVByElasticIsolines(): Nb iterations " << nbIter << " dist: " << sqrt( maxMove ));
2125 if ( nbIter >= maxNbIter && sqrt(maxMove) > minUvSize * 0.05 ) {
2126 MESSAGE( "compUVByElasticIsolines() failed: "<<sqrt(maxMove)<<">"<<minUvSize * 0.05);
2127 #ifndef DEB_COMPUVBYELASTICISOLINES
2132 // Set computed UV to points
2134 for ( pIt = thePntToCompute.begin(); pIt != thePntToCompute.end(); pIt++ ) {
2135 TPoint* point = *pIt;
2136 //gp_XY oldUV = point->myUV;
2137 double minDist = DBL_MAX;
2138 list < TIsoNode >::iterator nIt = nodes.begin();
2139 for ( ; nIt != nodes.end(); nIt++ ) {
2140 double dist = ( (*nIt).myInitUV - point->myInitUV ).SquareModulus();
2141 if ( dist < minDist ) {
2143 point->myUV = (*nIt).myUV;
2152 //=======================================================================
2153 //function : setFirstEdge
2154 //purpose : choose the best first edge of theWire; return the summary distance
2155 // between point UV computed by isolines intersection and
2156 // eventual UV got from edge p-curves
2157 //=======================================================================
2159 //#define DBG_SETFIRSTEDGE
2160 double SMESH_Pattern::setFirstEdge (list< TopoDS_Edge > & theWire, int theFirstEdgeID)
2162 int iE, nbEdges = theWire.size();
2166 // Transform UVs computed by iso to fit bnd box of a wire
2168 // max nb of points on an edge
2170 int eID = theFirstEdgeID;
2171 for ( iE = 0; iE < nbEdges; iE++ )
2172 maxNbPnt = Max ( maxNbPnt, getShapePoints( eID++ ).size() );
2174 // compute bnd boxes
2175 TopoDS_Face face = TopoDS::Face( myShape );
2176 Bnd_Box2d bndBox, eBndBox;
2177 eID = theFirstEdgeID;
2178 list< TopoDS_Edge >::iterator eIt;
2179 list< TPoint* >::iterator pIt;
2180 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2182 // UV by isos stored in TPoint.myXYZ
2183 list< TPoint* > & ePoints = getShapePoints( eID++ );
2184 for ( pIt = ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2186 bndBox.Add( gp_Pnt2d( p->myXYZ.X(), p->myXYZ.Y() ));
2188 // UV by an edge p-curve
2190 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface( *eIt, face, f, l );
2191 double dU = ( l - f ) / ( maxNbPnt - 1 );
2192 for ( int i = 0; i < maxNbPnt; i++ )
2193 eBndBox.Add( C2d->Value( f + i * dU ));
2196 // transform UVs by isos
2197 double minPar[2], maxPar[2], eMinPar[2], eMaxPar[2];
2198 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2199 eBndBox.Get( eMinPar[0], eMinPar[1], eMaxPar[0], eMaxPar[1] );
2200 #ifdef DBG_SETFIRSTEDGE
2201 MESSAGE ( "EDGES: X: " << eMinPar[0] << " - " << eMaxPar[0] << " Y: "
2202 << eMinPar[1] << " - " << eMaxPar[1] );
2204 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2206 double dMin = eMinPar[i] - minPar[i];
2207 double dMax = eMaxPar[i] - maxPar[i];
2208 double dPar = maxPar[i] - minPar[i];
2209 eID = theFirstEdgeID;
2210 for ( iE = 0; iE < nbEdges; iE++ ) // loop on edges of a boundary
2212 list< TPoint* > & ePoints = getShapePoints( eID++ );
2213 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) // loop on edge points
2215 double par = (*pIt)->myXYZ.Coord( iC );
2216 double r = ( par - minPar[i] ) / dPar;
2217 par += ( 1 - r ) * dMin + r * dMax;
2218 (*pIt)->myXYZ.SetCoord( iC, par );
2224 double minDist = DBL_MAX;
2225 for ( iE = 0 ; iE < nbEdges; iE++ )
2227 #ifdef DBG_SETFIRSTEDGE
2228 MESSAGE ( " VARIANT " << iE );
2230 // evaluate the distance between UV computed by the 2 methods:
2231 // by isos intersection ( myXYZ ) and by edge p-curves ( myUV )
2233 int eID = theFirstEdgeID;
2234 for ( eIt = theWire.begin(); eIt != theWire.end(); eIt++ )
2236 list< TPoint* > & ePoints = getShapePoints( eID++ );
2237 computeUVOnEdge( *eIt, ePoints );
2238 for ( pIt = ++ePoints.begin(); pIt != ePoints.end(); pIt++ ) {
2240 dist += ( p->myUV - gp_XY( p->myXYZ.X(), p->myXYZ.Y() )).SquareModulus();
2241 #ifdef DBG_SETFIRSTEDGE
2242 MESSAGE ( " ISO : ( " << p->myXYZ.X() << ", "<< p->myXYZ.Y() << " ) PCURVE : ( " <<
2243 p->myUV.X() << ", " << p->myUV.Y() << ") " );
2247 #ifdef DBG_SETFIRSTEDGE
2248 MESSAGE ( "dist -- " << dist );
2250 if ( dist < minDist ) {
2252 eBest = theWire.front();
2254 // check variant with another first edge
2255 theWire.splice( theWire.begin(), theWire, --theWire.end(), theWire.end() );
2257 // put the best first edge to the theWire front
2258 if ( eBest != theWire.front() ) {
2259 eIt = find ( theWire.begin(), theWire.end(), eBest );
2260 theWire.splice( theWire.begin(), theWire, eIt, theWire.end() );
2266 //=======================================================================
2267 //function : sortSameSizeWires
2268 //purpose : sort wires in theWireList from theFromWire until theToWire,
2269 // the wires are set in the order to correspond to the order
2270 // of boundaries; after sorting, edges in the wires are put
2271 // in a good order, point UVs on edges are computed and points
2272 // are appended to theEdgesPointsList
2273 //=======================================================================
2275 bool SMESH_Pattern::sortSameSizeWires (TListOfEdgesList & theWireList,
2276 const TListOfEdgesList::iterator& theFromWire,
2277 const TListOfEdgesList::iterator& theToWire,
2278 const int theFirstEdgeID,
2279 list< list< TPoint* > >& theEdgesPointsList )
2281 TopoDS_Face F = TopoDS::Face( myShape );
2282 int iW, nbWires = 0;
2283 TListOfEdgesList::iterator wlIt = theFromWire;
2284 while ( wlIt++ != theToWire )
2287 // Recompute key-point UVs by isolines intersection,
2288 // compute CG of key-points for each wire and bnd boxes of GCs
2291 gp_XY orig( gp::Origin2d().XY() );
2292 vector< gp_XY > vGcVec( nbWires, orig ), gcVec( nbWires, orig );
2293 Bnd_Box2d bndBox, vBndBox;
2294 int eID = theFirstEdgeID;
2295 list< TopoDS_Edge >::iterator eIt;
2296 for ( iW = 0, wlIt = theFromWire; wlIt != theToWire; wlIt++, iW++ )
2298 list< TopoDS_Edge > & wire = *wlIt;
2299 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2301 list< TPoint* > & ePoints = getShapePoints( eID++ );
2302 TPoint* p = ePoints.front();
2303 if ( !compUVByIsoIntersection( theEdgesPointsList, p->myInitUV, p->myUV, aBool )) {
2304 MESSAGE("cant sortSameSizeWires()");
2307 gcVec[iW] += p->myUV;
2308 bndBox.Add( gp_Pnt2d( p->myUV ));
2309 TopoDS_Vertex V = TopExp::FirstVertex( *eIt, true );
2310 gp_Pnt2d vXY = BRep_Tool::Parameters( V, F );
2311 vGcVec[iW] += vXY.XY();
2313 // keep the computed UV to compare against by setFirstEdge()
2314 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2316 gcVec[iW] /= nbWires;
2317 vGcVec[iW] /= nbWires;
2318 // cout << " Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2319 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2322 // Transform GCs computed by isos to fit in bnd box of GCs by vertices
2324 double minPar[2], maxPar[2], vMinPar[2], vMaxPar[2];
2325 bndBox.Get( minPar[0], minPar[1], maxPar[0], maxPar[1] );
2326 vBndBox.Get( vMinPar[0], vMinPar[1], vMaxPar[0], vMaxPar[1] );
2327 for ( int iC = 1, i = 0; i < 2; iC++, i++ ) // loop on 2 coordinates
2329 double dMin = vMinPar[i] - minPar[i];
2330 double dMax = vMaxPar[i] - maxPar[i];
2331 double dPar = maxPar[i] - minPar[i];
2332 if ( Abs( dPar ) <= DBL_MIN )
2334 for ( iW = 0; iW < nbWires; iW++ ) { // loop on GCs of wires
2335 double par = gcVec[iW].Coord( iC );
2336 double r = ( par - minPar[i] ) / dPar;
2337 par += ( 1 - r ) * dMin + r * dMax;
2338 gcVec[iW].SetCoord( iC, par );
2342 // Define boundary - wire correspondence by GC closeness
2344 TListOfEdgesList tmpWList;
2345 tmpWList.splice( tmpWList.end(), theWireList, theFromWire, theToWire );
2346 typedef map< int, TListOfEdgesList::iterator > TIntWirePosMap;
2347 TIntWirePosMap bndIndWirePosMap;
2348 vector< bool > bndFound( nbWires, false );
2349 for ( iW = 0, wlIt = tmpWList.begin(); iW < nbWires; iW++, wlIt++ )
2351 // cout << " TRSF Wire " << iW << " iso: " << gcVec[iW].X() << " " << gcVec[iW].Y() << endl <<
2352 // " \t vertex: " << vGcVec[iW].X() << " " << vGcVec[iW].Y() << endl;
2353 double minDist = DBL_MAX;
2354 gp_XY & wGc = vGcVec[ iW ];
2356 for ( int iB = 0; iB < nbWires; iB++ ) {
2357 if ( bndFound[ iB ] ) continue;
2358 double dist = ( wGc - gcVec[ iB ] ).SquareModulus();
2359 if ( dist < minDist ) {
2364 bndFound[ bIndex ] = true;
2365 bndIndWirePosMap.insert( TIntWirePosMap::value_type( bIndex, wlIt ));
2370 TIntWirePosMap::iterator bIndWPosIt = bndIndWirePosMap.begin();
2371 eID = theFirstEdgeID;
2372 for ( ; bIndWPosIt != bndIndWirePosMap.end(); bIndWPosIt++ )
2374 TListOfEdgesList::iterator wirePos = (*bIndWPosIt).second;
2375 list < TopoDS_Edge > & wire = ( *wirePos );
2377 // choose the best first edge of a wire
2378 setFirstEdge( wire, eID );
2380 // compute eventual UV and fill theEdgesPointsList
2381 theEdgesPointsList.push_back( list< TPoint* >() );
2382 list< TPoint* > & edgesPoints = theEdgesPointsList.back();
2383 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2385 list< TPoint* > & ePoints = getShapePoints( eID++ );
2386 computeUVOnEdge( *eIt, ePoints );
2387 edgesPoints.insert( edgesPoints.end(), ePoints.begin(), (--ePoints.end()));
2389 // put wire back to theWireList
2391 theWireList.splice( theToWire, tmpWList, wlIt, wirePos );
2397 //=======================================================================
2399 //purpose : Compute nodes coordinates applying
2400 // the loaded pattern to <theFace>. The first key-point
2401 // will be mapped into <theVertexOnKeyPoint1>
2402 //=======================================================================
2404 bool SMESH_Pattern::Apply (const TopoDS_Face& theFace,
2405 const TopoDS_Vertex& theVertexOnKeyPoint1,
2406 const bool theReverse)
2408 MESSAGE(" ::Apply(face) " );
2409 TopoDS_Face face = theReverse ? TopoDS::Face( theFace.Reversed() ) : theFace;
2410 if ( !setShapeToMesh( face ))
2413 // find points on edges, it fills myNbKeyPntInBoundary
2414 if ( !findBoundaryPoints() )
2417 // Define the edges order so that the first edge starts at
2418 // theVertexOnKeyPoint1
2420 list< TopoDS_Edge > eList;
2421 list< int > nbVertexInWires;
2422 int nbWires = SMESH_Block::GetOrderedEdges( face, eList, nbVertexInWires, theVertexOnKeyPoint1);
2423 if ( !theVertexOnKeyPoint1.IsSame( TopExp::FirstVertex( eList.front(), true )))
2425 MESSAGE( " theVertexOnKeyPoint1 not found in the outer wire ");
2426 return setErrorCode( ERR_APPLF_BAD_VERTEX );
2428 // check nb wires and edges
2429 list< int > l1 = myNbKeyPntInBoundary, l2 = nbVertexInWires;
2430 l1.sort(); l2.sort();
2433 MESSAGE( "Wrong nb vertices in wires" );
2434 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2437 // here shapes get IDs, for the outer wire IDs are OK
2438 int nbVertices = loadVE( eList, myShapeIDMap );
2439 myShapeIDMap.Add( face );
2441 if ( myShapeIDToPointsMap.size() != myShapeIDMap.Extent() ) {
2442 MESSAGE( myShapeIDToPointsMap.size() <<" != " << myShapeIDMap.Extent());
2443 return setErrorCode( ERR_APPLF_INTERNAL_EEROR );
2446 // points on edges to be used for UV computation of in-face points
2447 list< list< TPoint* > > edgesPointsList;
2448 edgesPointsList.push_back( list< TPoint* >() );
2449 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2450 list< TPoint* >::iterator pIt, pEnd;
2452 // compute UV of points on the outer wire
2453 int iE, nbEdgesInOuterWire = nbVertexInWires.front();
2454 list< TopoDS_Edge >::iterator elIt;
2455 for (iE = 0, elIt = eList.begin();
2456 iE < nbEdgesInOuterWire && elIt != eList.end();
2459 list< TPoint* > & ePoints = getShapePoints( *elIt );
2461 computeUVOnEdge( *elIt, ePoints );
2462 // collect on-edge points (excluding the last one)
2463 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2466 // If there are several wires, define the order of edges of inner wires:
2467 // compute UV of inner edge-points using 2 methods: the one for in-face points
2468 // and the one for on-edge points and then choose the best edge order
2469 // by the best correspondance of the 2 results
2472 // compute UV of inner edge-points using the method for in-face points
2473 // and devide eList into a list of separate wires
2475 list< list< TopoDS_Edge > > wireList;
2476 list<TopoDS_Edge>::iterator eIt = elIt;
2477 list<int>::iterator nbEIt = nbVertexInWires.begin();
2478 for ( nbEIt++; nbEIt != nbVertexInWires.end(); nbEIt++ )
2480 int nbEdges = *nbEIt;
2481 wireList.push_back( list< TopoDS_Edge >() );
2482 list< TopoDS_Edge > & wire = wireList.back();
2483 for ( iE = 0 ; iE < nbEdges; eIt++, iE++ )
2485 list< TPoint* > & ePoints = getShapePoints( *eIt );
2486 pIt = ePoints.begin();
2487 for ( pIt++; pIt != ePoints.end(); pIt++ ) {
2489 if ( !compUVByIsoIntersection( edgesPointsList, p->myInitUV, p->myUV, aBool )) {
2490 MESSAGE("cant Apply(face)");
2493 // keep the computed UV to compare against by setFirstEdge()
2494 p->myXYZ.SetCoord( p->myUV.X(), p->myUV.Y(), 0. );
2496 wire.push_back( *eIt );
2499 // remove inner edges from eList
2500 eList.erase( elIt, eList.end() );
2502 // sort wireList by nb edges in a wire
2503 sortBySize< TopoDS_Edge > ( wireList );
2505 // an ID of the first edge of a boundary
2506 int id1 = nbVertices + nbEdgesInOuterWire + 1;
2507 // if ( nbSeamShapes > 0 )
2508 // id1 += 2; // 2 vertices more
2510 // find points - edge correspondence for wires of unique size,
2511 // edge order within a wire should be defined only
2513 list< list< TopoDS_Edge > >::iterator wlIt = wireList.begin();
2514 while ( wlIt != wireList.end() )
2516 list< TopoDS_Edge >& wire = (*wlIt);
2517 int nbEdges = wire.size();
2519 if ( wlIt == wireList.end() || (*wlIt).size() != nbEdges ) // a unique size wire
2521 // choose the best first edge of a wire
2522 setFirstEdge( wire, id1 );
2524 // compute eventual UV and collect on-edge points
2525 edgesPointsList.push_back( list< TPoint* >() );
2526 edgesPoints = & edgesPointsList.back();
2528 for ( eIt = wire.begin(); eIt != wire.end(); eIt++ )
2530 list< TPoint* > & ePoints = getShapePoints( eID++ );
2531 computeUVOnEdge( *eIt, ePoints );
2532 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), (--ePoints.end()));
2538 // find boundary - wire correspondence for several wires of same size
2540 id1 = nbVertices + nbEdgesInOuterWire + 1;
2541 wlIt = wireList.begin();
2542 while ( wlIt != wireList.end() )
2544 int nbSameSize = 0, nbEdges = (*wlIt).size();
2545 list< list< TopoDS_Edge > >::iterator wlIt2 = wlIt;
2547 while ( wlIt2 != wireList.end() && (*wlIt2).size() == nbEdges ) { // a same size wire
2551 if ( nbSameSize > 0 )
2552 if (!sortSameSizeWires(wireList, wlIt, wlIt2, id1, edgesPointsList))
2555 id1 += nbEdges * ( nbSameSize + 1 );
2558 // add well-ordered edges to eList
2560 for ( wlIt = wireList.begin(); wlIt != wireList.end(); wlIt++ )
2562 list< TopoDS_Edge >& wire = (*wlIt);
2563 eList.splice( eList.end(), wire, wire.begin(), wire.end() );
2566 // re-fill myShapeIDMap - all shapes get good IDs
2568 myShapeIDMap.Clear();
2569 nbVertices = loadVE( eList, myShapeIDMap );
2570 myShapeIDMap.Add( face );
2572 } // there are inner wires
2574 // Set XYZ of on-vertex points
2576 // for ( int iV = 1; iV <= nbVertices; ++iV )
2578 // const TopoDS_Vertex& V = TopoDS::Vertex( myShapeIDMap( iV ));
2579 // list< TPoint* > & vPoints = getShapePoints( iV );
2580 // if ( !vPoints.empty() )
2582 // //vPoints.front()->myUV = BRep_Tool::Parameters( V, theFace ).XY();
2583 // vPoints.front()->myXYZ = BRep_Tool::Pnt( V );
2587 // Compute XYZ of on-edge points
2589 TopLoc_Location loc;
2590 for ( iE = nbVertices + 1, elIt = eList.begin(); elIt != eList.end(); elIt++ )
2592 BRepAdaptor_Curve C3d( *elIt );
2593 list< TPoint* > & ePoints = getShapePoints( iE++ );
2594 for ( pIt = ++ePoints.begin(), pEnd = ePoints.end(); pIt != pEnd; pIt++ )
2596 TPoint* point = *pIt;
2597 point->myXYZ = C3d.Value( point->myU );
2601 // Compute UV and XYZ of in-face points
2603 // try to use a simple algo
2604 list< TPoint* > & fPoints = getShapePoints( face );
2605 bool isDeformed = false;
2606 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2607 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2608 (*pIt)->myUV, isDeformed )) {
2609 MESSAGE("cant Apply(face)");
2612 // try to use a complex algo if it is a difficult case
2613 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2615 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2616 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2617 (*pIt)->myUV, isDeformed )) {
2618 MESSAGE("cant Apply(face)");
2623 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( face, loc );
2624 const gp_Trsf & aTrsf = loc.Transformation();
2625 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2627 TPoint * point = *pIt;
2628 point->myXYZ = aSurface->Value( point->myUV.X(), point->myUV.Y() );
2629 if ( !loc.IsIdentity() )
2630 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2633 myIsComputed = true;
2635 return setErrorCode( ERR_OK );
2638 //=======================================================================
2640 //purpose : Compute nodes coordinates applying
2641 // the loaded pattern to <theFace>. The first key-point
2642 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2643 //=======================================================================
2645 bool SMESH_Pattern::Apply (const SMDS_MeshFace* theFace,
2646 const int theNodeIndexOnKeyPoint1,
2647 const bool theReverse)
2649 // MESSAGE(" ::Apply(MeshFace) " );
2651 if ( !IsLoaded() ) {
2652 MESSAGE( "Pattern not loaded" );
2653 return setErrorCode( ERR_APPL_NOT_LOADED );
2656 // check nb of nodes
2657 const int nbFaceNodes = theFace->NbCornerNodes();
2658 if ( nbFaceNodes != myNbKeyPntInBoundary.front() ) {
2659 MESSAGE( myKeyPointIDs.size() << " != " << nbFaceNodes );
2660 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2663 // find points on edges, it fills myNbKeyPntInBoundary
2664 if ( !findBoundaryPoints() )
2667 // check that there are no holes in a pattern
2668 if (myNbKeyPntInBoundary.size() > 1 ) {
2669 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2672 // Define the nodes order
2674 list< const SMDS_MeshNode* > nodes;
2675 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2676 SMDS_NodeIteratorPtr noIt = theFace->nodeIterator();
2678 while ( noIt->more() && iSub < nbFaceNodes ) {
2679 const SMDS_MeshNode* node = noIt->next();
2680 nodes.push_back( node );
2681 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2684 if ( n != nodes.end() ) {
2686 if ( n != --nodes.end() )
2687 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2690 else if ( n != nodes.begin() )
2691 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2693 list< gp_XYZ > xyzList;
2694 myOrderedNodes.resize( nbFaceNodes );
2695 for ( iSub = 0, n = nodes.begin(); n != nodes.end(); ++n ) {
2696 xyzList.push_back( SMESH_TNodeXYZ( *n ));
2697 myOrderedNodes[ iSub++] = *n;
2700 // Define a face plane
2702 list< gp_XYZ >::iterator xyzIt = xyzList.begin();
2703 gp_Pnt P ( *xyzIt++ );
2704 gp_Vec Vx( P, *xyzIt++ ), N;
2706 N = Vx ^ gp_Vec( P, *xyzIt++ );
2707 } while ( N.SquareMagnitude() <= DBL_MIN && xyzIt != xyzList.end() );
2708 if ( N.SquareMagnitude() <= DBL_MIN )
2709 return setErrorCode( ERR_APPLF_BAD_FACE_GEOM );
2710 gp_Ax2 pos( P, N, Vx );
2712 // Compute UV of key-points on a plane
2713 for ( xyzIt = xyzList.begin(), iSub = 1; xyzIt != xyzList.end(); xyzIt++, iSub++ )
2715 gp_Vec vec ( pos.Location(), *xyzIt );
2716 TPoint* p = getShapePoints( iSub ).front();
2717 p->myUV.SetX( vec * pos.XDirection() );
2718 p->myUV.SetY( vec * pos.YDirection() );
2722 // points on edges to be used for UV computation of in-face points
2723 list< list< TPoint* > > edgesPointsList;
2724 edgesPointsList.push_back( list< TPoint* >() );
2725 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2726 list< TPoint* >::iterator pIt;
2728 // compute UV and XYZ of points on edges
2730 for ( xyzIt = xyzList.begin(); xyzIt != xyzList.end(); iSub++ )
2732 gp_XYZ& xyz1 = *xyzIt++;
2733 gp_XYZ& xyz2 = ( xyzIt != xyzList.end() ) ? *xyzIt : xyzList.front();
2735 list< TPoint* > & ePoints = getShapePoints( iSub );
2736 ePoints.back()->myInitU = 1.0;
2737 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2738 while ( *pIt != ePoints.back() )
2741 p->myXYZ = xyz1 * ( 1 - p->myInitU ) + xyz2 * p->myInitU;
2742 gp_Vec vec ( pos.Location(), p->myXYZ );
2743 p->myUV.SetX( vec * pos.XDirection() );
2744 p->myUV.SetY( vec * pos.YDirection() );
2746 // collect on-edge points (excluding the last one)
2747 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2750 // Compute UV and XYZ of in-face points
2752 // try to use a simple algo to compute UV
2753 list< TPoint* > & fPoints = getShapePoints( iSub );
2754 bool isDeformed = false;
2755 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2756 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2757 (*pIt)->myUV, isDeformed )) {
2758 MESSAGE("cant Apply(face)");
2761 // try to use a complex algo if it is a difficult case
2762 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2764 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2765 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2766 (*pIt)->myUV, isDeformed )) {
2767 MESSAGE("cant Apply(face)");
2772 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2774 (*pIt)->myXYZ = ElSLib::PlaneValue( (*pIt)->myUV.X(), (*pIt)->myUV.Y(), pos );
2777 myIsComputed = true;
2779 return setErrorCode( ERR_OK );
2782 //=======================================================================
2784 //purpose : Compute nodes coordinates applying
2785 // the loaded pattern to <theFace>. The first key-point
2786 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2787 //=======================================================================
2789 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2790 const SMDS_MeshFace* theFace,
2791 const TopoDS_Shape& theSurface,
2792 const int theNodeIndexOnKeyPoint1,
2793 const bool theReverse)
2795 // MESSAGE(" ::Apply(MeshFace) " );
2796 if ( theSurface.IsNull() || theSurface.ShapeType() != TopAbs_FACE ) {
2797 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2799 const TopoDS_Face& face = TopoDS::Face( theSurface );
2800 TopLoc_Location loc;
2801 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
2802 const gp_Trsf & aTrsf = loc.Transformation();
2804 if ( !IsLoaded() ) {
2805 MESSAGE( "Pattern not loaded" );
2806 return setErrorCode( ERR_APPL_NOT_LOADED );
2809 // check nb of nodes
2810 if (theFace->NbNodes() != myNbKeyPntInBoundary.front() ) {
2811 MESSAGE( myKeyPointIDs.size() << " != " << theFace->NbNodes() );
2812 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2815 // find points on edges, it fills myNbKeyPntInBoundary
2816 if ( !findBoundaryPoints() )
2819 // check that there are no holes in a pattern
2820 if (myNbKeyPntInBoundary.size() > 1 ) {
2821 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2824 // Define the nodes order
2826 list< const SMDS_MeshNode* > nodes;
2827 list< const SMDS_MeshNode* >::iterator n = nodes.end();
2828 SMDS_ElemIteratorPtr noIt = theFace->nodesIterator();
2830 while ( noIt->more() ) {
2831 const SMDS_MeshNode* node = smdsNode( noIt->next() );
2832 nodes.push_back( node );
2833 if ( iSub++ == theNodeIndexOnKeyPoint1 )
2836 if ( n != nodes.end() ) {
2838 if ( n != --nodes.end() )
2839 nodes.splice( nodes.begin(), nodes, ++n, nodes.end() );
2842 else if ( n != nodes.begin() )
2843 nodes.splice( nodes.end(), nodes, nodes.begin(), n );
2846 // find a node not on a seam edge, if necessary
2847 SMESH_MesherHelper helper( *theMesh );
2848 helper.SetSubShape( theSurface );
2849 const SMDS_MeshNode* inFaceNode = 0;
2850 if ( helper.GetNodeUVneedInFaceNode() )
2852 SMESH_MeshEditor editor( theMesh );
2853 for ( n = nodes.begin(); ( !inFaceNode && n != nodes.end()); ++n ) {
2854 int shapeID = editor.FindShape( *n );
2856 return Apply( theFace, theNodeIndexOnKeyPoint1, theReverse);
2857 if ( !helper.IsSeamShape( shapeID ))
2862 // Set UV of key-points (i.e. of nodes of theFace )
2863 vector< gp_XY > keyUV( theFace->NbNodes() );
2864 myOrderedNodes.resize( theFace->NbNodes() );
2865 for ( iSub = 1, n = nodes.begin(); n != nodes.end(); ++n, ++iSub )
2867 TPoint* p = getShapePoints( iSub ).front();
2868 p->myUV = helper.GetNodeUV( face, *n, inFaceNode );
2869 p->myXYZ = gp_XYZ( (*n)->X(), (*n)->Y(), (*n)->Z() );
2871 keyUV[ iSub-1 ] = p->myUV;
2872 myOrderedNodes[ iSub-1 ] = *n;
2875 // points on edges to be used for UV computation of in-face points
2876 list< list< TPoint* > > edgesPointsList;
2877 edgesPointsList.push_back( list< TPoint* >() );
2878 list< TPoint* > * edgesPoints = & edgesPointsList.back();
2879 list< TPoint* >::iterator pIt;
2881 // compute UV and XYZ of points on edges
2883 for ( int i = 0; i < myOrderedNodes.size(); ++i, ++iSub )
2885 gp_XY& uv1 = keyUV[ i ];
2886 gp_XY& uv2 = ( i+1 < keyUV.size() ) ? keyUV[ i+1 ] : keyUV[ 0 ];
2888 list< TPoint* > & ePoints = getShapePoints( iSub );
2889 ePoints.back()->myInitU = 1.0;
2890 list< TPoint* >::const_iterator pIt = ++ePoints.begin();
2891 while ( *pIt != ePoints.back() )
2894 p->myUV = uv1 * ( 1 - p->myInitU ) + uv2 * p->myInitU;
2895 p->myXYZ = surface->Value( p->myUV.X(), p->myUV.Y() );
2896 if ( !loc.IsIdentity() )
2897 aTrsf.Transforms( p->myXYZ.ChangeCoord() );
2899 // collect on-edge points (excluding the last one)
2900 edgesPoints->insert( edgesPoints->end(), ePoints.begin(), --ePoints.end());
2903 // Compute UV and XYZ of in-face points
2905 // try to use a simple algo to compute UV
2906 list< TPoint* > & fPoints = getShapePoints( iSub );
2907 bool isDeformed = false;
2908 for ( pIt = fPoints.begin(); !isDeformed && pIt != fPoints.end(); pIt++ )
2909 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2910 (*pIt)->myUV, isDeformed )) {
2911 MESSAGE("cant Apply(face)");
2914 // try to use a complex algo if it is a difficult case
2915 if ( isDeformed && !compUVByElasticIsolines( edgesPointsList, fPoints ))
2917 for ( ; pIt != fPoints.end(); pIt++ ) // continue with the simple algo
2918 if ( !compUVByIsoIntersection( edgesPointsList, (*pIt)->myInitUV,
2919 (*pIt)->myUV, isDeformed )) {
2920 MESSAGE("cant Apply(face)");
2925 for ( pIt = fPoints.begin(); pIt != fPoints.end(); pIt++ )
2927 TPoint * point = *pIt;
2928 point->myXYZ = surface->Value( point->myUV.X(), point->myUV.Y() );
2929 if ( !loc.IsIdentity() )
2930 aTrsf.Transforms( point->myXYZ.ChangeCoord() );
2933 myIsComputed = true;
2935 return setErrorCode( ERR_OK );
2938 //=======================================================================
2939 //function : undefinedXYZ
2941 //=======================================================================
2943 static const gp_XYZ& undefinedXYZ()
2945 static gp_XYZ xyz( 1.e100, 0., 0. );
2949 //=======================================================================
2950 //function : isDefined
2952 //=======================================================================
2954 inline static bool isDefined(const gp_XYZ& theXYZ)
2956 return theXYZ.X() < 1.e100;
2959 //=======================================================================
2961 //purpose : Compute nodes coordinates applying
2962 // the loaded pattern to <theFaces>. The first key-point
2963 // will be mapped into <theNodeIndexOnKeyPoint1>-th node
2964 //=======================================================================
2966 bool SMESH_Pattern::Apply (SMESH_Mesh* theMesh,
2967 std::set<const SMDS_MeshFace*>& theFaces,
2968 const int theNodeIndexOnKeyPoint1,
2969 const bool theReverse)
2971 MESSAGE(" ::Apply(set<MeshFace>) " );
2973 if ( !IsLoaded() ) {
2974 MESSAGE( "Pattern not loaded" );
2975 return setErrorCode( ERR_APPL_NOT_LOADED );
2978 // find points on edges, it fills myNbKeyPntInBoundary
2979 if ( !findBoundaryPoints() )
2982 // check that there are no holes in a pattern
2983 if (myNbKeyPntInBoundary.size() > 1 ) {
2984 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
2989 myElemXYZIDs.clear();
2990 myXYZIdToNodeMap.clear();
2992 myIdsOnBoundary.clear();
2993 myReverseConnectivity.clear();
2995 myXYZ.resize( myPoints.size() * theFaces.size(), undefinedXYZ() );
2996 myElements.reserve( theFaces.size() );
2998 int ind1 = 0; // lowest point index for a face
3003 // SMESH_MeshEditor editor( theMesh );
3005 // apply to each face in theFaces set
3006 set<const SMDS_MeshFace*>::iterator face = theFaces.begin();
3007 for ( ; face != theFaces.end(); ++face )
3009 // int curShapeId = editor.FindShape( *face );
3010 // if ( curShapeId != shapeID ) {
3011 // if ( curShapeId )
3012 // shape = theMesh->GetMeshDS()->IndexToShape( curShapeId );
3015 // shapeID = curShapeId;
3018 if ( shape.IsNull() )
3019 ok = Apply( *face, theNodeIndexOnKeyPoint1, theReverse );
3021 ok = Apply( theMesh, *face, shape, theNodeIndexOnKeyPoint1, theReverse );
3023 MESSAGE( "Failed on " << *face );
3026 myElements.push_back( *face );
3028 // store computed points belonging to elements
3029 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3030 for ( ; ll != myElemPointIDs.end(); ++ll )
3032 myElemXYZIDs.push_back(TElemDef());
3033 TElemDef& xyzIds = myElemXYZIDs.back();
3034 TElemDef& pIds = *ll;
3035 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3036 int pIndex = *id + ind1;
3037 xyzIds.push_back( pIndex );
3038 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3039 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3042 // put points on links to myIdsOnBoundary,
3043 // they will be used to sew new elements on adjacent refined elements
3044 int nbNodes = (*face)->NbCornerNodes(), eID = nbNodes + 1;
3045 for ( int i = 0; i < nbNodes; i++ )
3047 list< TPoint* > & linkPoints = getShapePoints( eID++ );
3048 const SMDS_MeshNode* n1 = myOrderedNodes[ i ];
3049 const SMDS_MeshNode* n2 = myOrderedNodes[( i+1 ) % nbNodes ];
3050 // make a link and a node set
3051 TNodeSet linkSet, node1Set;
3052 linkSet.insert( n1 );
3053 linkSet.insert( n2 );
3054 node1Set.insert( n1 );
3055 list< TPoint* >::iterator p = linkPoints.begin();
3057 // map the first link point to n1
3058 int nId = ( *p - &myPoints[0] ) + ind1;
3059 myXYZIdToNodeMap[ nId ] = n1;
3060 list< list< int > >& groups = myIdsOnBoundary[ node1Set ];
3061 groups.push_back(list< int > ());
3062 groups.back().push_back( nId );
3064 // add the linkSet to the map
3065 list< list< int > >& groups = myIdsOnBoundary[ linkSet ];
3066 groups.push_back(list< int > ());
3067 list< int >& indList = groups.back();
3068 // add points to the map excluding the end points
3069 for ( p++; *p != linkPoints.back(); p++ )
3070 indList.push_back( ( *p - &myPoints[0] ) + ind1 );
3072 ind1 += myPoints.size();
3075 return !myElemXYZIDs.empty();
3078 //=======================================================================
3080 //purpose : Compute nodes coordinates applying
3081 // the loaded pattern to <theVolumes>. The (0,0,0) key-point
3082 // will be mapped into <theNode000Index>-th node. The
3083 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3085 //=======================================================================
3087 bool SMESH_Pattern::Apply (std::set<const SMDS_MeshVolume*> & theVolumes,
3088 const int theNode000Index,
3089 const int theNode001Index)
3091 MESSAGE(" ::Apply(set<MeshVolumes>) " );
3093 if ( !IsLoaded() ) {
3094 MESSAGE( "Pattern not loaded" );
3095 return setErrorCode( ERR_APPL_NOT_LOADED );
3098 // bind ID to points
3099 if ( !findBoundaryPoints() )
3102 // check that there are no holes in a pattern
3103 if (myNbKeyPntInBoundary.size() > 1 ) {
3104 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
3109 myElemXYZIDs.clear();
3110 myXYZIdToNodeMap.clear();
3112 myIdsOnBoundary.clear();
3113 myReverseConnectivity.clear();
3115 myXYZ.resize( myPoints.size() * theVolumes.size(), undefinedXYZ() );
3116 myElements.reserve( theVolumes.size() );
3118 // to find point index
3119 map< TPoint*, int > pointIndex;
3120 for ( int i = 0; i < myPoints.size(); i++ )
3121 pointIndex.insert( make_pair( & myPoints[ i ], i ));
3123 int ind1 = 0; // lowest point index for an element
3125 // apply to each element in theVolumes set
3126 set<const SMDS_MeshVolume*>::iterator vol = theVolumes.begin();
3127 for ( ; vol != theVolumes.end(); ++vol )
3129 if ( !Apply( *vol, theNode000Index, theNode001Index )) {
3130 MESSAGE( "Failed on " << *vol );
3133 myElements.push_back( *vol );
3135 // store computed points belonging to elements
3136 list< TElemDef >::iterator ll = myElemPointIDs.begin();
3137 for ( ; ll != myElemPointIDs.end(); ++ll )
3139 myElemXYZIDs.push_back(TElemDef());
3140 TElemDef& xyzIds = myElemXYZIDs.back();
3141 TElemDef& pIds = *ll;
3142 for ( TElemDef::iterator id = pIds.begin(); id != pIds.end(); id++ ) {
3143 int pIndex = *id + ind1;
3144 xyzIds.push_back( pIndex );
3145 myXYZ[ pIndex ] = myPoints[ *id ].myXYZ.XYZ();
3146 myReverseConnectivity[ pIndex ].push_back( & xyzIds );
3149 // put points on edges and faces to myIdsOnBoundary,
3150 // they will be used to sew new elements on adjacent refined elements
3151 for ( int Id = SMESH_Block::ID_V000; Id <= SMESH_Block::ID_F1yz; Id++ )
3153 // make a set of sub-points
3155 vector< int > subIDs;
3156 if ( SMESH_Block::IsVertexID( Id )) {
3157 subNodes.insert( myOrderedNodes[ Id - 1 ]);
3159 else if ( SMESH_Block::IsEdgeID( Id )) {
3160 SMESH_Block::GetEdgeVertexIDs( Id, subIDs );
3161 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3162 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3165 SMESH_Block::GetFaceEdgesIDs( Id, subIDs );
3166 int e1 = subIDs[ 0 ], e2 = subIDs[ 1 ];
3167 SMESH_Block::GetEdgeVertexIDs( e1, subIDs );
3168 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3169 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3170 SMESH_Block::GetEdgeVertexIDs( e2, subIDs );
3171 subNodes.insert( myOrderedNodes[ subIDs.front() - 1 ]);
3172 subNodes.insert( myOrderedNodes[ subIDs.back() - 1 ]);
3175 list< TPoint* > & points = getShapePoints( Id );
3176 list< TPoint* >::iterator p = points.begin();
3177 list< list< int > >& groups = myIdsOnBoundary[ subNodes ];
3178 groups.push_back(list< int > ());
3179 list< int >& indList = groups.back();
3180 for ( ; p != points.end(); p++ )
3181 indList.push_back( pointIndex[ *p ] + ind1 );
3182 if ( subNodes.size() == 1 ) // vertex case
3183 myXYZIdToNodeMap[ indList.back() ] = myOrderedNodes[ Id - 1 ];
3185 ind1 += myPoints.size();
3188 return !myElemXYZIDs.empty();
3191 //=======================================================================
3193 //purpose : Create a pattern from the mesh built on <theBlock>
3194 //=======================================================================
3196 bool SMESH_Pattern::Load (SMESH_Mesh* theMesh,
3197 const TopoDS_Shell& theBlock)
3199 MESSAGE(" ::Load(volume) " );
3202 SMESHDS_SubMesh * aSubMesh;
3204 const bool isQuadMesh = theMesh->NbVolumes( ORDER_QUADRATIC );
3206 // load shapes in myShapeIDMap
3208 TopoDS_Vertex v1, v2;
3209 if ( !block.LoadBlockShapes( theBlock, v1, v2, myShapeIDMap ))
3210 return setErrorCode( ERR_LOADV_BAD_SHAPE );
3213 int nbNodes = 0, shapeID;
3214 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3216 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3217 aSubMesh = getSubmeshWithElements( theMesh, S );
3219 nbNodes += aSubMesh->NbNodes();
3221 myPoints.resize( nbNodes );
3223 // load U of points on edges
3224 TNodePointIDMap nodePointIDMap;
3226 for ( shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3228 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3229 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3230 aSubMesh = getSubmeshWithElements( theMesh, S );
3231 if ( ! aSubMesh ) continue;
3232 SMDS_NodeIteratorPtr nIt = aSubMesh->GetNodes();
3233 if ( !nIt->more() ) continue;
3235 // store a node and a point
3236 while ( nIt->more() ) {
3237 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3238 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Volume ))
3240 nodePointIDMap.insert( make_pair( node, iPoint ));
3241 if ( block.IsVertexID( shapeID ))
3242 myKeyPointIDs.push_back( iPoint );
3243 TPoint* p = & myPoints[ iPoint++ ];
3244 shapePoints.push_back( p );
3245 p->myXYZ.SetCoord( node->X(), node->Y(), node->Z() );
3246 p->myInitXYZ.SetCoord( 0,0,0 );
3248 list< TPoint* >::iterator pIt = shapePoints.begin();
3251 switch ( S.ShapeType() )
3256 for ( ; pIt != shapePoints.end(); pIt++ ) {
3257 double * coef = block.GetShapeCoef( shapeID );
3258 for ( int iCoord = 1; iCoord <= 3; iCoord++ )
3259 if ( coef[ iCoord - 1] > 0 )
3260 (*pIt)->myInitXYZ.SetCoord( iCoord, 1. );
3262 if ( S.ShapeType() == TopAbs_VERTEX )
3265 const TopoDS_Edge& edge = TopoDS::Edge( S );
3267 BRep_Tool::Range( edge, f, l );
3268 int iCoord = SMESH_Block::GetCoordIndOnEdge( shapeID );
3269 bool isForward = SMESH_Block::IsForwardEdge( edge, myShapeIDMap );
3270 pIt = shapePoints.begin();
3271 nIt = aSubMesh->GetNodes();
3272 for ( ; nIt->more(); pIt++ )
3274 const SMDS_MeshNode* node = nIt->next();
3275 if ( isQuadMesh && SMESH_MeshEditor::IsMedium( node, SMDSAbs_Edge ))
3277 const SMDS_EdgePosition* epos =
3278 static_cast<const SMDS_EdgePosition*>(node->GetPosition());
3279 double u = ( epos->GetUParameter() - f ) / ( l - f );
3280 (*pIt)->myInitXYZ.SetCoord( iCoord, isForward ? u : 1 - u );
3285 for ( ; pIt != shapePoints.end(); pIt++ )
3287 if ( !block.ComputeParameters( (*pIt)->myXYZ, (*pIt)->myInitXYZ, shapeID )) {
3288 MESSAGE( "!block.ComputeParameters()" );
3289 return setErrorCode( ERR_LOADV_COMPUTE_PARAMS );
3293 } // loop on block sub-shapes
3297 aSubMesh = getSubmeshWithElements( theMesh, theBlock );
3300 SMDS_ElemIteratorPtr elemIt = aSubMesh->GetElements();
3301 while ( elemIt->more() ) {
3302 const SMDS_MeshElement* elem = elemIt->next();
3303 myElemPointIDs.push_back( TElemDef() );
3304 TElemDef& elemPoints = myElemPointIDs.back();
3305 int nbNodes = elem->NbCornerNodes();
3306 for ( int i = 0;i < nbNodes; ++i )
3307 elemPoints.push_back( nodePointIDMap[ elem->GetNode( i )]);
3311 myIsBoundaryPointsFound = true;
3313 return setErrorCode( ERR_OK );
3316 //=======================================================================
3317 //function : getSubmeshWithElements
3318 //purpose : return submesh containing elements bound to theBlock in theMesh
3319 //=======================================================================
3321 SMESHDS_SubMesh * SMESH_Pattern::getSubmeshWithElements(SMESH_Mesh* theMesh,
3322 const TopoDS_Shape& theShape)
3324 SMESHDS_SubMesh * aSubMesh = theMesh->GetMeshDS()->MeshElements( theShape );
3325 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3328 if ( theShape.ShapeType() == TopAbs_SHELL )
3330 // look for submesh of VOLUME
3331 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( theShape ));
3332 for (; it.More(); it.Next()) {
3333 aSubMesh = theMesh->GetMeshDS()->MeshElements( it.Value() );
3334 if ( aSubMesh && ( aSubMesh->GetElements()->more() || aSubMesh->GetNodes()->more() ))
3342 //=======================================================================
3344 //purpose : Compute nodes coordinates applying
3345 // the loaded pattern to <theBlock>. The (0,0,0) key-point
3346 // will be mapped into <theVertex000>. The (0,0,1)
3347 // fifth key-point will be mapped into <theVertex001>.
3348 //=======================================================================
3350 bool SMESH_Pattern::Apply (const TopoDS_Shell& theBlock,
3351 const TopoDS_Vertex& theVertex000,
3352 const TopoDS_Vertex& theVertex001)
3354 MESSAGE(" ::Apply(volume) " );
3356 if (!findBoundaryPoints() || // bind ID to points
3357 !setShapeToMesh( theBlock )) // check theBlock is a suitable shape
3360 SMESH_Block block; // bind ID to shape
3361 if (!block.LoadBlockShapes( theBlock, theVertex000, theVertex001, myShapeIDMap ))
3362 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3364 // compute XYZ of points on shapes
3366 for ( int shapeID = 1; shapeID <= myShapeIDMap.Extent(); shapeID++ )
3368 list< TPoint* > & shapePoints = getShapePoints( shapeID );
3369 list< TPoint* >::iterator pIt = shapePoints.begin();
3370 const TopoDS_Shape& S = myShapeIDMap( shapeID );
3371 switch ( S.ShapeType() )
3373 case TopAbs_VERTEX: {
3375 for ( ; pIt != shapePoints.end(); pIt++ )
3376 block.VertexPoint( shapeID, (*pIt)->myXYZ.ChangeCoord() );
3381 for ( ; pIt != shapePoints.end(); pIt++ )
3382 block.EdgePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3387 for ( ; pIt != shapePoints.end(); pIt++ )
3388 block.FacePoint( shapeID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3392 for ( ; pIt != shapePoints.end(); pIt++ )
3393 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3395 } // loop on block sub-shapes
3397 myIsComputed = true;
3399 return setErrorCode( ERR_OK );
3402 //=======================================================================
3404 //purpose : Compute nodes coordinates applying
3405 // the loaded pattern to <theVolume>. The (0,0,0) key-point
3406 // will be mapped into <theNode000Index>-th node. The
3407 // (0,0,1) key-point will be mapped into <theNode000Index>-th
3409 //=======================================================================
3411 bool SMESH_Pattern::Apply (const SMDS_MeshVolume* theVolume,
3412 const int theNode000Index,
3413 const int theNode001Index)
3415 //MESSAGE(" ::Apply(MeshVolume) " );
3417 if (!findBoundaryPoints()) // bind ID to points
3420 SMESH_Block block; // bind ID to shape
3421 if (!block.LoadMeshBlock( theVolume, theNode000Index, theNode001Index, myOrderedNodes ))
3422 return setErrorCode( ERR_APPLV_BAD_SHAPE );
3423 // compute XYZ of points on shapes
3425 for ( int ID = SMESH_Block::ID_V000; ID <= SMESH_Block::ID_Shell; ID++ )
3427 list< TPoint* > & shapePoints = getShapePoints( ID );
3428 list< TPoint* >::iterator pIt = shapePoints.begin();
3430 if ( block.IsVertexID( ID ))
3431 for ( ; pIt != shapePoints.end(); pIt++ ) {
3432 block.VertexPoint( ID, (*pIt)->myXYZ.ChangeCoord() );
3434 else if ( block.IsEdgeID( ID ))
3435 for ( ; pIt != shapePoints.end(); pIt++ ) {
3436 block.EdgePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3438 else if ( block.IsFaceID( ID ))
3439 for ( ; pIt != shapePoints.end(); pIt++ ) {
3440 block.FacePoint( ID, (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3443 for ( ; pIt != shapePoints.end(); pIt++ )
3444 block.ShellPoint( (*pIt)->myInitXYZ, (*pIt)->myXYZ.ChangeCoord() );
3445 } // loop on block sub-shapes
3447 myIsComputed = true;
3449 return setErrorCode( ERR_OK );
3452 //=======================================================================
3453 //function : mergePoints
3454 //purpose : Merge XYZ on edges and/or faces.
3455 //=======================================================================
3457 void SMESH_Pattern::mergePoints (const bool uniteGroups)
3459 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
3460 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
3462 list<list< int > >& groups = idListIt->second;
3463 if ( groups.size() < 2 )
3467 const TNodeSet& nodes = idListIt->first;
3468 double tol2 = 1.e-10;
3469 if ( nodes.size() > 1 ) {
3471 TNodeSet::const_iterator n = nodes.begin();
3472 for ( ; n != nodes.end(); ++n )
3473 box.Add( gp_Pnt( SMESH_TNodeXYZ( *n )));
3474 double x, y, z, X, Y, Z;
3475 box.Get( x, y, z, X, Y, Z );
3476 gp_Pnt p( x, y, z ), P( X, Y, Z );
3477 tol2 = 1.e-4 * p.SquareDistance( P );
3480 // to unite groups on link
3481 bool unite = ( uniteGroups && nodes.size() == 2 );
3482 map< double, int > distIndMap;
3483 const SMDS_MeshNode* node = *nodes.begin();
3484 gp_Pnt P = SMESH_TNodeXYZ( node );
3486 // compare points, replace indices
3488 list< int >::iterator ind1, ind2;
3489 list< list< int > >::iterator grpIt1, grpIt2;
3490 for ( grpIt1 = groups.begin(); grpIt1 != groups.end(); grpIt1++ )
3492 list< int >& indices1 = *grpIt1;
3494 for ( grpIt2++; grpIt2 != groups.end(); grpIt2++ )
3496 list< int >& indices2 = *grpIt2;
3497 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3499 gp_XYZ& p1 = myXYZ[ *ind1 ];
3500 ind2 = indices2.begin();
3501 while ( ind2 != indices2.end() )
3503 gp_XYZ& p2 = myXYZ[ *ind2 ];
3504 //MESSAGE("COMP: " << *ind1 << " " << *ind2 << " X: " << p2.X() << " tol2: " << tol2);
3505 if ( ( p1 - p2 ).SquareModulus() <= tol2 )
3507 ASSERT( myReverseConnectivity.find( *ind2 ) != myReverseConnectivity.end() );
3508 list< TElemDef* > & elemXYZIDsList = myReverseConnectivity[ *ind2 ];
3509 list< TElemDef* >::iterator elemXYZIDs = elemXYZIDsList.begin();
3510 for ( ; elemXYZIDs != elemXYZIDsList.end(); elemXYZIDs++ )
3512 //MESSAGE( " Replace " << *ind2 << " with " << *ind1 );
3513 myXYZ[ *ind2 ] = undefinedXYZ();
3514 replace( (*elemXYZIDs)->begin(), (*elemXYZIDs)->end(), *ind2, *ind1 );
3516 ind2 = indices2.erase( ind2 );
3523 if ( unite ) { // sort indices using distIndMap
3524 for ( ind1 = indices1.begin(); ind1 != indices1.end(); ind1++ )
3526 ASSERT( isDefined( myXYZ[ *ind1 ] ));
3527 double dist = P.SquareDistance( myXYZ[ *ind1 ]);
3528 distIndMap.insert( make_pair( dist, *ind1 ));
3532 if ( unite ) { // put all sorted indices into the first group
3533 list< int >& g = groups.front();
3535 map< double, int >::iterator dist_ind = distIndMap.begin();
3536 for ( ; dist_ind != distIndMap.end(); dist_ind++ )
3537 g.push_back( dist_ind->second );
3539 } // loop on myIdsOnBoundary
3542 //=======================================================================
3543 //function : makePolyElements
3544 //purpose : prepare intermediate data to create Polygons and Polyhedrons
3545 //=======================================================================
3547 void SMESH_Pattern::
3548 makePolyElements(const vector< const SMDS_MeshNode* >& theNodes,
3549 const bool toCreatePolygons,
3550 const bool toCreatePolyedrs)
3552 myPolyElemXYZIDs.clear();
3553 myPolyElems.clear();
3554 myPolyElems.reserve( myIdsOnBoundary.size() );
3556 // make a set of refined elements
3557 TIDSortedElemSet avoidSet, elemSet;
3558 std::vector<const SMDS_MeshElement*>::iterator itv = myElements.begin();
3559 for(; itv!=myElements.end(); itv++) {
3560 const SMDS_MeshElement* el = (*itv);
3561 avoidSet.insert( el );
3563 //avoidSet.insert( myElements.begin(), myElements.end() );
3565 map< TNodeSet, list< list< int > > >::iterator indListIt, nn_IdList;
3567 if ( toCreatePolygons )
3569 int lastFreeId = myXYZ.size();
3571 // loop on links of refined elements
3572 indListIt = myIdsOnBoundary.begin();
3573 for ( ; indListIt != myIdsOnBoundary.end(); indListIt++ )
3575 const TNodeSet & linkNodes = indListIt->first;
3576 if ( linkNodes.size() != 2 )
3577 continue; // skip face
3578 const SMDS_MeshNode* n1 = * linkNodes.begin();
3579 const SMDS_MeshNode* n2 = * linkNodes.rbegin();
3581 list<list< int > >& idGroups = indListIt->second; // ids of nodes to build
3582 if ( idGroups.empty() || idGroups.front().empty() )
3585 // find not refined face having n1-n2 link
3589 const SMDS_MeshElement* face =
3590 SMESH_MeshAlgos::FindFaceInSet( n1, n2, elemSet, avoidSet );
3593 avoidSet.insert ( face );
3594 myPolyElems.push_back( face );
3596 // some links of <face> are split;
3597 // make list of xyz for <face>
3598 myPolyElemXYZIDs.push_back(TElemDef());
3599 TElemDef & faceNodeIds = myPolyElemXYZIDs.back();
3600 // loop on links of a <face>
3601 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3602 int i = 0, nbNodes = face->NbNodes();
3603 vector<const SMDS_MeshNode*> nodes( nbNodes + 1 );
3604 while ( nIt->more() )
3605 nodes[ i++ ] = smdsNode( nIt->next() );
3606 nodes[ i ] = nodes[ 0 ];
3607 for ( i = 0; i < nbNodes; ++i )
3609 // look for point mapped on a link
3610 TNodeSet faceLinkNodes;
3611 faceLinkNodes.insert( nodes[ i ] );
3612 faceLinkNodes.insert( nodes[ i + 1 ] );
3613 if ( faceLinkNodes == linkNodes )
3614 nn_IdList = indListIt;
3616 nn_IdList = myIdsOnBoundary.find( faceLinkNodes );
3617 // add face point ids
3618 faceNodeIds.push_back( ++lastFreeId );
3619 myXYZIdToNodeMap.insert( make_pair( lastFreeId, nodes[ i ]));
3620 if ( nn_IdList != myIdsOnBoundary.end() )
3622 // there are points mapped on a link
3623 list< int >& mappedIds = nn_IdList->second.front();
3624 if ( isReversed( nodes[ i ], mappedIds ))
3625 faceNodeIds.insert (faceNodeIds.end(),mappedIds.rbegin(), mappedIds.rend() );
3627 faceNodeIds.insert (faceNodeIds.end(),mappedIds.begin(), mappedIds.end() );
3629 } // loop on links of a <face>
3635 if ( myIs2D && idGroups.size() > 1 ) {
3637 // sew new elements on 2 refined elements sharing n1-n2 link
3639 list< int >& idsOnLink = idGroups.front();
3640 // temporarily add ids of link nodes to idsOnLink
3641 bool rev = isReversed( n1, idsOnLink );
3642 for ( int i = 0; i < 2; ++i )
3645 nodeSet.insert( i ? n2 : n1 );
3646 ASSERT( myIdsOnBoundary.find( nodeSet ) != myIdsOnBoundary.end() );
3647 list<list< int > >& groups = myIdsOnBoundary[ nodeSet ];
3648 int nodeId = groups.front().front();
3650 if ( rev ) append = !append;
3652 idsOnLink.push_back( nodeId );
3654 idsOnLink.push_front( nodeId );
3656 list< int >::iterator id = idsOnLink.begin();
3657 for ( ; id != idsOnLink.end(); ++id ) // loop on XYZ ids on a link
3659 list< TElemDef* >& elemDefs = myReverseConnectivity[ *id ]; // elems sharing id
3660 list< TElemDef* >::iterator pElemDef = elemDefs.begin();
3661 for ( ; pElemDef != elemDefs.end(); pElemDef++ ) // loop on elements sharing id
3663 TElemDef* pIdList = *pElemDef; // ptr on list of ids making element up
3664 // look for <id> in element definition
3665 TElemDef::iterator idDef = find( pIdList->begin(), pIdList->end(), *id );
3666 ASSERT ( idDef != pIdList->end() );
3667 // look for 2 neighbour ids of <id> in element definition
3668 for ( int prev = 0; prev < 2; ++prev ) {
3669 TElemDef::iterator idDef2 = idDef;
3671 idDef2 = ( idDef2 == pIdList->begin() ) ? --pIdList->end() : --idDef2;
3673 idDef2 = ( ++idDef2 == pIdList->end() ) ? pIdList->begin() : idDef2;
3674 // look for idDef2 on a link starting from id
3675 list< int >::iterator id2 = find( id, idsOnLink.end(), *idDef2 );
3676 if ( id2 != idsOnLink.end() && id != --id2 ) { // found not next to id
3677 // insert ids located on link between <id> and <id2>
3678 // into the element definition between idDef and idDef2
3680 for ( ; id2 != id; --id2 )
3681 pIdList->insert( idDef, *id2 );
3683 list< int >::iterator id1 = id;
3684 for ( ++id1, ++id2; id1 != id2; ++id1 )
3685 pIdList->insert( idDef2, *id1 );
3691 // remove ids of link nodes
3692 idsOnLink.pop_front();
3693 idsOnLink.pop_back();
3695 } // loop on myIdsOnBoundary
3696 } // if ( toCreatePolygons )
3698 if ( toCreatePolyedrs )
3700 // check volumes adjacent to the refined elements
3701 SMDS_VolumeTool volTool;
3702 vector<const SMDS_MeshElement*>::iterator refinedElem = myElements.begin();
3703 for ( ; refinedElem != myElements.end(); ++refinedElem )
3705 // loop on nodes of refinedElem
3706 SMDS_ElemIteratorPtr nIt = (*refinedElem)->nodesIterator();
3707 while ( nIt->more() ) {
3708 const SMDS_MeshNode* node = smdsNode( nIt->next() );
3709 // loop on inverse elements of node
3710 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator();
3711 while ( eIt->more() )
3713 const SMDS_MeshElement* elem = eIt->next();
3714 if ( !volTool.Set( elem ) || !avoidSet.insert( elem ).second )
3715 continue; // skip faces or refined elements
3716 // add polyhedron definition
3717 myPolyhedronQuantities.push_back(vector<int> ());
3718 myPolyElemXYZIDs.push_back(TElemDef());
3719 vector<int>& quantity = myPolyhedronQuantities.back();
3720 TElemDef & elemDef = myPolyElemXYZIDs.back();
3721 // get definitions of new elements on volume faces
3722 bool makePoly = false;
3723 for ( int iF = 0; iF < volTool.NbFaces(); ++iF )
3725 if ( getFacesDefinition(volTool.GetFaceNodes( iF ),
3726 volTool.NbFaceNodes( iF ),
3727 theNodes, elemDef, quantity))
3731 myPolyElems.push_back( elem );
3733 myPolyhedronQuantities.pop_back();
3734 myPolyElemXYZIDs.pop_back();
3742 //=======================================================================
3743 //function : getFacesDefinition
3744 //purpose : return faces definition for a volume face defined by theBndNodes
3745 //=======================================================================
3747 bool SMESH_Pattern::
3748 getFacesDefinition(const SMDS_MeshNode** theBndNodes,
3749 const int theNbBndNodes,
3750 const vector< const SMDS_MeshNode* >& theNodes,
3751 list< int >& theFaceDefs,
3752 vector<int>& theQuantity)
3754 bool makePoly = false;
3756 set< const SMDS_MeshNode* > bndNodeSet( theBndNodes, theBndNodes + theNbBndNodes);
3758 map< TNodeSet, list< list< int > > >::iterator nn_IdList;
3760 // make a set of all nodes on a face
3762 if ( !myIs2D ) { // for 2D, merge only edges
3763 nn_IdList = myIdsOnBoundary.find( bndNodeSet );
3764 if ( nn_IdList != myIdsOnBoundary.end() ) {
3765 list< int > & faceIds = nn_IdList->second.front();
3766 if ( !faceIds.empty() ) {
3768 ids.insert( faceIds.begin(), faceIds.end() );
3773 // add ids on links and bnd nodes
3774 int lastFreeId = Max( myXYZIdToNodeMap.rbegin()->first, theNodes.size() );
3775 TElemDef faceDef; // definition for the case if there is no new adjacent volumes
3776 for ( int iN = 0; iN < theNbBndNodes; ++iN )
3778 // add id of iN-th bnd node
3780 nSet.insert( theBndNodes[ iN ] );
3781 nn_IdList = myIdsOnBoundary.find( nSet );
3782 int bndId = ++lastFreeId;
3783 if ( nn_IdList != myIdsOnBoundary.end() ) {
3784 bndId = nn_IdList->second.front().front();
3785 ids.insert( bndId );
3788 myXYZIdToNodeMap.insert( make_pair( bndId, theBndNodes[ iN ] ));
3790 faceDef.push_back( bndId );
3791 // add ids on a link
3793 linkNodes.insert( theBndNodes[ iN ]);
3794 linkNodes.insert( theBndNodes[ (iN + 1) % theNbBndNodes] );
3795 nn_IdList = myIdsOnBoundary.find( linkNodes );
3796 if ( nn_IdList != myIdsOnBoundary.end() ) {
3797 list< int > & linkIds = nn_IdList->second.front();
3798 if ( !linkIds.empty() )
3801 ids.insert( linkIds.begin(), linkIds.end() );
3802 if ( isReversed( theBndNodes[ iN ], linkIds ))
3803 faceDef.insert( faceDef.end(), linkIds.begin(), linkIds.end() );
3805 faceDef.insert( faceDef.end(), linkIds.rbegin(), linkIds.rend() );
3810 // find faces definition of new volumes
3812 bool defsAdded = false;
3813 if ( !myIs2D ) { // for 2D, merge only edges
3814 SMDS_VolumeTool vol;
3815 set< TElemDef* > checkedVolDefs;
3816 set< int >::iterator id = ids.begin();
3817 for ( ; id != ids.end(); ++id )
3819 // definitions of volumes sharing id
3820 list< TElemDef* >& defList = myReverseConnectivity[ *id ];
3821 ASSERT( !defList.empty() );
3822 // loop on volume definitions
3823 list< TElemDef* >::iterator pIdList = defList.begin();
3824 for ( ; pIdList != defList.end(); ++pIdList)
3826 if ( !checkedVolDefs.insert( *pIdList ).second )
3827 continue; // skip already checked volume definition
3828 vector< int > idVec( (*pIdList)->begin(), (*pIdList)->end() );
3829 // loop on face defs of a volume
3830 SMDS_VolumeTool::VolumeType volType = vol.GetType( idVec.size() );
3831 if ( volType == SMDS_VolumeTool::UNKNOWN )
3833 int nbFaces = vol.NbFaces( volType );
3834 for ( int iF = 0; iF < nbFaces; ++iF )
3836 const int* nodeInds = vol.GetFaceNodesIndices( volType, iF, true );
3837 int iN, nbN = vol.NbFaceNodes( volType, iF );
3838 // check if all nodes of a faces are in <ids>
3840 for ( iN = 0; iN < nbN && all; ++iN ) {
3841 int nodeId = idVec[ nodeInds[ iN ]];
3842 all = ( ids.find( nodeId ) != ids.end() );
3845 // store a face definition
3846 for ( iN = 0; iN < nbN; ++iN ) {
3847 theFaceDefs.push_back( idVec[ nodeInds[ iN ]]);
3849 theQuantity.push_back( nbN );
3857 theQuantity.push_back( faceDef.size() );
3858 theFaceDefs.splice( theFaceDefs.end(), faceDef );
3864 //=======================================================================
3865 //function : clearSubMesh
3867 //=======================================================================
3869 static bool clearSubMesh( SMESH_Mesh* theMesh,
3870 const TopoDS_Shape& theShape)
3872 bool removed = false;
3873 if ( SMESH_subMesh * aSubMesh = theMesh->GetSubMeshContaining( theShape ))
3875 removed = !aSubMesh->IsEmpty();
3877 aSubMesh->ComputeStateEngine( SMESH_subMesh::CLEAN );
3880 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
3881 if ( SMESHDS_SubMesh* aSubMeshDS = aMeshDS->MeshElements( theShape ))
3883 SMDS_ElemIteratorPtr eIt = aSubMeshDS->GetElements();
3884 removed = eIt->more();
3885 while ( eIt->more() )
3886 aMeshDS->RemoveElement( eIt->next() );
3887 SMDS_NodeIteratorPtr nIt = aSubMeshDS->GetNodes();
3888 removed = removed || nIt->more();
3889 while ( nIt->more() )
3890 aMeshDS->RemoveNode( smdsNode( nIt->next() ));
3896 //=======================================================================
3897 //function : clearMesh
3898 //purpose : clear mesh elements existing on myShape in theMesh
3899 //=======================================================================
3901 void SMESH_Pattern::clearMesh(SMESH_Mesh* theMesh) const
3904 if ( !myShape.IsNull() )
3906 if ( !clearSubMesh( theMesh, myShape ) && !myIs2D ) { // myShape is SHELL but volumes may be bound to SOLID
3907 TopTools_ListIteratorOfListOfShape it( theMesh->GetAncestors( myShape ));
3908 for (; it.More() && it.Value().ShapeType() == TopAbs_SOLID; it.Next())
3910 clearSubMesh( theMesh, it.Value() );
3916 //=======================================================================
3917 //function : findExistingNodes
3918 //purpose : fills nodes vector with nodes existing on a given shape (IMP 22368)
3919 // Returns true if all nodes for all points on S are found
3920 //=======================================================================
3922 bool SMESH_Pattern::findExistingNodes( SMESH_Mesh* mesh,
3923 const TopoDS_Shape& S,
3924 const std::list< TPoint* > & points,
3925 vector< const SMDS_MeshNode* > & nodesVector)
3927 if ( S.IsNull() || points.empty() )
3930 SMESHDS_Mesh* aMeshDS = mesh->GetMeshDS();
3932 switch ( S.ShapeType() )
3936 int pIndex = points.back() - &myPoints[0];
3937 if ( !nodesVector[ pIndex ] )
3938 nodesVector[ pIndex ] = SMESH_Algo::VertexNode( TopoDS::Vertex( S ), aMeshDS );
3939 return nodesVector[ pIndex ];
3943 const TopoDS_Edge& edge = TopoDS::Edge( S );
3944 map< double, const SMDS_MeshNode* > paramsOfNodes;
3945 if ( !SMESH_Algo::GetSortedNodesOnEdge( aMeshDS, edge,
3946 /*ignoreMediumNodes=*/false,
3948 || paramsOfNodes.size() < 3 )
3950 // points on VERTEXes are included with wrong myU
3951 list< TPoint* >::const_reverse_iterator pItR = ++points.rbegin();
3952 list< TPoint* >::const_iterator pItF = ++points.begin();
3953 const bool isForward = ( (*pItF)->myU < (*pItR)->myU );
3954 map< double, const SMDS_MeshNode* >::iterator u2n = ++paramsOfNodes.begin();
3955 map< double, const SMDS_MeshNode* >::iterator u2nEnd = --paramsOfNodes.end();
3957 if ( paramsOfNodes.size() == points.size() )
3959 for ( ; u2n != u2nEnd; ++u2n )
3961 p = ( isForward ? *pItF : *pItR );
3962 int pIndex = p - &myPoints[0];
3963 if ( !nodesVector [ pIndex ] )
3964 nodesVector [ pIndex ] = u2n->second;
3972 const double tolFact = 0.05;
3973 while ( u2n != u2nEnd && pItF != points.end() )
3975 const double u = u2n->first;
3976 const SMDS_MeshNode* n = u2n->second;
3977 const double tol = ( (++u2n)->first - u ) * tolFact;
3980 p = ( isForward ? *pItF : *pItR );
3981 if ( Abs( u - p->myU ) < tol )
3983 int pIndex = p - &myPoints[0];
3984 if ( !nodesVector [ pIndex ] )
3985 nodesVector [ pIndex ] = n;
3991 while ( p->myU < u && ( ++pItF, ++pItR != points.rend() ));
3995 } // case TopAbs_EDGE:
3998 } // switch ( S.ShapeType() )
4003 //=======================================================================
4004 //function : MakeMesh
4005 //purpose : Create nodes and elements in <theMesh> using nodes
4006 // coordinates computed by either of Apply...() methods
4007 //=======================================================================
4009 bool SMESH_Pattern::MakeMesh(SMESH_Mesh* theMesh,
4010 const bool toCreatePolygons,
4011 const bool toCreatePolyedrs)
4013 MESSAGE(" ::MakeMesh() " );
4014 if ( !myIsComputed )
4015 return setErrorCode( ERR_MAKEM_NOT_COMPUTED );
4017 mergePoints( toCreatePolygons );
4019 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4021 // clear elements and nodes existing on myShape
4024 bool onMeshElements = ( !myElements.empty() );
4026 // Create missing nodes
4028 vector< const SMDS_MeshNode* > nodesVector; // i-th point/xyz -> node
4029 if ( onMeshElements )
4031 nodesVector.resize( Max( myXYZ.size(), myXYZIdToNodeMap.rbegin()->first ), 0 );
4032 map< int, const SMDS_MeshNode*>::iterator i_node = myXYZIdToNodeMap.begin();
4033 for ( ; i_node != myXYZIdToNodeMap.end(); i_node++ ) {
4034 nodesVector[ i_node->first ] = i_node->second;
4036 for ( int i = 0; i < myXYZ.size(); ++i ) {
4037 if ( !nodesVector[ i ] && isDefined( myXYZ[ i ] ) )
4038 nodesVector[ i ] = aMeshDS->AddNode (myXYZ[ i ].X(),
4042 if ( theMesh->HasShapeToMesh() )
4044 // set nodes on EDGEs (IMP 22368)
4045 SMESH_MesherHelper helper( *theMesh );
4046 helper.ToFixNodeParameters( true );
4047 map< TNodeSet, list< list< int > > >::iterator idListIt = myIdsOnBoundary.begin();
4048 for ( ; idListIt != myIdsOnBoundary.end(); idListIt++ )
4050 list<list< int > >& groups = idListIt->second;
4051 const TNodeSet& nodes = idListIt->first;
4052 if ( nodes.size() != 2 )
4053 continue; // not a link
4054 const SMDS_MeshNode* n1 = *nodes.begin();
4055 const SMDS_MeshNode* n2 = *nodes.rbegin();
4056 TopoDS_Shape S1 = helper.GetSubShapeByNode( n1, aMeshDS );
4057 TopoDS_Shape S2 = helper.GetSubShapeByNode( n2, aMeshDS );
4058 if ( S1.IsNull() || S1.ShapeType() < TopAbs_EDGE ||
4059 S2.IsNull() || S2.ShapeType() < TopAbs_EDGE )
4062 if ( S1.ShapeType() == TopAbs_EDGE )
4064 if ( S1 == S2 || helper.IsSubShape( S2, S1 ))
4067 else if ( S2.ShapeType() == TopAbs_EDGE )
4069 if ( helper.IsSubShape( S1, S2 ))
4074 S = helper.GetCommonAncestor( S1, S2, *theMesh, TopAbs_EDGE );
4078 const TopoDS_Edge & E = TopoDS::Edge( S );
4079 helper.SetSubShape( E );
4080 list<list< int > >::iterator g = groups.begin();
4081 for ( ; g != groups.end(); ++g )
4083 list< int >& ids = *g;
4084 list< int >::iterator id = ids.begin();
4085 for ( ; id != ids.end(); ++id )
4086 if ( nodesVector[ *id ] && nodesVector[ *id ]->getshapeId() < 1 )
4089 aMeshDS->SetNodeOnEdge( nodesVector[ *id ], E, u );
4090 helper.CheckNodeU( E, nodesVector[ *id ], u, 1e-7, true );
4095 } // if ( onMeshElements )
4099 nodesVector.resize( myPoints.size(), 0 );
4101 // loop on sub-shapes of myShape: create nodes
4102 map< int, list< TPoint* > >::iterator idPointIt = myShapeIDToPointsMap.begin();
4103 for ( ; idPointIt != myShapeIDToPointsMap.end(); idPointIt++ )
4105 list< TPoint* > & points = idPointIt->second;
4107 if ( !myShapeIDMap.IsEmpty() )
4108 S = myShapeIDMap( idPointIt->first );
4110 // find existing nodes on EDGEs and VERTEXes
4111 if ( findExistingNodes( theMesh, S, points, nodesVector ))
4114 list< TPoint* >::iterator pIt = points.begin();
4115 for ( ; pIt != points.end(); pIt++ )
4117 TPoint* point = *pIt;
4118 int pIndex = point - &myPoints[0];
4119 if ( nodesVector [ pIndex ] )
4121 SMDS_MeshNode* node = aMeshDS->AddNode (point->myXYZ.X(),
4124 nodesVector [ pIndex ] = node;
4126 if ( !S.IsNull() ) {
4128 switch ( S.ShapeType() ) {
4129 case TopAbs_VERTEX: {
4130 aMeshDS->SetNodeOnVertex( node, TopoDS::Vertex( S )); break;
4133 aMeshDS->SetNodeOnEdge( node, TopoDS::Edge( S ), point->myU ); break;
4136 aMeshDS->SetNodeOnFace( node, TopoDS::Face( S ),
4137 point->myUV.X(), point->myUV.Y() ); break;
4140 aMeshDS->SetNodeInVolume( node, TopoDS::Shell( S ));
4149 if ( onMeshElements )
4151 // prepare data to create poly elements
4152 makePolyElements( nodesVector, toCreatePolygons, toCreatePolyedrs );
4155 createElements( theMesh, nodesVector, myElemXYZIDs, myElements );
4156 // sew old and new elements
4157 createElements( theMesh, nodesVector, myPolyElemXYZIDs, myPolyElems );
4161 createElements( theMesh, nodesVector, myElemPointIDs, myElements );
4164 aMeshDS->compactMesh();
4166 // const map<int,SMESHDS_SubMesh*>& sm = aMeshDS->SubMeshes();
4167 // map<int,SMESHDS_SubMesh*>::const_iterator i_sm = sm.begin();
4168 // for ( ; i_sm != sm.end(); i_sm++ )
4170 // cout << " SM " << i_sm->first << " ";
4171 // TopAbs::Print( aMeshDS->IndexToShape( i_sm->first ).ShapeType(), cout)<< " ";
4172 // //SMDS_ElemIteratorPtr GetElements();
4173 // SMDS_NodeIteratorPtr nit = i_sm->second->GetNodes();
4174 // while ( nit->more() )
4175 // cout << nit->next()->GetID() << " ";
4178 return setErrorCode( ERR_OK );
4181 //=======================================================================
4182 //function : createElements
4183 //purpose : add elements to the mesh
4184 //=======================================================================
4186 void SMESH_Pattern::createElements(SMESH_Mesh* theMesh,
4187 const vector<const SMDS_MeshNode* >& theNodesVector,
4188 const list< TElemDef > & theElemNodeIDs,
4189 const vector<const SMDS_MeshElement*>& theElements)
4191 SMESHDS_Mesh* aMeshDS = theMesh->GetMeshDS();
4192 SMESH_MeshEditor editor( theMesh );
4194 bool onMeshElements = !theElements.empty();
4196 // shapes and groups theElements are on
4197 vector< int > shapeIDs;
4198 vector< list< SMESHDS_Group* > > groups;
4199 set< const SMDS_MeshNode* > shellNodes;
4200 if ( onMeshElements )
4202 shapeIDs.resize( theElements.size() );
4203 groups.resize( theElements.size() );
4204 const set<SMESHDS_GroupBase*>& allGroups = aMeshDS->GetGroups();
4205 set<SMESHDS_GroupBase*>::const_iterator grIt;
4206 for ( int i = 0; i < theElements.size(); i++ )
4208 shapeIDs[ i ] = editor.FindShape( theElements[ i ] );
4209 for ( grIt = allGroups.begin(); grIt != allGroups.end(); grIt++ ) {
4210 SMESHDS_Group* group = dynamic_cast<SMESHDS_Group*>( *grIt );
4211 if ( group && group->SMDSGroup().Contains( theElements[ i ] ))
4212 groups[ i ].push_back( group );
4215 // get all nodes bound to shells because their SpacePosition is not set
4216 // by SMESHDS_Mesh::SetNodeInVolume()
4217 TopoDS_Shape aMainShape = aMeshDS->ShapeToMesh();
4218 if ( !aMainShape.IsNull() ) {
4219 TopExp_Explorer shellExp( aMainShape, TopAbs_SHELL );
4220 for ( ; shellExp.More(); shellExp.Next() )
4222 SMESHDS_SubMesh * sm = aMeshDS->MeshElements( shellExp.Current() );
4224 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4225 while ( nIt->more() )
4226 shellNodes.insert( nIt->next() );
4231 // nb new elements per a refined element
4232 int nbNewElemsPerOld = 1;
4233 if ( onMeshElements )
4234 nbNewElemsPerOld = theElemNodeIDs.size() / theElements.size();
4238 list< TElemDef >::const_iterator enIt = theElemNodeIDs.begin();
4239 list< vector<int> >::iterator quantity = myPolyhedronQuantities.begin();
4240 for ( int iElem = 0; enIt != theElemNodeIDs.end(); enIt++, iElem++ )
4242 const TElemDef & elemNodeInd = *enIt;
4244 vector< const SMDS_MeshNode* > nodes( elemNodeInd.size() );
4245 TElemDef::const_iterator id = elemNodeInd.begin();
4247 for ( nbNodes = 0; id != elemNodeInd.end(); id++ ) {
4248 if ( *id < theNodesVector.size() )
4249 nodes[ nbNodes++ ] = theNodesVector[ *id ];
4251 nodes[ nbNodes++ ] = myXYZIdToNodeMap[ *id ];
4253 // dim of refined elem
4254 int elemIndex = iElem / nbNewElemsPerOld; // refined element index
4255 if ( onMeshElements ) {
4256 is2d = ( theElements[ elemIndex ]->GetType() == SMDSAbs_Face );
4259 const SMDS_MeshElement* elem = 0;
4261 switch ( nbNodes ) {
4263 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2] ); break;
4265 elem = aMeshDS->AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4267 if ( !onMeshElements ) {// create a quadratic face
4268 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4269 nodes[4], nodes[5] ); break;
4270 } // else do not break but create a polygon
4272 if ( !onMeshElements ) {// create a quadratic face
4273 elem = aMeshDS->AddFace (nodes[0], nodes[1], nodes[2], nodes[3],
4274 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4275 } // else do not break but create a polygon
4277 elem = aMeshDS->AddPolygonalFace( nodes );
4281 switch ( nbNodes ) {
4283 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3] ); break;
4285 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4288 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4289 nodes[4], nodes[5] ); break;
4291 elem = aMeshDS->AddVolume (nodes[0], nodes[1], nodes[2], nodes[3],
4292 nodes[4], nodes[5], nodes[6], nodes[7] ); break;
4294 elem = aMeshDS->AddPolyhedralVolume( nodes, *quantity++ );
4297 // set element on a shape
4298 if ( elem && onMeshElements ) // applied to mesh elements
4300 int shapeID = shapeIDs[ elemIndex ];
4301 if ( shapeID > 0 ) {
4302 aMeshDS->SetMeshElementOnShape( elem, shapeID );
4303 // set nodes on a shape
4304 TopoDS_Shape S = aMeshDS->IndexToShape( shapeID );
4305 if ( S.ShapeType() == TopAbs_SOLID ) {
4306 TopoDS_Iterator shellIt( S );
4307 if ( shellIt.More() )
4308 shapeID = aMeshDS->ShapeToIndex( shellIt.Value() );
4310 SMDS_ElemIteratorPtr noIt = elem->nodesIterator();
4311 while ( noIt->more() ) {
4312 SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>(smdsNode( noIt->next() ));
4313 if ( node->getshapeId() < 1 &&
4314 shellNodes.find( node ) == shellNodes.end() )
4316 if ( S.ShapeType() == TopAbs_FACE )
4317 aMeshDS->SetNodeOnFace( node, shapeID,
4318 Precision::Infinite(),// <- it's a sign that UV is not set
4319 Precision::Infinite());
4321 aMeshDS->SetNodeInVolume( node, shapeID );
4322 shellNodes.insert( node );
4327 // add elem in groups
4328 list< SMESHDS_Group* >::iterator g = groups[ elemIndex ].begin();
4329 for ( ; g != groups[ elemIndex ].end(); ++g )
4330 (*g)->SMDSGroup().Add( elem );
4332 if ( elem && !myShape.IsNull() ) // applied to shape
4333 aMeshDS->SetMeshElementOnShape( elem, myShape );
4336 // make that SMESH_subMesh::_computeState == COMPUTE_OK
4337 // so that operations with hypotheses will erase the mesh being built
4339 SMESH_subMesh * subMesh;
4340 if ( !myShape.IsNull() ) {
4341 subMesh = theMesh->GetSubMesh( myShape );
4343 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4345 if ( onMeshElements ) {
4346 list< int > elemIDs;
4347 for ( int i = 0; i < theElements.size(); i++ )
4349 subMesh = theMesh->GetSubMeshContaining( shapeIDs[ i ] );
4351 subMesh->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
4353 elemIDs.push_back( theElements[ i ]->GetID() );
4355 // remove refined elements
4356 editor.Remove( elemIDs, false );
4360 //=======================================================================
4361 //function : isReversed
4362 //purpose : check xyz ids order in theIdsList taking into account
4363 // theFirstNode on a link
4364 //=======================================================================
4366 bool SMESH_Pattern::isReversed(const SMDS_MeshNode* theFirstNode,
4367 const list< int >& theIdsList) const
4369 if ( theIdsList.size() < 2 )
4372 gp_Pnt Pf ( theFirstNode->X(), theFirstNode->Y(), theFirstNode->Z() );
4374 list<int>::const_iterator id = theIdsList.begin();
4375 for ( int i = 0; i < 2; ++i, ++id ) {
4376 if ( *id < myXYZ.size() )
4377 P[ i ] = myXYZ[ *id ];
4379 map< int, const SMDS_MeshNode*>::const_iterator i_n;
4380 i_n = myXYZIdToNodeMap.find( *id );
4381 ASSERT( i_n != myXYZIdToNodeMap.end() );
4382 const SMDS_MeshNode* n = i_n->second;
4383 P[ i ].SetCoord( n->X(), n->Y(), n->Z() );
4386 return Pf.SquareDistance( P[ 1 ] ) < Pf.SquareDistance( P[ 0 ] );
4390 //=======================================================================
4391 //function : arrangeBoundaries
4392 //purpose : if there are several wires, arrange boundaryPoints so that
4393 // the outer wire goes first and fix inner wires orientation
4394 // update myKeyPointIDs to correspond to the order of key-points
4395 // in boundaries; sort internal boundaries by the nb of key-points
4396 //=======================================================================
4398 void SMESH_Pattern::arrangeBoundaries (list< list< TPoint* > >& boundaryList)
4400 typedef list< list< TPoint* > >::iterator TListOfListIt;
4401 TListOfListIt bndIt;
4402 list< TPoint* >::iterator pIt;
4404 int nbBoundaries = boundaryList.size();
4405 if ( nbBoundaries > 1 )
4407 // sort boundaries by nb of key-points
4408 if ( nbBoundaries > 2 )
4410 // move boundaries in tmp list
4411 list< list< TPoint* > > tmpList;
4412 tmpList.splice( tmpList.begin(), boundaryList, boundaryList.begin(), boundaryList.end());
4413 // make a map nb-key-points to boundary-position-in-tmpList,
4414 // boundary-positions get ordered in it
4415 typedef map< int, TListOfListIt > TNbKpBndPosMap;
4416 TNbKpBndPosMap nbKpBndPosMap;
4417 bndIt = tmpList.begin();
4418 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4419 for ( ; nbKpIt != myNbKeyPntInBoundary.end(); nbKpIt++, bndIt++ ) {
4420 int nb = *nbKpIt * nbBoundaries;
4421 while ( nbKpBndPosMap.find ( nb ) != nbKpBndPosMap.end() )
4423 nbKpBndPosMap.insert( TNbKpBndPosMap::value_type( nb, bndIt ));
4425 // move boundaries back to boundaryList
4426 TNbKpBndPosMap::iterator nbKpBndPosIt = nbKpBndPosMap.begin();
4427 for ( ; nbKpBndPosIt != nbKpBndPosMap.end(); nbKpBndPosIt++ ) {
4428 TListOfListIt & bndPos2 = (*nbKpBndPosIt).second;
4429 TListOfListIt bndPos1 = bndPos2++;
4430 boundaryList.splice( boundaryList.end(), tmpList, bndPos1, bndPos2 );
4434 // Look for the outer boundary: the one with the point with the least X
4435 double leastX = DBL_MAX;
4436 TListOfListIt outerBndPos;
4437 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++ )
4439 list< TPoint* >& boundary = (*bndIt);
4440 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4442 TPoint* point = *pIt;
4443 if ( point->myInitXYZ.X() < leastX ) {
4444 leastX = point->myInitXYZ.X();
4445 outerBndPos = bndIt;
4450 if ( outerBndPos != boundaryList.begin() )
4451 boundaryList.splice( boundaryList.begin(), boundaryList, outerBndPos, ++outerBndPos );
4453 } // if nbBoundaries > 1
4455 // Check boundaries orientation and re-fill myKeyPointIDs
4457 set< TPoint* > keyPointSet;
4458 list< int >::iterator kpIt = myKeyPointIDs.begin();
4459 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4460 keyPointSet.insert( & myPoints[ *kpIt ]);
4461 myKeyPointIDs.clear();
4463 // update myNbKeyPntInBoundary also
4464 list< int >::iterator nbKpIt = myNbKeyPntInBoundary.begin();
4466 for ( bndIt = boundaryList.begin(); bndIt != boundaryList.end(); bndIt++, nbKpIt++ )
4468 // find the point with the least X
4469 double leastX = DBL_MAX;
4470 list< TPoint* >::iterator xpIt;
4471 list< TPoint* >& boundary = (*bndIt);
4472 for ( pIt = boundary.begin(); pIt != boundary.end(); pIt++)
4474 TPoint* point = *pIt;
4475 if ( point->myInitXYZ.X() < leastX ) {
4476 leastX = point->myInitXYZ.X();
4480 // find points next to the point with the least X
4481 TPoint* p = *xpIt, *pPrev, *pNext;
4482 if ( p == boundary.front() )
4483 pPrev = *(++boundary.rbegin());
4489 if ( p == boundary.back() )
4490 pNext = *(++boundary.begin());
4495 // vectors of boundary direction near <p>
4496 gp_Vec2d v1( pPrev->myInitUV, p->myInitUV ), v2( p->myInitUV, pNext->myInitUV );
4497 double sqMag1 = v1.SquareMagnitude(), sqMag2 = v2.SquareMagnitude();
4498 if ( sqMag1 > DBL_MIN && sqMag2 > DBL_MIN ) {
4499 double yPrev = v1.Y() / sqrt( sqMag1 );
4500 double yNext = v2.Y() / sqrt( sqMag2 );
4501 double sumY = yPrev + yNext;
4503 if ( bndIt == boundaryList.begin() ) // outer boundary
4511 // Put key-point IDs of a well-oriented boundary in myKeyPointIDs
4512 (*nbKpIt) = 0; // count nb of key-points again
4513 pIt = boundary.begin();
4514 for ( ; pIt != boundary.end(); pIt++)
4516 TPoint* point = *pIt;
4517 if ( keyPointSet.find( point ) == keyPointSet.end() )
4519 // find an index of a keypoint
4521 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4522 for ( ; pVecIt != myPoints.end(); pVecIt++, index++ )
4523 if ( &(*pVecIt) == point )
4525 myKeyPointIDs.push_back( index );
4528 myKeyPointIDs.pop_back(); // remove the first key-point from the back
4531 } // loop on a list of boundaries
4533 ASSERT( myKeyPointIDs.size() == keyPointSet.size() );
4536 //=======================================================================
4537 //function : findBoundaryPoints
4538 //purpose : if loaded from file, find points to map on edges and faces and
4539 // compute their parameters
4540 //=======================================================================
4542 bool SMESH_Pattern::findBoundaryPoints()
4544 if ( myIsBoundaryPointsFound ) return true;
4546 MESSAGE(" findBoundaryPoints() ");
4548 myNbKeyPntInBoundary.clear();
4552 set< TPoint* > pointsInElems;
4554 // Find free links of elements:
4555 // put links of all elements in a set and remove links encountered twice
4557 typedef pair< TPoint*, TPoint*> TLink;
4558 set< TLink > linkSet;
4559 list<TElemDef >::iterator epIt = myElemPointIDs.begin();
4560 for ( ; epIt != myElemPointIDs.end(); epIt++ )
4562 TElemDef & elemPoints = *epIt;
4563 TElemDef::iterator pIt = elemPoints.begin();
4564 int prevP = elemPoints.back();
4565 for ( ; pIt != elemPoints.end(); pIt++ ) {
4566 TPoint* p1 = & myPoints[ prevP ];
4567 TPoint* p2 = & myPoints[ *pIt ];
4568 TLink link(( p1 < p2 ? p1 : p2 ), ( p1 < p2 ? p2 : p1 ));
4569 ASSERT( link.first != link.second );
4570 pair<set< TLink >::iterator,bool> itUniq = linkSet.insert( link );
4571 if ( !itUniq.second )
4572 linkSet.erase( itUniq.first );
4575 pointsInElems.insert( p1 );
4578 // Now linkSet contains only free links,
4579 // find the points order that they have in boundaries
4581 // 1. make a map of key-points
4582 set< TPoint* > keyPointSet;
4583 list< int >::iterator kpIt = myKeyPointIDs.begin();
4584 for ( ; kpIt != myKeyPointIDs.end(); kpIt++ )
4585 keyPointSet.insert( & myPoints[ *kpIt ]);
4587 // 2. chain up boundary points
4588 list< list< TPoint* > > boundaryList;
4589 boundaryList.push_back( list< TPoint* >() );
4590 list< TPoint* > * boundary = & boundaryList.back();
4592 TPoint *point1, *point2, *keypoint1;
4593 kpIt = myKeyPointIDs.begin();
4594 point1 = keypoint1 = & myPoints[ *kpIt++ ];
4595 // loop on free links: look for the next point
4597 set< TLink >::iterator lIt = linkSet.begin();
4598 while ( lIt != linkSet.end() )
4600 if ( (*lIt).first == point1 )
4601 point2 = (*lIt).second;
4602 else if ( (*lIt).second == point1 )
4603 point2 = (*lIt).first;
4608 linkSet.erase( lIt );
4609 lIt = linkSet.begin();
4611 if ( keyPointSet.find( point2 ) == keyPointSet.end() ) // not a key-point
4613 boundary->push_back( point2 );
4615 else // a key-point found
4617 keyPointSet.erase( point2 ); // keyPointSet contains not found key-points only
4619 if ( point2 != keypoint1 ) // its not the boundary end
4621 boundary->push_back( point2 );
4623 else // the boundary end reached
4625 boundary->push_front( keypoint1 );
4626 boundary->push_back( keypoint1 );
4627 myNbKeyPntInBoundary.push_back( iKeyPoint );
4628 if ( keyPointSet.empty() )
4629 break; // all boundaries containing key-points are found
4631 // prepare to search for the next boundary
4632 boundaryList.push_back( list< TPoint* >() );
4633 boundary = & boundaryList.back();
4634 point2 = keypoint1 = (*keyPointSet.begin());
4638 } // loop on the free links set
4640 if ( boundary->empty() ) {
4641 MESSAGE(" a separate key-point");
4642 return setErrorCode( ERR_READ_BAD_KEY_POINT );
4645 // if there are several wires, arrange boundaryPoints so that
4646 // the outer wire goes first and fix inner wires orientation;
4647 // sort myKeyPointIDs to correspond to the order of key-points
4649 arrangeBoundaries( boundaryList );
4651 // Find correspondence shape ID - points,
4652 // compute points parameter on edge
4654 keyPointSet.clear();
4655 for ( kpIt = myKeyPointIDs.begin(); kpIt != myKeyPointIDs.end(); kpIt++ )
4656 keyPointSet.insert( & myPoints[ *kpIt ]);
4658 set< TPoint* > edgePointSet; // to find in-face points
4659 int vertexID = 1; // the first index in TopTools_IndexedMapOfShape
4660 int edgeID = myKeyPointIDs.size() + 1;
4662 list< list< TPoint* > >::iterator bndIt = boundaryList.begin();
4663 for ( ; bndIt != boundaryList.end(); bndIt++ )
4665 boundary = & (*bndIt);
4666 double edgeLength = 0;
4667 list< TPoint* >::iterator pIt = boundary->begin();
4668 getShapePoints( edgeID ).push_back( *pIt );
4669 getShapePoints( vertexID++ ).push_back( *pIt );
4670 for ( pIt++; pIt != boundary->end(); pIt++)
4672 list< TPoint* > & edgePoints = getShapePoints( edgeID );
4673 TPoint* prevP = edgePoints.empty() ? 0 : edgePoints.back();
4674 TPoint* point = *pIt;
4675 edgePointSet.insert( point );
4676 if ( keyPointSet.find( point ) == keyPointSet.end() ) // inside-edge point
4678 edgePoints.push_back( point );
4679 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4680 point->myInitU = edgeLength;
4684 // treat points on the edge which ends up: compute U [0,1]
4685 edgePoints.push_back( point );
4686 if ( edgePoints.size() > 2 ) {
4687 edgeLength += ( point->myInitUV - prevP->myInitUV ).Modulus();
4688 list< TPoint* >::iterator epIt = edgePoints.begin();
4689 for ( ; epIt != edgePoints.end(); epIt++ )
4690 (*epIt)->myInitU /= edgeLength;
4692 // begin the next edge treatment
4695 if ( point != boundary->front() ) { // not the first key-point again
4696 getShapePoints( edgeID ).push_back( point );
4697 getShapePoints( vertexID++ ).push_back( point );
4703 // find in-face points
4704 list< TPoint* > & facePoints = getShapePoints( edgeID );
4705 vector< TPoint >::iterator pVecIt = myPoints.begin();
4706 for ( ; pVecIt != myPoints.end(); pVecIt++ ) {
4707 TPoint* point = &(*pVecIt);
4708 if ( edgePointSet.find( point ) == edgePointSet.end() &&
4709 pointsInElems.find( point ) != pointsInElems.end())
4710 facePoints.push_back( point );
4717 // bind points to shapes according to point parameters
4718 vector< TPoint >::iterator pVecIt = myPoints.begin();
4719 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ ) {
4720 TPoint* point = &(*pVecIt);
4721 int shapeID = SMESH_Block::GetShapeIDByParams( point->myInitXYZ );
4722 getShapePoints( shapeID ).push_back( point );
4723 // detect key-points
4724 if ( SMESH_Block::IsVertexID( shapeID ))
4725 myKeyPointIDs.push_back( i );
4729 myIsBoundaryPointsFound = true;
4730 return myIsBoundaryPointsFound;
4733 //=======================================================================
4735 //purpose : clear fields
4736 //=======================================================================
4738 void SMESH_Pattern::Clear()
4740 myIsComputed = myIsBoundaryPointsFound = false;
4743 myKeyPointIDs.clear();
4744 myElemPointIDs.clear();
4745 myShapeIDToPointsMap.clear();
4746 myShapeIDMap.Clear();
4748 myNbKeyPntInBoundary.clear();
4751 myElemXYZIDs.clear();
4752 myXYZIdToNodeMap.clear();
4754 myOrderedNodes.clear();
4755 myPolyElems.clear();
4756 myPolyElemXYZIDs.clear();
4757 myPolyhedronQuantities.clear();
4758 myIdsOnBoundary.clear();
4759 myReverseConnectivity.clear();
4762 //================================================================================
4764 * \brief set ErrorCode and return true if it is Ok
4766 //================================================================================
4768 bool SMESH_Pattern::setErrorCode( const ErrorCode theErrorCode )
4770 myErrorCode = theErrorCode;
4771 return myErrorCode == ERR_OK;
4774 //=======================================================================
4775 //function : setShapeToMesh
4776 //purpose : set a shape to be meshed. Return True if meshing is possible
4777 //=======================================================================
4779 bool SMESH_Pattern::setShapeToMesh(const TopoDS_Shape& theShape)
4781 if ( !IsLoaded() ) {
4782 MESSAGE( "Pattern not loaded" );
4783 return setErrorCode( ERR_APPL_NOT_LOADED );
4786 TopAbs_ShapeEnum aType = theShape.ShapeType();
4787 bool dimOk = ( myIs2D ? aType == TopAbs_FACE : aType == TopAbs_SHELL );
4789 MESSAGE( "Pattern dimention mismatch" );
4790 return setErrorCode( ERR_APPL_BAD_DIMENTION );
4793 // check if a face is closed
4794 int nbNodeOnSeamEdge = 0;
4796 TopTools_MapOfShape seamVertices;
4797 TopoDS_Face face = TopoDS::Face( theShape );
4798 TopExp_Explorer eExp( theShape, TopAbs_EDGE );
4799 for ( ; eExp.More() /*&& nbNodeOnSeamEdge == 0*/; eExp.Next() ) {
4800 const TopoDS_Edge& ee = TopoDS::Edge(eExp.Current());
4801 if ( BRep_Tool::IsClosed(ee, face) ) {
4802 // seam edge and vertices encounter twice in theFace
4803 if ( !seamVertices.Add( TopExp::FirstVertex( ee ))) nbNodeOnSeamEdge++;
4804 if ( !seamVertices.Add( TopExp::LastVertex( ee ))) nbNodeOnSeamEdge++;
4809 // check nb of vertices
4810 TopTools_IndexedMapOfShape vMap;
4811 TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap );
4812 if ( vMap.Extent() + nbNodeOnSeamEdge != myKeyPointIDs.size() ) {
4813 MESSAGE( myKeyPointIDs.size() + nbNodeOnSeamEdge << " != " << vMap.Extent() );
4814 return setErrorCode( ERR_APPL_BAD_NB_VERTICES );
4817 myElements.clear(); // not refine elements
4818 myElemXYZIDs.clear();
4820 myShapeIDMap.Clear();
4825 //=======================================================================
4826 //function : GetMappedPoints
4827 //purpose : Return nodes coordinates computed by Apply() method
4828 //=======================================================================
4830 bool SMESH_Pattern::GetMappedPoints ( list< const gp_XYZ * > & thePoints ) const
4833 if ( !myIsComputed )
4836 if ( myElements.empty() ) { // applied to shape
4837 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4838 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4839 thePoints.push_back( & (*pVecIt).myXYZ.XYZ() );
4841 else { // applied to mesh elements
4842 const gp_XYZ * definedXYZ = & myPoints[ myKeyPointIDs.front() ].myXYZ.XYZ();
4843 vector<gp_XYZ>::const_iterator xyz = myXYZ.begin();
4844 for ( ; xyz != myXYZ.end(); ++xyz )
4845 if ( !isDefined( *xyz ))
4846 thePoints.push_back( definedXYZ );
4848 thePoints.push_back( & (*xyz) );
4850 return !thePoints.empty();
4854 //=======================================================================
4855 //function : GetPoints
4856 //purpose : Return nodes coordinates of the pattern
4857 //=======================================================================
4859 bool SMESH_Pattern::GetPoints ( list< const gp_XYZ * > & thePoints ) const
4866 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4867 for ( ; pVecIt != myPoints.end(); pVecIt++ )
4868 thePoints.push_back( & (*pVecIt).myInitXYZ );
4870 return ( thePoints.size() > 0 );
4873 //=======================================================================
4874 //function : getShapePoints
4875 //purpose : return list of points located on theShape
4876 //=======================================================================
4878 list< SMESH_Pattern::TPoint* > &
4879 SMESH_Pattern::getShapePoints(const TopoDS_Shape& theShape)
4882 if ( !myShapeIDMap.Contains( theShape ))
4883 aShapeID = myShapeIDMap.Add( theShape );
4885 aShapeID = myShapeIDMap.FindIndex( theShape );
4887 return myShapeIDToPointsMap[ aShapeID ];
4890 //=======================================================================
4891 //function : getShapePoints
4892 //purpose : return list of points located on the shape
4893 //=======================================================================
4895 list< SMESH_Pattern::TPoint* > & SMESH_Pattern::getShapePoints(const int theShapeID)
4897 return myShapeIDToPointsMap[ theShapeID ];
4900 //=======================================================================
4901 //function : DumpPoints
4903 //=======================================================================
4905 void SMESH_Pattern::DumpPoints() const
4908 vector< TPoint >::const_iterator pVecIt = myPoints.begin();
4909 for ( int i = 0; pVecIt != myPoints.end(); pVecIt++, i++ )
4910 MESSAGE_ADD ( std::endl << i << ": " << *pVecIt );
4914 //=======================================================================
4915 //function : TPoint()
4917 //=======================================================================
4919 SMESH_Pattern::TPoint::TPoint()
4922 myInitXYZ.SetCoord(0,0,0);
4923 myInitUV.SetCoord(0.,0.);
4925 myXYZ.SetCoord(0,0,0);
4926 myUV.SetCoord(0.,0.);
4931 //=======================================================================
4932 //function : operator <<
4934 //=======================================================================
4936 ostream & operator <<(ostream & OS, const SMESH_Pattern::TPoint& p)
4938 gp_XYZ xyz = p.myInitXYZ;
4939 OS << "\tinit( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4940 gp_XY xy = p.myInitUV;
4941 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4942 double u = p.myInitU;
4943 OS << " u( " << u << " )) " << &p << endl;
4944 xyz = p.myXYZ.XYZ();
4945 OS << "\t ( xyz( " << xyz.X() << " " << xyz.Y() << " " << xyz.Z() << " )";
4947 OS << " uv( " << xy.X() << " " << xy.Y() << " )";
4949 OS << " u( " << u << " ))" << endl;