1 // Copyright (C) 2007-2012 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.
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_MesherHelper.cxx
24 // Created: 15.02.06 15:22:41
25 // Author: Sergey KUUL
27 #include "SMESH_MesherHelper.hxx"
29 #include "SMDS_FacePosition.hxx"
30 #include "SMDS_EdgePosition.hxx"
31 #include "SMDS_VolumeTool.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_ProxyMesh.hxx"
35 #include <BRepAdaptor_Surface.hxx>
36 #include <BRepTools.hxx>
37 #include <BRepTools_WireExplorer.hxx>
38 #include <BRep_Tool.hxx>
39 #include <Geom2d_Curve.hxx>
40 #include <GeomAPI_ProjectPointOnCurve.hxx>
41 #include <GeomAPI_ProjectPointOnSurf.hxx>
42 #include <Geom_Curve.hxx>
43 #include <Geom_RectangularTrimmedSurface.hxx>
44 #include <Geom_Surface.hxx>
45 #include <ShapeAnalysis.hxx>
47 #include <TopExp_Explorer.hxx>
48 #include <TopTools_ListIteratorOfListOfShape.hxx>
49 #include <TopTools_MapIteratorOfMapOfShape.hxx>
50 #include <TopTools_MapOfShape.hxx>
53 #include <gp_Pnt2d.hxx>
54 #include <gp_Trsf.hxx>
56 #include <Standard_Failure.hxx>
57 #include <Standard_ErrorHandler.hxx>
59 #include <utilities.h>
65 #define RETURN_BAD_RESULT(msg) { MESSAGE(msg); return false; }
69 gp_XYZ XYZ(const SMDS_MeshNode* n) { return gp_XYZ(n->X(), n->Y(), n->Z()); }
71 enum { U_periodic = 1, V_periodic = 2 };
74 //================================================================================
78 //================================================================================
80 SMESH_MesherHelper::SMESH_MesherHelper(SMESH_Mesh& theMesh)
81 : myParIndex(0), myMesh(&theMesh), myShapeID(0), myCreateQuadratic(false),
82 myFixNodeParameters(false)
84 myPar1[0] = myPar2[0] = myPar1[1] = myPar2[1] = 0;
85 mySetElemOnShape = ( ! myMesh->HasShapeToMesh() );
88 //=======================================================================
89 //function : ~SMESH_MesherHelper
91 //=======================================================================
93 SMESH_MesherHelper::~SMESH_MesherHelper()
96 TID2ProjectorOnSurf::iterator i_proj = myFace2Projector.begin();
97 for ( ; i_proj != myFace2Projector.end(); ++i_proj )
98 delete i_proj->second;
101 TID2ProjectorOnCurve::iterator i_proj = myEdge2Projector.begin();
102 for ( ; i_proj != myEdge2Projector.end(); ++i_proj )
103 delete i_proj->second;
107 //=======================================================================
108 //function : IsQuadraticSubMesh
109 //purpose : Check submesh for given shape: if all elements on this shape
110 // are quadratic, quadratic elements will be created.
111 // Also fill myTLinkNodeMap
112 //=======================================================================
114 bool SMESH_MesherHelper::IsQuadraticSubMesh(const TopoDS_Shape& aSh)
116 SMESHDS_Mesh* meshDS = GetMeshDS();
117 // we can create quadratic elements only if all elements
118 // created on sub-shapes of given shape are quadratic
119 // also we have to fill myTLinkNodeMap
120 myCreateQuadratic = true;
121 mySeamShapeIds.clear();
122 myDegenShapeIds.clear();
123 TopAbs_ShapeEnum subType( aSh.ShapeType()==TopAbs_FACE ? TopAbs_EDGE : TopAbs_FACE );
124 if ( aSh.ShapeType()==TopAbs_COMPOUND )
126 TopoDS_Iterator subIt( aSh );
128 subType = ( subIt.Value().ShapeType()==TopAbs_FACE ) ? TopAbs_EDGE : TopAbs_FACE;
130 SMDSAbs_ElementType elemType( subType==TopAbs_FACE ? SMDSAbs_Face : SMDSAbs_Edge );
133 int nbOldLinks = myTLinkNodeMap.size();
135 if ( !myMesh->HasShapeToMesh() )
137 if (( myCreateQuadratic = myMesh->NbFaces( ORDER_QUADRATIC )))
139 SMDS_FaceIteratorPtr fIt = meshDS->facesIterator();
140 while ( fIt->more() )
141 AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
146 TopExp_Explorer exp( aSh, subType );
147 TopTools_MapOfShape checkedSubShapes;
148 for (; exp.More() && myCreateQuadratic; exp.Next()) {
149 if ( !checkedSubShapes.Add( exp.Current() ))
150 continue; // needed if aSh is compound of solids
151 if ( SMESHDS_SubMesh * subMesh = meshDS->MeshElements( exp.Current() )) {
152 if ( SMDS_ElemIteratorPtr it = subMesh->GetElements() ) {
154 const SMDS_MeshElement* e = it->next();
155 if ( e->GetType() != elemType || !e->IsQuadratic() ) {
156 myCreateQuadratic = false;
161 switch ( e->NbNodes() ) {
163 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(2)); break;
165 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(3));
166 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(4));
167 AddTLinkNode(e->GetNode(2),e->GetNode(0),e->GetNode(5)); break;
169 AddTLinkNode(e->GetNode(0),e->GetNode(1),e->GetNode(4));
170 AddTLinkNode(e->GetNode(1),e->GetNode(2),e->GetNode(5));
171 AddTLinkNode(e->GetNode(2),e->GetNode(3),e->GetNode(6));
172 AddTLinkNode(e->GetNode(3),e->GetNode(0),e->GetNode(7));
175 myCreateQuadratic = false;
185 if ( nbOldLinks == myTLinkNodeMap.size() )
186 myCreateQuadratic = false;
188 if(!myCreateQuadratic) {
189 myTLinkNodeMap.clear();
193 return myCreateQuadratic;
196 //=======================================================================
197 //function : SetSubShape
198 //purpose : Set geomerty to make elements on
199 //=======================================================================
201 void SMESH_MesherHelper::SetSubShape(const int aShID)
203 if ( aShID == myShapeID )
206 SetSubShape( GetMeshDS()->IndexToShape( aShID ));
208 SetSubShape( TopoDS_Shape() );
211 //=======================================================================
212 //function : SetSubShape
213 //purpose : Set geomerty to create elements on
214 //=======================================================================
216 void SMESH_MesherHelper::SetSubShape(const TopoDS_Shape& aSh)
218 if ( myShape.IsSame( aSh ))
222 mySeamShapeIds.clear();
223 myDegenShapeIds.clear();
225 if ( myShape.IsNull() ) {
229 SMESHDS_Mesh* meshDS = GetMeshDS();
230 myShapeID = meshDS->ShapeToIndex(aSh);
233 // treatment of periodic faces
234 for ( TopExp_Explorer eF( aSh, TopAbs_FACE ); eF.More(); eF.Next() )
236 const TopoDS_Face& face = TopoDS::Face( eF.Current() );
238 Handle(Geom_Surface) surface = BRep_Tool::Surface( face, loc );
240 if ( surface->IsUPeriodic() || surface->IsVPeriodic() ||
241 surface->IsUClosed() || surface->IsVClosed() )
243 //while ( surface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
244 //surface = Handle(Geom_RectangularTrimmedSurface)::DownCast( surface )->BasisSurface();
245 GeomAdaptor_Surface surf( surface );
247 for (TopExp_Explorer exp( face, TopAbs_EDGE ); exp.More(); exp.Next())
249 // look for a seam edge
250 const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
251 if ( BRep_Tool::IsClosed( edge, face )) {
252 // initialize myPar1, myPar2 and myParIndex
254 BRep_Tool::UVPoints( edge, face, uv1, uv2 );
255 if ( Abs( uv1.Coord(1) - uv2.Coord(1) ) < Abs( uv1.Coord(2) - uv2.Coord(2) ))
257 myParIndex |= U_periodic;
258 myPar1[0] = surf.FirstUParameter();
259 myPar2[0] = surf.LastUParameter();
262 myParIndex |= V_periodic;
263 myPar1[1] = surf.FirstVParameter();
264 myPar2[1] = surf.LastVParameter();
266 // store seam shape indices, negative if shape encounters twice
267 int edgeID = meshDS->ShapeToIndex( edge );
268 mySeamShapeIds.insert( IsSeamShape( edgeID ) ? -edgeID : edgeID );
269 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() ) {
270 int vertexID = meshDS->ShapeToIndex( v.Current() );
271 mySeamShapeIds.insert( IsSeamShape( vertexID ) ? -vertexID : vertexID );
275 // look for a degenerated edge
276 if ( BRep_Tool::Degenerated( edge )) {
277 myDegenShapeIds.insert( meshDS->ShapeToIndex( edge ));
278 for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next() )
279 myDegenShapeIds.insert( meshDS->ShapeToIndex( v.Current() ));
286 //=======================================================================
287 //function : GetNodeUVneedInFaceNode
288 //purpose : Check if inFaceNode argument is necessary for call GetNodeUV(F,..)
289 // Return true if the face is periodic.
290 // If F is Null, answer about sub-shape set through IsQuadraticSubMesh() or
292 //=======================================================================
294 bool SMESH_MesherHelper::GetNodeUVneedInFaceNode(const TopoDS_Face& F) const
296 if ( F.IsNull() ) return !mySeamShapeIds.empty();
298 if ( !F.IsNull() && !myShape.IsNull() && myShape.IsSame( F ))
299 return !mySeamShapeIds.empty();
302 Handle(Geom_Surface) aSurface = BRep_Tool::Surface( F,loc );
303 if ( !aSurface.IsNull() )
304 return ( aSurface->IsUPeriodic() || aSurface->IsVPeriodic() );
309 //=======================================================================
310 //function : IsMedium
312 //=======================================================================
314 bool SMESH_MesherHelper::IsMedium(const SMDS_MeshNode* node,
315 const SMDSAbs_ElementType typeToCheck)
317 return SMESH_MeshEditor::IsMedium( node, typeToCheck );
320 //=======================================================================
321 //function : GetSubShapeByNode
322 //purpose : Return support shape of a node
323 //=======================================================================
325 TopoDS_Shape SMESH_MesherHelper::GetSubShapeByNode(const SMDS_MeshNode* node,
326 const SMESHDS_Mesh* meshDS)
328 int shapeID = node->getshapeId();
329 if ( 0 < shapeID && shapeID <= meshDS->MaxShapeIndex() )
330 return meshDS->IndexToShape( shapeID );
332 return TopoDS_Shape();
336 //=======================================================================
337 //function : AddTLinkNode
338 //purpose : add a link in my data structure
339 //=======================================================================
341 void SMESH_MesherHelper::AddTLinkNode(const SMDS_MeshNode* n1,
342 const SMDS_MeshNode* n2,
343 const SMDS_MeshNode* n12)
345 // add new record to map
346 SMESH_TLink link( n1, n2 );
347 myTLinkNodeMap.insert( make_pair(link,n12));
350 //================================================================================
352 * \brief Add quadratic links of edge to own data structure
354 //================================================================================
356 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshEdge* edge)
358 if ( edge->IsQuadratic() )
359 AddTLinkNode(edge->GetNode(0), edge->GetNode(1), edge->GetNode(2));
362 //================================================================================
364 * \brief Add quadratic links of face to own data structure
366 //================================================================================
368 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshFace* f)
371 switch ( f->NbNodes() ) {
373 AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(3));
374 AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(4));
375 AddTLinkNode(f->GetNode(2),f->GetNode(0),f->GetNode(5)); break;
377 AddTLinkNode(f->GetNode(0),f->GetNode(1),f->GetNode(4));
378 AddTLinkNode(f->GetNode(1),f->GetNode(2),f->GetNode(5));
379 AddTLinkNode(f->GetNode(2),f->GetNode(3),f->GetNode(6));
380 AddTLinkNode(f->GetNode(3),f->GetNode(0),f->GetNode(7));
385 //================================================================================
387 * \brief Add quadratic links of volume to own data structure
389 //================================================================================
391 void SMESH_MesherHelper::AddTLinks(const SMDS_MeshVolume* volume)
393 if ( volume->IsQuadratic() )
395 SMDS_VolumeTool vTool( volume );
396 const SMDS_MeshNode** nodes = vTool.GetNodes();
398 for ( int iF = 1; iF < vTool.NbFaces(); ++iF )
400 const int nbN = vTool.NbFaceNodes( iF );
401 const int* iNodes = vTool.GetFaceNodesIndices( iF );
402 for ( int i = 0; i < nbN; )
404 int iN1 = iNodes[i++];
405 int iN12 = iNodes[i++];
406 int iN2 = iNodes[i++];
407 if ( iN1 > iN2 ) std::swap( iN1, iN2 );
408 int linkID = iN1 * vTool.NbNodes() + iN2;
409 pair< set<int>::iterator, bool > it_isNew = addedLinks.insert( linkID );
410 if ( it_isNew.second )
411 AddTLinkNode( nodes[iN1], nodes[iN2], nodes[iN12] );
413 addedLinks.erase( it_isNew.first ); // each link encounters only twice
419 //================================================================================
421 * \brief Return true if position of nodes on the shape hasn't yet been checked or
422 * the positions proved to be invalid
424 //================================================================================
426 bool SMESH_MesherHelper::toCheckPosOnShape(int shapeID ) const
428 map< int,bool >::const_iterator id_ok = myNodePosShapesValidity.find( shapeID );
429 return ( id_ok == myNodePosShapesValidity.end() || !id_ok->second );
432 //================================================================================
434 * \brief Set validity of positions of nodes on the shape.
435 * Once set, validity is not changed
437 //================================================================================
439 void SMESH_MesherHelper::setPosOnShapeValidity(int shapeID, bool ok ) const
441 ((SMESH_MesherHelper*)this)->myNodePosShapesValidity.insert( make_pair( shapeID, ok));
444 //=======================================================================
445 //function : ToFixNodeParameters
446 //purpose : Enables fixing node parameters on EDGEs and FACEs in
447 // GetNodeU(...,check=true), GetNodeUV(...,check=true), CheckNodeUV() and
448 // CheckNodeU() in case if a node lies on a shape set via SetSubShape().
450 //=======================================================================
452 void SMESH_MesherHelper::ToFixNodeParameters(bool toFix)
454 myFixNodeParameters = toFix;
458 //=======================================================================
459 //function : GetUVOnSeam
460 //purpose : Select UV on either of 2 pcurves of a seam edge, closest to the given UV
461 //=======================================================================
463 gp_Pnt2d SMESH_MesherHelper::GetUVOnSeam( const gp_Pnt2d& uv1, const gp_Pnt2d& uv2 ) const
465 gp_Pnt2d result = uv1;
466 for ( int i = U_periodic; i <= V_periodic ; ++i )
468 if ( myParIndex & i )
470 double p1 = uv1.Coord( i );
471 double dp1 = Abs( p1-myPar1[i-1]), dp2 = Abs( p1-myPar2[i-1]);
472 if ( myParIndex == i ||
473 dp1 < ( myPar2[i-1] - myPar2[i-1] ) / 100. ||
474 dp2 < ( myPar2[i-1] - myPar2[i-1] ) / 100. )
476 double p2 = uv2.Coord( i );
477 double p1Alt = ( dp1 < dp2 ) ? myPar2[i-1] : myPar1[i-1];
478 if ( Abs( p2 - p1 ) > Abs( p2 - p1Alt ))
479 result.SetCoord( i, p1Alt );
486 //=======================================================================
487 //function : GetNodeUV
488 //purpose : Return node UV on face
489 //=======================================================================
491 gp_XY SMESH_MesherHelper::GetNodeUV(const TopoDS_Face& F,
492 const SMDS_MeshNode* n,
493 const SMDS_MeshNode* n2,
496 gp_Pnt2d uv( Precision::Infinite(), Precision::Infinite() );
497 const SMDS_PositionPtr Pos = n->GetPosition();
499 if(Pos->GetTypeOfPosition()==SMDS_TOP_FACE)
501 // node has position on face
502 const SMDS_FacePosition* fpos =
503 static_cast<const SMDS_FacePosition*>(n->GetPosition());
504 uv.SetCoord(fpos->GetUParameter(),fpos->GetVParameter());
506 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
508 else if(Pos->GetTypeOfPosition()==SMDS_TOP_EDGE)
510 // node has position on edge => it is needed to find
511 // corresponding edge from face, get pcurve for this
512 // edge and retrieve value from this pcurve
513 const SMDS_EdgePosition* epos =
514 static_cast<const SMDS_EdgePosition*>(n->GetPosition());
515 int edgeID = n->getshapeId();
516 TopoDS_Edge E = TopoDS::Edge(GetMeshDS()->IndexToShape(edgeID));
517 double f, l, u = epos->GetUParameter();
518 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, F, f, l);
519 bool validU = ( f < u && u < l );
521 uv = C2d->Value( u );
523 uv.SetCoord( Precision::Infinite(),0.);
524 if ( check || !validU )
525 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ),/*force=*/ !validU );
527 // for a node on a seam edge select one of UVs on 2 pcurves
528 if ( n2 && IsSeamShape( edgeID ) )
530 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0, check ));
533 { // adjust uv to period
535 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
536 Standard_Boolean isUPeriodic = S->IsUPeriodic();
537 Standard_Boolean isVPeriodic = S->IsVPeriodic();
538 if ( isUPeriodic || isVPeriodic ) {
539 Standard_Real UF,UL,VF,VL;
540 S->Bounds(UF,UL,VF,VL);
542 uv.SetX( uv.X() + ShapeAnalysis::AdjustToPeriod(uv.X(),UF,UL));
544 uv.SetY( uv.Y() + ShapeAnalysis::AdjustToPeriod(uv.Y(),VF,VL));
548 else if(Pos->GetTypeOfPosition()==SMDS_TOP_VERTEX)
550 if ( int vertexID = n->getshapeId() ) {
551 const TopoDS_Vertex& V = TopoDS::Vertex(GetMeshDS()->IndexToShape(vertexID));
553 uv = BRep_Tool::Parameters( V, F );
556 catch (Standard_Failure& exc) {
559 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() )
560 uvOK = ( V == vert.Current() );
563 MESSAGE ( "SMESH_MesherHelper::GetNodeUV(); Vertex " << vertexID
564 << " not in face " << GetMeshDS()->ShapeToIndex( F ) );
566 // get UV of a vertex closest to the node
568 gp_Pnt pn = XYZ( n );
569 for ( TopExp_Explorer vert(F,TopAbs_VERTEX); !uvOK && vert.More(); vert.Next() ) {
570 TopoDS_Vertex curV = TopoDS::Vertex( vert.Current() );
571 gp_Pnt p = BRep_Tool::Pnt( curV );
572 double curDist = p.SquareDistance( pn );
573 if ( curDist < dist ) {
575 uv = BRep_Tool::Parameters( curV, F );
576 uvOK = ( dist < DBL_MIN );
582 TopTools_ListIteratorOfListOfShape it( myMesh->GetAncestors( V ));
583 for ( ; it.More(); it.Next() ) {
584 if ( it.Value().ShapeType() == TopAbs_EDGE ) {
585 const TopoDS_Edge & edge = TopoDS::Edge( it.Value() );
587 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(edge, F, f, l);
588 if ( !C2d.IsNull() ) {
589 double u = ( V == TopExp::FirstVertex( edge ) ) ? f : l;
590 uv = C2d->Value( u );
598 if ( n2 && IsSeamShape( vertexID ) )
599 uv = GetUVOnSeam( uv, GetNodeUV( F, n2, 0 ));
604 uvOK = CheckNodeUV( F, n, uv.ChangeCoord(), 10*MaxTolerance( F ));
613 //=======================================================================
614 //function : CheckNodeUV
615 //purpose : Check and fix node UV on a face
616 //=======================================================================
618 bool SMESH_MesherHelper::CheckNodeUV(const TopoDS_Face& F,
619 const SMDS_MeshNode* n,
623 double distXYZ[4]) const
625 int shapeID = n->getshapeId();
626 bool infinit = ( Precision::IsInfinite( uv.X() ) || Precision::IsInfinite( uv.Y() ));
627 if ( force || toCheckPosOnShape( shapeID ) || infinit )
629 // check that uv is correct
631 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
632 gp_Pnt nodePnt = XYZ( n ), surfPnt(0,0,0);
634 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
636 (dist = nodePnt.Distance( surfPnt = surface->Value( uv.X(), uv.Y() ))) > tol )
638 setPosOnShapeValidity( shapeID, false );
639 if ( !infinit && distXYZ ) {
640 surfPnt.Transform( loc );
642 distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
644 // uv incorrect, project the node to surface
645 GeomAPI_ProjectPointOnSurf& projector = GetProjector( F, loc, tol );
646 projector.Perform( nodePnt );
647 if ( !projector.IsDone() || projector.NbPoints() < 1 )
649 MESSAGE( "SMESH_MesherHelper::CheckNodeUV() failed to project" );
652 Quantity_Parameter U,V;
653 projector.LowerDistanceParameters(U,V);
655 surfPnt = surface->Value( U, V );
656 dist = nodePnt.Distance( surfPnt );
658 surfPnt.Transform( loc );
660 distXYZ[1] = surfPnt.X(); distXYZ[2] = surfPnt.Y(); distXYZ[3]=surfPnt.Z();
664 MESSAGE( "SMESH_MesherHelper::CheckNodeUV(), invalid projection" );
667 // store the fixed UV on the face
668 if ( myShape.IsSame(F) && shapeID == myShapeID && myFixNodeParameters )
669 const_cast<SMDS_MeshNode*>(n)->SetPosition
670 ( SMDS_PositionPtr( new SMDS_FacePosition( U, V )));
672 else if ( uv.Modulus() > numeric_limits<double>::min() )
674 setPosOnShapeValidity( shapeID, true );
680 //=======================================================================
681 //function : GetProjector
682 //purpose : Return projector intitialized by given face without location, which is returned
683 //=======================================================================
685 GeomAPI_ProjectPointOnSurf& SMESH_MesherHelper::GetProjector(const TopoDS_Face& F,
686 TopLoc_Location& loc,
689 Handle(Geom_Surface) surface = BRep_Tool::Surface( F,loc );
690 int faceID = GetMeshDS()->ShapeToIndex( F );
691 TID2ProjectorOnSurf& i2proj = const_cast< TID2ProjectorOnSurf&>( myFace2Projector );
692 TID2ProjectorOnSurf::iterator i_proj = i2proj.find( faceID );
693 if ( i_proj == i2proj.end() )
695 if ( tol == 0 ) tol = BRep_Tool::Tolerance( F );
696 double U1, U2, V1, V2;
697 surface->Bounds(U1, U2, V1, V2);
698 GeomAPI_ProjectPointOnSurf* proj = new GeomAPI_ProjectPointOnSurf();
699 proj->Init( surface, U1, U2, V1, V2, tol );
700 i_proj = i2proj.insert( make_pair( faceID, proj )).first;
702 return *( i_proj->second );
707 gp_XY AverageUV(const gp_XY& uv1, const gp_XY& uv2) { return ( uv1 + uv2 ) / 2.; }
708 gp_XY_FunPtr(Added); // define gp_XY_Added pointer to function calling gp_XY::Added(gp_XY)
709 gp_XY_FunPtr(Subtracted);
712 //=======================================================================
713 //function : applyIn2D
714 //purpose : Perform given operation on two 2d points in parameric space of given surface.
715 // It takes into account period of the surface. Use gp_XY_FunPtr macro
716 // to easily define pointer to function of gp_XY class.
717 //=======================================================================
719 gp_XY SMESH_MesherHelper::applyIn2D(const Handle(Geom_Surface)& surface,
723 const bool resultInPeriod)
725 Standard_Boolean isUPeriodic = surface.IsNull() ? false : surface->IsUPeriodic();
726 Standard_Boolean isVPeriodic = surface.IsNull() ? false : surface->IsVPeriodic();
727 if ( !isUPeriodic && !isVPeriodic )
730 // move uv2 not far than half-period from uv1
732 uv2.X()+(isUPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.X(),uv1.X(),surface->UPeriod()) :0);
734 uv2.Y()+(isVPeriodic ? ShapeAnalysis::AdjustByPeriod(uv2.Y(),uv1.Y(),surface->VPeriod()) :0);
737 gp_XY res = fun( uv1, gp_XY(u2,v2) );
739 // move result within period
740 if ( resultInPeriod )
742 Standard_Real UF,UL,VF,VL;
743 surface->Bounds(UF,UL,VF,VL);
745 res.SetX( res.X() + ShapeAnalysis::AdjustToPeriod(res.X(),UF,UL));
747 res.SetY( res.Y() + ShapeAnalysis::AdjustToPeriod(res.Y(),VF,VL));
752 //=======================================================================
753 //function : GetMiddleUV
754 //purpose : Return middle UV taking in account surface period
755 //=======================================================================
757 gp_XY SMESH_MesherHelper::GetMiddleUV(const Handle(Geom_Surface)& surface,
762 // the proper place of getting basic surface seems to be in applyIn2D()
763 // but we put it here to decrease a risk of regressions just before releasing a version
764 Handle(Geom_Surface) surf = surface;
765 while ( !surf.IsNull() && surf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface )))
766 surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( surf )->BasisSurface();
768 return applyIn2D( surf, p1, p2, & AverageUV );
771 //=======================================================================
772 //function : GetNodeU
773 //purpose : Return node U on edge
774 //=======================================================================
776 double SMESH_MesherHelper::GetNodeU(const TopoDS_Edge& E,
777 const SMDS_MeshNode* n,
778 const SMDS_MeshNode* inEdgeNode,
782 const SMDS_PositionPtr pos = n->GetPosition();
783 if ( pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
785 const SMDS_EdgePosition* epos = static_cast<const SMDS_EdgePosition*>( pos );
786 param = epos->GetUParameter();
788 else if( pos->GetTypeOfPosition() == SMDS_TOP_VERTEX )
790 if ( inEdgeNode && TopExp::FirstVertex( E ).IsSame( TopExp::LastVertex( E ))) // issue 0020128
793 BRep_Tool::Range( E, f,l );
794 double uInEdge = GetNodeU( E, inEdgeNode );
795 param = ( fabs( uInEdge - f ) < fabs( l - uInEdge )) ? f : l;
799 SMESHDS_Mesh * meshDS = GetMeshDS();
800 int vertexID = n->getshapeId();
801 const TopoDS_Vertex& V = TopoDS::Vertex(meshDS->IndexToShape(vertexID));
802 param = BRep_Tool::Parameter( V, E );
807 double tol = BRep_Tool::Tolerance( E );
808 double f,l; BRep_Tool::Range( E, f,l );
809 bool force = ( param < f-tol || param > l+tol );
810 if ( !force && pos->GetTypeOfPosition()==SMDS_TOP_EDGE )
811 force = ( GetMeshDS()->ShapeToIndex( E ) != n->getshapeId() );
813 *check = CheckNodeU( E, n, param, 2*tol, force );
818 //=======================================================================
819 //function : CheckNodeU
820 //purpose : Check and fix node U on an edge
821 // Return false if U is bad and could not be fixed
822 //=======================================================================
824 bool SMESH_MesherHelper::CheckNodeU(const TopoDS_Edge& E,
825 const SMDS_MeshNode* n,
829 double distXYZ[4]) const
831 int shapeID = n->getshapeId();
832 if ( force || toCheckPosOnShape( shapeID ))
834 TopLoc_Location loc; double f,l;
835 Handle(Geom_Curve) curve = BRep_Tool::Curve( E,loc,f,l );
836 if ( curve.IsNull() ) // degenerated edge
838 if ( u+tol < f || u-tol > l )
840 double r = Max( 0.5, 1 - tol*n->GetID()); // to get a unique u on edge
846 gp_Pnt nodePnt = SMESH_TNodeXYZ( n );
847 if ( !loc.IsIdentity() ) nodePnt.Transform( loc.Transformation().Inverted() );
848 gp_Pnt curvPnt = curve->Value( u );
849 double dist = nodePnt.Distance( curvPnt );
851 curvPnt.Transform( loc );
853 distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
857 setPosOnShapeValidity( shapeID, false );
858 // u incorrect, project the node to the curve
859 int edgeID = GetMeshDS()->ShapeToIndex( E );
860 TID2ProjectorOnCurve& i2proj = const_cast< TID2ProjectorOnCurve&>( myEdge2Projector );
861 TID2ProjectorOnCurve::iterator i_proj =
862 i2proj.insert( make_pair( edgeID, (GeomAPI_ProjectPointOnCurve*) 0 )).first;
863 if ( !i_proj->second )
865 i_proj->second = new GeomAPI_ProjectPointOnCurve();
866 i_proj->second->Init( curve, f, l );
868 GeomAPI_ProjectPointOnCurve* projector = i_proj->second;
869 projector->Perform( nodePnt );
870 if ( projector->NbPoints() < 1 )
872 MESSAGE( "SMESH_MesherHelper::CheckNodeU() failed to project" );
875 Quantity_Parameter U = projector->LowerDistanceParameter();
877 curvPnt = curve->Value( u );
878 dist = nodePnt.Distance( curvPnt );
880 curvPnt.Transform( loc );
882 distXYZ[1] = curvPnt.X(); distXYZ[2] = curvPnt.Y(); distXYZ[3]=curvPnt.Z();
886 MESSAGE( "SMESH_MesherHelper::CheckNodeU(), invalid projection" );
887 MESSAGE("distance " << dist << " " << tol );
890 // store the fixed U on the edge
891 if ( myShape.IsSame(E) && shapeID == myShapeID && myFixNodeParameters )
892 const_cast<SMDS_MeshNode*>(n)->SetPosition
893 ( SMDS_PositionPtr( new SMDS_EdgePosition( U )));
895 else if ( fabs( u ) > numeric_limits<double>::min() )
897 setPosOnShapeValidity( shapeID, true );
899 if (( u < f-tol || u > l+tol ) && force )
901 // node is on vertex but is set on periodic but trimmed edge (issue 0020890)
904 // do not use IsPeriodic() as Geom_TrimmedCurve::IsPeriodic () returns false
905 double period = curve->Period();
906 u = ( u < f ) ? u + period : u - period;
908 catch (Standard_Failure& exc)
918 //=======================================================================
919 //function : GetMediumPos
920 //purpose : Return index and type of the shape (EDGE or FACE only) to
921 // set a medium node on
922 //=======================================================================
924 std::pair<int, TopAbs_ShapeEnum> SMESH_MesherHelper::GetMediumPos(const SMDS_MeshNode* n1,
925 const SMDS_MeshNode* n2)
927 TopAbs_ShapeEnum shapeType = TopAbs_SHAPE;
931 if (( myShapeID == n1->getshapeId() || myShapeID == n2->getshapeId() ) && myShapeID > 0 )
933 shapeType = myShape.ShapeType();
936 else if ( n1->getshapeId() == n2->getshapeId() )
938 shapeID = n2->getshapeId();
939 shape = GetSubShapeByNode( n1, GetMeshDS() );
943 const SMDS_TypeOfPosition Pos1 = n1->GetPosition()->GetTypeOfPosition();
944 const SMDS_TypeOfPosition Pos2 = n2->GetPosition()->GetTypeOfPosition();
946 if ( Pos1 == SMDS_TOP_3DSPACE || Pos2 == SMDS_TOP_3DSPACE )
949 else if ( Pos1 == SMDS_TOP_FACE || Pos2 == SMDS_TOP_FACE )
951 if ( Pos1 != SMDS_TOP_FACE || Pos2 != SMDS_TOP_FACE )
953 if ( Pos1 != SMDS_TOP_FACE ) std::swap( n1,n2 );
954 TopoDS_Shape F = GetSubShapeByNode( n1, GetMeshDS() );
955 TopoDS_Shape S = GetSubShapeByNode( n2, GetMeshDS() );
956 if ( IsSubShape( S, F ))
958 shapeType = TopAbs_FACE;
959 shapeID = n1->getshapeId();
963 else if ( Pos1 == SMDS_TOP_EDGE && Pos2 == SMDS_TOP_EDGE )
965 TopoDS_Shape E1 = GetSubShapeByNode( n1, GetMeshDS() );
966 TopoDS_Shape E2 = GetSubShapeByNode( n2, GetMeshDS() );
967 shape = GetCommonAncestor( E1, E2, *myMesh, TopAbs_FACE );
969 else if ( Pos1 == SMDS_TOP_VERTEX && Pos2 == SMDS_TOP_VERTEX )
971 TopoDS_Shape V1 = GetSubShapeByNode( n1, GetMeshDS() );
972 TopoDS_Shape V2 = GetSubShapeByNode( n2, GetMeshDS() );
973 shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_EDGE );
974 if ( shape.IsNull() ) shape = GetCommonAncestor( V1, V2, *myMesh, TopAbs_FACE );
976 else // VERTEX and EDGE
978 if ( Pos1 != SMDS_TOP_VERTEX ) std::swap( n1,n2 );
979 TopoDS_Shape V = GetSubShapeByNode( n1, GetMeshDS() );
980 TopoDS_Shape E = GetSubShapeByNode( n2, GetMeshDS() );
981 if ( IsSubShape( V, E ))
984 shape = GetCommonAncestor( V, E, *myMesh, TopAbs_FACE );
988 if ( !shape.IsNull() )
991 shapeID = GetMeshDS()->ShapeToIndex( shape );
992 shapeType = shape.ShapeType();
994 return make_pair( shapeID, shapeType );
997 //=======================================================================
998 //function : GetMediumNode
999 //purpose : Return existing or create new medium nodes between given ones
1000 //=======================================================================
1002 const SMDS_MeshNode* SMESH_MesherHelper::GetMediumNode(const SMDS_MeshNode* n1,
1003 const SMDS_MeshNode* n2,
1006 // Find existing node
1008 SMESH_TLink link(n1,n2);
1009 ItTLinkNode itLN = myTLinkNodeMap.find( link );
1010 if ( itLN != myTLinkNodeMap.end() ) {
1011 return (*itLN).second;
1014 // Create medium node
1017 SMESHDS_Mesh* meshDS = GetMeshDS();
1019 if ( IsSeamShape( n1->getshapeId() ))
1020 // to get a correct UV of a node on seam, the second node must have checked UV
1021 std::swap( n1, n2 );
1023 // get type of shape for the new medium node
1024 int faceID = -1, edgeID = -1;
1025 TopoDS_Edge E; double u [2];
1026 TopoDS_Face F; gp_XY uv[2];
1027 bool uvOK[2] = { false, false };
1029 pair<int, TopAbs_ShapeEnum> pos = GetMediumPos( n1, n2 );
1031 // get positions of the given nodes on shapes
1032 if ( pos.second == TopAbs_FACE )
1034 F = TopoDS::Face(meshDS->IndexToShape( faceID = pos.first ));
1035 uv[0] = GetNodeUV(F,n1,n2, force3d ? 0 : &uvOK[0]);
1036 uv[1] = GetNodeUV(F,n2,n1, force3d ? 0 : &uvOK[1]);
1038 else if ( pos.second == TopAbs_EDGE )
1040 const SMDS_PositionPtr Pos1 = n1->GetPosition();
1041 const SMDS_PositionPtr Pos2 = n2->GetPosition();
1042 if ( Pos1->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1043 Pos2->GetTypeOfPosition()==SMDS_TOP_EDGE &&
1044 n1->getshapeId() != n2->getshapeId() )
1047 return getMediumNodeOnComposedWire(n1,n2,force3d);
1049 E = TopoDS::Edge(meshDS->IndexToShape( edgeID = pos.first ));
1050 u[0] = GetNodeU(E,n1,n2, force3d ? 0 : &uvOK[0]);
1051 u[1] = GetNodeU(E,n2,n1, force3d ? 0 : &uvOK[1]);
1054 if ( !force3d & uvOK[0] && uvOK[1] )
1056 // we try to create medium node using UV parameters of
1057 // nodes, else - medium between corresponding 3d points
1060 //if ( uvOK[0] && uvOK[1] )
1062 if ( IsDegenShape( n1->getshapeId() )) {
1063 if ( myParIndex & U_periodic ) uv[0].SetCoord( 1, uv[1].Coord( 1 ));
1064 else uv[0].SetCoord( 2, uv[1].Coord( 2 ));
1066 else if ( IsDegenShape( n2->getshapeId() )) {
1067 if ( myParIndex & U_periodic ) uv[1].SetCoord( 1, uv[0].Coord( 1 ));
1068 else uv[1].SetCoord( 2, uv[0].Coord( 2 ));
1071 TopLoc_Location loc;
1072 Handle(Geom_Surface) S = BRep_Tool::Surface(F,loc);
1073 gp_XY UV = GetMiddleUV( S, uv[0], uv[1] );
1074 gp_Pnt P = S->Value( UV.X(), UV.Y() ).Transformed(loc);
1075 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1076 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y());
1077 myTLinkNodeMap.insert(make_pair(link,n12));
1081 else if ( !E.IsNull() )
1084 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f, l);
1087 Standard_Boolean isPeriodic = C->IsPeriodic();
1090 Standard_Real Period = C->Period();
1091 Standard_Real p = u[1]+ShapeAnalysis::AdjustByPeriod(u[1],u[0],Period);
1092 Standard_Real pmid = (u[0]+p)/2.;
1093 U = pmid+ShapeAnalysis::AdjustToPeriod(pmid,C->FirstParameter(),C->LastParameter());
1098 gp_Pnt P = C->Value( U );
1099 n12 = meshDS->AddNode(P.X(), P.Y(), P.Z());
1100 meshDS->SetNodeOnEdge(n12, edgeID, U);
1101 myTLinkNodeMap.insert(make_pair(link,n12));
1108 double x = ( n1->X() + n2->X() )/2.;
1109 double y = ( n1->Y() + n2->Y() )/2.;
1110 double z = ( n1->Z() + n2->Z() )/2.;
1111 n12 = meshDS->AddNode(x,y,z);
1115 gp_XY UV = ( uv[0] + uv[1] ) / 2.;
1116 CheckNodeUV( F, n12, UV, 2*BRep_Tool::Tolerance( F ), /*force=*/true);
1117 meshDS->SetNodeOnFace(n12, faceID, UV.X(), UV.Y() );
1119 else if ( !E.IsNull() )
1121 double U = ( u[0] + u[1] ) / 2.;
1122 CheckNodeU( E, n12, U, 2*BRep_Tool::Tolerance( E ), /*force=*/true);
1123 meshDS->SetNodeOnEdge(n12, edgeID, U);
1125 else if ( myShapeID > 0 )
1127 meshDS->SetNodeInVolume(n12, myShapeID);
1130 myTLinkNodeMap.insert( make_pair( link, n12 ));
1134 //================================================================================
1136 * \brief Makes a medium node if nodes reside different edges
1138 //================================================================================
1140 const SMDS_MeshNode* SMESH_MesherHelper::getMediumNodeOnComposedWire(const SMDS_MeshNode* n1,
1141 const SMDS_MeshNode* n2,
1144 gp_Pnt middle = 0.5 * XYZ(n1) + 0.5 * XYZ(n2);
1145 SMDS_MeshNode* n12 = AddNode( middle.X(), middle.Y(), middle.Z() );
1147 // To find position on edge and 3D position for n12,
1148 // project <middle> to 2 edges and select projection most close to <middle>
1150 double u = 0, distMiddleProj = Precision::Infinite(), distXYZ[4];
1152 TopoDS_Edge edges[2];
1153 for ( int is2nd = 0; is2nd < 2; ++is2nd )
1156 const SMDS_MeshNode* n = is2nd ? n2 : n1;
1157 TopoDS_Shape shape = GetSubShapeByNode( n, GetMeshDS() );
1158 if ( shape.IsNull() || shape.ShapeType() != TopAbs_EDGE )
1161 // project to get U of projection and distance from middle to projection
1162 TopoDS_Edge edge = edges[ is2nd ] = TopoDS::Edge( shape );
1163 double node2MiddleDist = middle.Distance( XYZ(n) );
1164 double foundU = GetNodeU( edge, n );
1165 CheckNodeU( edge, n12, foundU, 2*BRep_Tool::Tolerance(edge), /*force=*/true, distXYZ );
1166 if ( distXYZ[0] < node2MiddleDist )
1168 distMiddleProj = distXYZ[0];
1173 if ( Precision::IsInfinite( distMiddleProj ))
1175 // both projections failed; set n12 on the edge of n1 with U of a common vertex
1176 TopoDS_Vertex vCommon;
1177 if ( TopExp::CommonVertex( edges[0], edges[1], vCommon ))
1178 u = BRep_Tool::Parameter( vCommon, edges[0] );
1181 double f,l, u0 = GetNodeU( edges[0], n1 );
1182 BRep_Tool::Range( edges[0],f,l );
1183 u = ( fabs(u0-f) < fabs(u0-l) ) ? f : l;
1189 // move n12 to position of a successfull projection
1190 double tol = BRep_Tool::Tolerance(edges[ iOkEdge ]);
1191 if ( !force3d && distMiddleProj > 2*tol )
1193 TopLoc_Location loc; double f,l;
1194 Handle(Geom_Curve) curve = BRep_Tool::Curve( edges[iOkEdge],loc,f,l );
1195 gp_Pnt p = curve->Value( u );
1196 GetMeshDS()->MoveNode( n12, p.X(), p.Y(), p.Z() );
1199 GetMeshDS()->SetNodeOnEdge(n12, edges[iOkEdge], u);
1201 myTLinkNodeMap.insert( make_pair( SMESH_TLink(n1,n2), n12 ));
1206 //=======================================================================
1207 //function : AddNode
1208 //purpose : Creates a node
1209 //=======================================================================
1211 SMDS_MeshNode* SMESH_MesherHelper::AddNode(double x, double y, double z, int ID,
1214 SMESHDS_Mesh * meshDS = GetMeshDS();
1215 SMDS_MeshNode* node = 0;
1217 node = meshDS->AddNodeWithID( x, y, z, ID );
1219 node = meshDS->AddNode( x, y, z );
1220 if ( mySetElemOnShape && myShapeID > 0 ) {
1221 switch ( myShape.ShapeType() ) {
1222 case TopAbs_SOLID: meshDS->SetNodeInVolume( node, myShapeID); break;
1223 case TopAbs_SHELL: meshDS->SetNodeInVolume( node, myShapeID); break;
1224 case TopAbs_FACE: meshDS->SetNodeOnFace( node, myShapeID, u, v); break;
1225 case TopAbs_EDGE: meshDS->SetNodeOnEdge( node, myShapeID, u); break;
1226 case TopAbs_VERTEX: meshDS->SetNodeOnVertex( node, myShapeID); break;
1233 //=======================================================================
1234 //function : AddEdge
1235 //purpose : Creates quadratic or linear edge
1236 //=======================================================================
1238 SMDS_MeshEdge* SMESH_MesherHelper::AddEdge(const SMDS_MeshNode* n1,
1239 const SMDS_MeshNode* n2,
1243 SMESHDS_Mesh * meshDS = GetMeshDS();
1245 SMDS_MeshEdge* edge = 0;
1246 if (myCreateQuadratic) {
1247 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1249 edge = meshDS->AddEdgeWithID(n1, n2, n12, id);
1251 edge = meshDS->AddEdge(n1, n2, n12);
1255 edge = meshDS->AddEdgeWithID(n1, n2, id);
1257 edge = meshDS->AddEdge(n1, n2);
1260 if ( mySetElemOnShape && myShapeID > 0 )
1261 meshDS->SetMeshElementOnShape( edge, myShapeID );
1266 //=======================================================================
1267 //function : AddFace
1268 //purpose : Creates quadratic or linear triangle
1269 //=======================================================================
1271 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1272 const SMDS_MeshNode* n2,
1273 const SMDS_MeshNode* n3,
1277 SMESHDS_Mesh * meshDS = GetMeshDS();
1278 SMDS_MeshFace* elem = 0;
1280 if( n1==n2 || n2==n3 || n3==n1 )
1283 if(!myCreateQuadratic) {
1285 elem = meshDS->AddFaceWithID(n1, n2, n3, id);
1287 elem = meshDS->AddFace(n1, n2, n3);
1290 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1291 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1292 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1295 elem = meshDS->AddFaceWithID(n1, n2, n3, n12, n23, n31, id);
1297 elem = meshDS->AddFace(n1, n2, n3, n12, n23, n31);
1299 if ( mySetElemOnShape && myShapeID > 0 )
1300 meshDS->SetMeshElementOnShape( elem, myShapeID );
1305 //=======================================================================
1306 //function : AddFace
1307 //purpose : Creates quadratic or linear quadrangle
1308 //=======================================================================
1310 SMDS_MeshFace* SMESH_MesherHelper::AddFace(const SMDS_MeshNode* n1,
1311 const SMDS_MeshNode* n2,
1312 const SMDS_MeshNode* n3,
1313 const SMDS_MeshNode* n4,
1317 SMESHDS_Mesh * meshDS = GetMeshDS();
1318 SMDS_MeshFace* elem = 0;
1321 return AddFace(n1,n3,n4,id,force3d);
1324 return AddFace(n1,n2,n4,id,force3d);
1327 return AddFace(n1,n2,n3,id,force3d);
1330 return AddFace(n1,n2,n4,id,force3d);
1333 return AddFace(n1,n2,n3,id,force3d);
1336 return AddFace(n1,n2,n3,id,force3d);
1339 if(!myCreateQuadratic) {
1341 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, id);
1343 elem = meshDS->AddFace(n1, n2, n3, n4);
1346 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1347 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1348 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1349 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1352 elem = meshDS->AddFaceWithID(n1, n2, n3, n4, n12, n23, n34, n41, id);
1354 elem = meshDS->AddFace(n1, n2, n3, n4, n12, n23, n34, n41);
1356 if ( mySetElemOnShape && myShapeID > 0 )
1357 meshDS->SetMeshElementOnShape( elem, myShapeID );
1362 //=======================================================================
1363 //function : AddPolygonalFace
1364 //purpose : Creates polygon, with additional nodes in quadratic mesh
1365 //=======================================================================
1367 SMDS_MeshFace* SMESH_MesherHelper::AddPolygonalFace (const vector<const SMDS_MeshNode*>& nodes,
1371 SMESHDS_Mesh * meshDS = GetMeshDS();
1372 SMDS_MeshFace* elem = 0;
1374 if(!myCreateQuadratic) {
1376 elem = meshDS->AddPolygonalFaceWithID(nodes, id);
1378 elem = meshDS->AddPolygonalFace(nodes);
1381 vector<const SMDS_MeshNode*> newNodes;
1382 for ( int i = 0; i < nodes.size(); ++i )
1384 const SMDS_MeshNode* n1 = nodes[i];
1385 const SMDS_MeshNode* n2 = nodes[(i+1)%nodes.size()];
1386 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1387 newNodes.push_back( n1 );
1388 newNodes.push_back( n12 );
1391 elem = meshDS->AddPolygonalFaceWithID(newNodes, id);
1393 elem = meshDS->AddPolygonalFace(newNodes);
1395 if ( mySetElemOnShape && myShapeID > 0 )
1396 meshDS->SetMeshElementOnShape( elem, myShapeID );
1401 //=======================================================================
1402 //function : AddVolume
1403 //purpose : Creates quadratic or linear prism
1404 //=======================================================================
1406 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1407 const SMDS_MeshNode* n2,
1408 const SMDS_MeshNode* n3,
1409 const SMDS_MeshNode* n4,
1410 const SMDS_MeshNode* n5,
1411 const SMDS_MeshNode* n6,
1415 SMESHDS_Mesh * meshDS = GetMeshDS();
1416 SMDS_MeshVolume* elem = 0;
1417 if(!myCreateQuadratic) {
1419 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, id);
1421 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6);
1424 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1425 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1426 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1428 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1429 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1430 const SMDS_MeshNode* n64 = GetMediumNode(n6,n4,force3d);
1432 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1433 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1434 const SMDS_MeshNode* n36 = GetMediumNode(n3,n6,force3d);
1437 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6,
1438 n12, n23, n31, n45, n56, n64, n14, n25, n36, id);
1440 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6,
1441 n12, n23, n31, n45, n56, n64, n14, n25, n36);
1443 if ( mySetElemOnShape && myShapeID > 0 )
1444 meshDS->SetMeshElementOnShape( elem, myShapeID );
1449 //=======================================================================
1450 //function : AddVolume
1451 //purpose : Creates quadratic or linear tetrahedron
1452 //=======================================================================
1454 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1455 const SMDS_MeshNode* n2,
1456 const SMDS_MeshNode* n3,
1457 const SMDS_MeshNode* n4,
1461 SMESHDS_Mesh * meshDS = GetMeshDS();
1462 SMDS_MeshVolume* elem = 0;
1463 if(!myCreateQuadratic) {
1465 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, id);
1467 elem = meshDS->AddVolume(n1, n2, n3, n4);
1470 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1471 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1472 const SMDS_MeshNode* n31 = GetMediumNode(n3,n1,force3d);
1474 const SMDS_MeshNode* n14 = GetMediumNode(n1,n4,force3d);
1475 const SMDS_MeshNode* n24 = GetMediumNode(n2,n4,force3d);
1476 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1479 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34, id);
1481 elem = meshDS->AddVolume(n1, n2, n3, n4, n12, n23, n31, n14, n24, n34);
1483 if ( mySetElemOnShape && myShapeID > 0 )
1484 meshDS->SetMeshElementOnShape( elem, myShapeID );
1489 //=======================================================================
1490 //function : AddVolume
1491 //purpose : Creates quadratic or linear pyramid
1492 //=======================================================================
1494 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1495 const SMDS_MeshNode* n2,
1496 const SMDS_MeshNode* n3,
1497 const SMDS_MeshNode* n4,
1498 const SMDS_MeshNode* n5,
1502 SMDS_MeshVolume* elem = 0;
1503 if(!myCreateQuadratic) {
1505 elem = GetMeshDS()->AddVolumeWithID(n1, n2, n3, n4, n5, id);
1507 elem = GetMeshDS()->AddVolume(n1, n2, n3, n4, n5);
1510 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1511 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1512 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1513 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1515 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1516 const SMDS_MeshNode* n25 = GetMediumNode(n2,n5,force3d);
1517 const SMDS_MeshNode* n35 = GetMediumNode(n3,n5,force3d);
1518 const SMDS_MeshNode* n45 = GetMediumNode(n4,n5,force3d);
1521 elem = GetMeshDS()->AddVolumeWithID ( n1, n2, n3, n4, n5,
1526 elem = GetMeshDS()->AddVolume( n1, n2, n3, n4, n5,
1528 n15, n25, n35, n45);
1530 if ( mySetElemOnShape && myShapeID > 0 )
1531 GetMeshDS()->SetMeshElementOnShape( elem, myShapeID );
1536 //=======================================================================
1537 //function : AddVolume
1538 //purpose : Creates quadratic or linear hexahedron
1539 //=======================================================================
1541 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1542 const SMDS_MeshNode* n2,
1543 const SMDS_MeshNode* n3,
1544 const SMDS_MeshNode* n4,
1545 const SMDS_MeshNode* n5,
1546 const SMDS_MeshNode* n6,
1547 const SMDS_MeshNode* n7,
1548 const SMDS_MeshNode* n8,
1552 SMESHDS_Mesh * meshDS = GetMeshDS();
1553 SMDS_MeshVolume* elem = 0;
1554 if(!myCreateQuadratic) {
1556 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8, id);
1558 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8);
1561 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1562 const SMDS_MeshNode* n23 = GetMediumNode(n2,n3,force3d);
1563 const SMDS_MeshNode* n34 = GetMediumNode(n3,n4,force3d);
1564 const SMDS_MeshNode* n41 = GetMediumNode(n4,n1,force3d);
1566 const SMDS_MeshNode* n56 = GetMediumNode(n5,n6,force3d);
1567 const SMDS_MeshNode* n67 = GetMediumNode(n6,n7,force3d);
1568 const SMDS_MeshNode* n78 = GetMediumNode(n7,n8,force3d);
1569 const SMDS_MeshNode* n85 = GetMediumNode(n8,n5,force3d);
1571 const SMDS_MeshNode* n15 = GetMediumNode(n1,n5,force3d);
1572 const SMDS_MeshNode* n26 = GetMediumNode(n2,n6,force3d);
1573 const SMDS_MeshNode* n37 = GetMediumNode(n3,n7,force3d);
1574 const SMDS_MeshNode* n48 = GetMediumNode(n4,n8,force3d);
1577 elem = meshDS->AddVolumeWithID(n1, n2, n3, n4, n5, n6, n7, n8,
1578 n12, n23, n34, n41, n56, n67,
1579 n78, n85, n15, n26, n37, n48, id);
1581 elem = meshDS->AddVolume(n1, n2, n3, n4, n5, n6, n7, n8,
1582 n12, n23, n34, n41, n56, n67,
1583 n78, n85, n15, n26, n37, n48);
1585 if ( mySetElemOnShape && myShapeID > 0 )
1586 meshDS->SetMeshElementOnShape( elem, myShapeID );
1591 //=======================================================================
1592 //function : AddVolume
1593 //purpose : Creates LINEAR!!!!!!!!! octahedron
1594 //=======================================================================
1596 SMDS_MeshVolume* SMESH_MesherHelper::AddVolume(const SMDS_MeshNode* n1,
1597 const SMDS_MeshNode* n2,
1598 const SMDS_MeshNode* n3,
1599 const SMDS_MeshNode* n4,
1600 const SMDS_MeshNode* n5,
1601 const SMDS_MeshNode* n6,
1602 const SMDS_MeshNode* n7,
1603 const SMDS_MeshNode* n8,
1604 const SMDS_MeshNode* n9,
1605 const SMDS_MeshNode* n10,
1606 const SMDS_MeshNode* n11,
1607 const SMDS_MeshNode* n12,
1611 SMESHDS_Mesh * meshDS = GetMeshDS();
1612 SMDS_MeshVolume* elem = 0;
1614 elem = meshDS->AddVolumeWithID(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,id);
1616 elem = meshDS->AddVolume(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12);
1617 if ( mySetElemOnShape && myShapeID > 0 )
1618 meshDS->SetMeshElementOnShape( elem, myShapeID );
1622 //=======================================================================
1623 //function : AddPolyhedralVolume
1624 //purpose : Creates polyhedron. In quadratic mesh, adds medium nodes
1625 //=======================================================================
1628 SMESH_MesherHelper::AddPolyhedralVolume (const std::vector<const SMDS_MeshNode*>& nodes,
1629 const std::vector<int>& quantities,
1633 SMESHDS_Mesh * meshDS = GetMeshDS();
1634 SMDS_MeshVolume* elem = 0;
1635 if(!myCreateQuadratic)
1638 elem = meshDS->AddPolyhedralVolumeWithID(nodes, quantities, id);
1640 elem = meshDS->AddPolyhedralVolume(nodes, quantities);
1644 vector<const SMDS_MeshNode*> newNodes;
1645 vector<int> newQuantities;
1646 for ( int iFace=0, iN=0; iFace < quantities.size(); ++iFace)
1648 int nbNodesInFace = quantities[iFace];
1649 newQuantities.push_back(0);
1650 for ( int i = 0; i < nbNodesInFace; ++i )
1652 const SMDS_MeshNode* n1 = nodes[ iN + i ];
1653 newNodes.push_back( n1 );
1654 newQuantities.back()++;
1656 const SMDS_MeshNode* n2 = nodes[ iN + ( i+1==nbNodesInFace ? 0 : i+1 )];
1657 // if ( n1->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE &&
1658 // n2->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
1660 const SMDS_MeshNode* n12 = GetMediumNode(n1,n2,force3d);
1661 newNodes.push_back( n12 );
1662 newQuantities.back()++;
1665 iN += nbNodesInFace;
1668 elem = meshDS->AddPolyhedralVolumeWithID( newNodes, newQuantities, id );
1670 elem = meshDS->AddPolyhedralVolume( newNodes, newQuantities );
1672 if ( mySetElemOnShape && myShapeID > 0 )
1673 meshDS->SetMeshElementOnShape( elem, myShapeID );
1680 //================================================================================
1682 * \brief Check if a node belongs to any face of sub-mesh
1684 //================================================================================
1686 bool isNodeInSubMesh( const SMDS_MeshNode* n, const SMESHDS_SubMesh* sm )
1688 SMDS_ElemIteratorPtr fIt = n->GetInverseElementIterator( SMDSAbs_Face );
1689 while ( fIt->more() )
1690 if ( sm->Contains( fIt->next() ))
1696 //=======================================================================
1697 //function : LoadNodeColumns
1698 //purpose : Load nodes bound to face into a map of node columns
1699 //=======================================================================
1701 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1702 const TopoDS_Face& theFace,
1703 const TopoDS_Edge& theBaseEdge,
1704 SMESHDS_Mesh* theMesh,
1705 SMESH_ProxyMesh* theProxyMesh)
1707 return LoadNodeColumns(theParam2ColumnMap,
1709 std::list<TopoDS_Edge>(1,theBaseEdge),
1714 //=======================================================================
1715 //function : LoadNodeColumns
1716 //purpose : Load nodes bound to face into a map of node columns
1717 //=======================================================================
1719 bool SMESH_MesherHelper::LoadNodeColumns(TParam2ColumnMap & theParam2ColumnMap,
1720 const TopoDS_Face& theFace,
1721 const std::list<TopoDS_Edge>& theBaseSide,
1722 SMESHDS_Mesh* theMesh,
1723 SMESH_ProxyMesh* theProxyMesh)
1725 // get a right submesh of theFace
1727 const SMESHDS_SubMesh* faceSubMesh = 0;
1730 faceSubMesh = theProxyMesh->GetSubMesh( theFace );
1731 if ( !faceSubMesh ||
1732 faceSubMesh->NbElements() == 0 ||
1733 theProxyMesh->IsTemporary( faceSubMesh->GetElements()->next() ))
1735 // can use a proxy sub-mesh with not temporary elements only
1741 faceSubMesh = theMesh->MeshElements( theFace );
1742 if ( !faceSubMesh || faceSubMesh->NbElements() == 0 )
1745 // get data of edges for normalization of params
1747 vector< double > length;
1749 list<TopoDS_Edge>::const_iterator edge;
1751 for ( edge = theBaseSide.begin(); edge != theBaseSide.end(); ++edge )
1753 double len = std::max( 1e-10, SMESH_Algo::EdgeLength( *edge ));
1755 length.push_back( len );
1759 // get nodes on theBaseEdge sorted by param on edge and initialize theParam2ColumnMap with them
1760 edge = theBaseSide.begin();
1761 for ( int iE = 0; edge != theBaseSide.end(); ++edge, ++iE )
1763 map< double, const SMDS_MeshNode*> sortedBaseNodes;
1764 SMESH_Algo::GetSortedNodesOnEdge( theMesh, *edge,/*noMedium=*/true, sortedBaseNodes);
1765 if ( sortedBaseNodes.empty() ) continue;
1767 map< double, const SMDS_MeshNode*>::iterator u_n = sortedBaseNodes.begin();
1768 if ( theProxyMesh ) // from sortedBaseNodes remove nodes not shared by faces of faceSubMesh
1770 const SMDS_MeshNode* n1 = sortedBaseNodes.begin()->second;
1771 const SMDS_MeshNode* n2 = sortedBaseNodes.rbegin()->second;
1772 bool allNodesAreProxy = ( n1 != theProxyMesh->GetProxyNode( n1 ) &&
1773 n2 != theProxyMesh->GetProxyNode( n2 ));
1774 if ( allNodesAreProxy )
1775 for ( u_n = sortedBaseNodes.begin(); u_n != sortedBaseNodes.end(); u_n++ )
1776 u_n->second = theProxyMesh->GetProxyNode( u_n->second );
1778 if ( u_n = sortedBaseNodes.begin(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
1780 while ( ++u_n != sortedBaseNodes.end() && !isNodeInSubMesh( u_n->second, faceSubMesh ));
1781 sortedBaseNodes.erase( sortedBaseNodes.begin(), u_n );
1783 else if ( u_n = --sortedBaseNodes.end(), !isNodeInSubMesh( u_n->second, faceSubMesh ))
1785 while ( u_n != sortedBaseNodes.begin() && !isNodeInSubMesh( (--u_n)->second, faceSubMesh ));
1786 sortedBaseNodes.erase( ++u_n, sortedBaseNodes.end() );
1788 if ( sortedBaseNodes.empty() ) continue;
1792 BRep_Tool::Range( *edge, f, l );
1793 if ( edge->Orientation() == TopAbs_REVERSED ) std::swap( f, l );
1794 const double coeff = 1. / ( l - f ) * length[iE] / fullLen;
1795 const double prevPar = theParam2ColumnMap.empty() ? 0 : theParam2ColumnMap.rbegin()->first;
1796 for ( u_n = sortedBaseNodes.begin(); u_n != sortedBaseNodes.end(); u_n++ )
1798 double par = prevPar + coeff * ( u_n->first - f );
1799 TParam2ColumnMap::iterator u2nn =
1800 theParam2ColumnMap.insert( theParam2ColumnMap.end(), make_pair( par, TNodeColumn()));
1801 u2nn->second.push_back( u_n->second );
1804 if ( theParam2ColumnMap.empty() )
1808 int nbRows = 1 + faceSubMesh->NbElements() / ( theParam2ColumnMap.size()-1 );
1810 // fill theParam2ColumnMap column by column by passing from nodes on
1811 // theBaseEdge up via mesh faces on theFace
1813 TParam2ColumnMap::iterator par_nVec_1, par_nVec_2;
1814 par_nVec_2 = theParam2ColumnMap.begin();
1815 par_nVec_1 = par_nVec_2++;
1816 TIDSortedElemSet emptySet, avoidSet;
1817 for ( ; par_nVec_2 != theParam2ColumnMap.end(); ++par_nVec_1, ++par_nVec_2 )
1819 vector<const SMDS_MeshNode*>& nCol1 = par_nVec_1->second;
1820 vector<const SMDS_MeshNode*>& nCol2 = par_nVec_2->second;
1821 nCol1.resize( nbRows );
1822 nCol2.resize( nbRows );
1824 int i1, i2, iRow = 0;
1825 const SMDS_MeshNode *n1 = nCol1[0], *n2 = nCol2[0];
1826 // find face sharing node n1 and n2 and belonging to faceSubMesh
1827 while ( const SMDS_MeshElement* face =
1828 SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, avoidSet, &i1, &i2))
1830 if ( faceSubMesh->Contains( face ))
1832 int nbNodes = face->IsQuadratic() ? face->NbNodes()/2 : face->NbNodes();
1835 n1 = face->GetNode( (i2+2) % 4 ); // opposite corner of quadrangle face
1836 n2 = face->GetNode( (i1+2) % 4 );
1837 if ( ++iRow >= nbRows )
1843 avoidSet.insert( face );
1845 // set a real height
1846 nCol1.resize( iRow + 1 );
1847 nCol2.resize( iRow + 1 );
1849 return theParam2ColumnMap.size() > 1 && theParam2ColumnMap.begin()->second.size() > 1;
1852 //=======================================================================
1853 //function : NbAncestors
1854 //purpose : Return number of unique ancestors of the shape
1855 //=======================================================================
1857 int SMESH_MesherHelper::NbAncestors(const TopoDS_Shape& shape,
1858 const SMESH_Mesh& mesh,
1859 TopAbs_ShapeEnum ancestorType/*=TopAbs_SHAPE*/)
1861 TopTools_MapOfShape ancestors;
1862 TopTools_ListIteratorOfListOfShape ansIt( mesh.GetAncestors(shape) );
1863 for ( ; ansIt.More(); ansIt.Next() ) {
1864 if ( ancestorType == TopAbs_SHAPE || ansIt.Value().ShapeType() == ancestorType )
1865 ancestors.Add( ansIt.Value() );
1867 return ancestors.Extent();
1870 //=======================================================================
1871 //function : GetSubShapeOri
1872 //purpose : Return orientation of sub-shape in the main shape
1873 //=======================================================================
1875 TopAbs_Orientation SMESH_MesherHelper::GetSubShapeOri(const TopoDS_Shape& shape,
1876 const TopoDS_Shape& subShape)
1878 TopAbs_Orientation ori = TopAbs_Orientation(-1);
1879 if ( !shape.IsNull() && !subShape.IsNull() )
1881 TopExp_Explorer e( shape, subShape.ShapeType() );
1882 if ( shape.Orientation() >= TopAbs_INTERNAL ) // TopAbs_INTERNAL or TopAbs_EXTERNAL
1883 e.Init( shape.Oriented(TopAbs_FORWARD), subShape.ShapeType() );
1884 for ( ; e.More(); e.Next())
1885 if ( subShape.IsSame( e.Current() ))
1888 ori = e.Current().Orientation();
1893 //=======================================================================
1894 //function : IsSubShape
1896 //=======================================================================
1898 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape,
1899 const TopoDS_Shape& mainShape )
1901 if ( !shape.IsNull() && !mainShape.IsNull() )
1903 for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
1906 if ( shape.IsSame( exp.Current() ))
1909 SCRUTE((shape.IsNull()));
1910 SCRUTE((mainShape.IsNull()));
1914 //=======================================================================
1915 //function : IsSubShape
1917 //=======================================================================
1919 bool SMESH_MesherHelper::IsSubShape( const TopoDS_Shape& shape, SMESH_Mesh* aMesh )
1921 if ( shape.IsNull() || !aMesh )
1924 aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
1926 (shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape ));
1929 //================================================================================
1931 * \brief Return maximal tolerance of shape
1933 //================================================================================
1935 double SMESH_MesherHelper::MaxTolerance( const TopoDS_Shape& shape )
1937 double tol = Precision::Confusion();
1938 TopExp_Explorer exp;
1939 for ( exp.Init( shape, TopAbs_FACE ); exp.More(); exp.Next() )
1940 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Face( exp.Current())));
1941 for ( exp.Init( shape, TopAbs_EDGE ); exp.More(); exp.Next() )
1942 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Edge( exp.Current())));
1943 for ( exp.Init( shape, TopAbs_VERTEX ); exp.More(); exp.Next() )
1944 tol = Max( tol, BRep_Tool::Tolerance( TopoDS::Vertex( exp.Current())));
1949 //================================================================================
1951 * \brief Check if the first and last vertices of an edge are the same
1952 * \param anEdge - the edge to check
1953 * \retval bool - true if same
1955 //================================================================================
1957 bool SMESH_MesherHelper::IsClosedEdge( const TopoDS_Edge& anEdge )
1959 if ( anEdge.Orientation() >= TopAbs_INTERNAL )
1960 return IsClosedEdge( TopoDS::Edge( anEdge.Oriented( TopAbs_FORWARD )));
1961 return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
1964 //================================================================================
1966 * \brief Wrapper over TopExp::FirstVertex() and TopExp::LastVertex() fixing them
1967 * in the case of INTERNAL edge
1969 //================================================================================
1971 TopoDS_Vertex SMESH_MesherHelper::IthVertex( const bool is2nd,
1975 if ( anEdge.Orientation() >= TopAbs_INTERNAL )
1976 anEdge.Orientation( TopAbs_FORWARD );
1978 const TopAbs_Orientation tgtOri = is2nd ? TopAbs_REVERSED : TopAbs_FORWARD;
1979 TopoDS_Iterator vIt( anEdge, CumOri );
1980 while ( vIt.More() && vIt.Value().Orientation() != tgtOri )
1983 return ( vIt.More() ? TopoDS::Vertex(vIt.Value()) : TopoDS_Vertex() );
1986 //=======================================================================
1987 //function : IsQuadraticMesh
1988 //purpose : Check mesh without geometry for: if all elements on this shape are quadratic,
1989 // quadratic elements will be created.
1990 // Used then generated 3D mesh without geometry.
1991 //=======================================================================
1993 SMESH_MesherHelper:: MType SMESH_MesherHelper::IsQuadraticMesh()
1995 int NbAllEdgsAndFaces=0;
1996 int NbQuadFacesAndEdgs=0;
1997 int NbFacesAndEdges=0;
1998 //All faces and edges
1999 NbAllEdgsAndFaces = myMesh->NbEdges() + myMesh->NbFaces();
2001 //Quadratic faces and edges
2002 NbQuadFacesAndEdgs = myMesh->NbEdges(ORDER_QUADRATIC) + myMesh->NbFaces(ORDER_QUADRATIC);
2004 //Linear faces and edges
2005 NbFacesAndEdges = myMesh->NbEdges(ORDER_LINEAR) + myMesh->NbFaces(ORDER_LINEAR);
2007 if (NbAllEdgsAndFaces == NbQuadFacesAndEdgs) {
2009 return SMESH_MesherHelper::QUADRATIC;
2011 else if (NbAllEdgsAndFaces == NbFacesAndEdges) {
2013 return SMESH_MesherHelper::LINEAR;
2016 //Mesh with both type of elements
2017 return SMESH_MesherHelper::COMP;
2020 //=======================================================================
2021 //function : GetOtherParam
2022 //purpose : Return an alternative parameter for a node on seam
2023 //=======================================================================
2025 double SMESH_MesherHelper::GetOtherParam(const double param) const
2027 int i = myParIndex & U_periodic ? 0 : 1;
2028 return fabs(param-myPar1[i]) < fabs(param-myPar2[i]) ? myPar2[i] : myPar1[i];
2033 //=======================================================================
2035 * \brief Iterator on ancestors of the given type
2037 //=======================================================================
2039 struct TAncestorsIterator : public SMDS_Iterator<const TopoDS_Shape*>
2041 TopTools_ListIteratorOfListOfShape _ancIter;
2042 TopAbs_ShapeEnum _type;
2043 TopTools_MapOfShape _encountered;
2044 TAncestorsIterator( const TopTools_ListOfShape& ancestors, TopAbs_ShapeEnum type)
2045 : _ancIter( ancestors ), _type( type )
2047 if ( _ancIter.More() ) {
2048 if ( _ancIter.Value().ShapeType() != _type ) next();
2049 else _encountered.Add( _ancIter.Value() );
2054 return _ancIter.More();
2056 virtual const TopoDS_Shape* next()
2058 const TopoDS_Shape* s = _ancIter.More() ? & _ancIter.Value() : 0;
2059 if ( _ancIter.More() )
2060 for ( _ancIter.Next(); _ancIter.More(); _ancIter.Next())
2061 if ( _ancIter.Value().ShapeType() == _type && _encountered.Add( _ancIter.Value() ))
2069 //=======================================================================
2071 * \brief Return iterator on ancestors of the given type
2073 //=======================================================================
2075 PShapeIteratorPtr SMESH_MesherHelper::GetAncestors(const TopoDS_Shape& shape,
2076 const SMESH_Mesh& mesh,
2077 TopAbs_ShapeEnum ancestorType)
2079 return PShapeIteratorPtr( new TAncestorsIterator( mesh.GetAncestors(shape), ancestorType));
2082 //=======================================================================
2083 //function : GetCommonAncestor
2084 //purpose : Find a common ancestors of two shapes of the given type
2085 //=======================================================================
2087 TopoDS_Shape SMESH_MesherHelper::GetCommonAncestor(const TopoDS_Shape& shape1,
2088 const TopoDS_Shape& shape2,
2089 const SMESH_Mesh& mesh,
2090 TopAbs_ShapeEnum ancestorType)
2092 TopoDS_Shape commonAnc;
2093 if ( !shape1.IsNull() && !shape2.IsNull() )
2095 PShapeIteratorPtr ancIt = GetAncestors( shape1, mesh, ancestorType );
2096 while ( const TopoDS_Shape* anc = ancIt->next() )
2097 if ( IsSubShape( shape2, *anc ))
2106 //#include <Perf_Meter.hxx>
2108 //=======================================================================
2109 namespace { // Structures used by FixQuadraticElements()
2110 //=======================================================================
2112 #define __DMP__(txt) \
2114 #define MSG(txt) __DMP__(txt<<endl)
2115 #define MSGBEG(txt) __DMP__(txt)
2117 //const double straightTol2 = 1e-33; // to detect straing links
2118 bool isStraightLink(double linkLen2, double middleNodeMove2)
2120 // straight if <node move> < 1/15 * <link length>
2121 return middleNodeMove2 < 1/15./15. * linkLen2;
2125 // ---------------------------------------
2127 * \brief Quadratic link knowing its faces
2129 struct QLink: public SMESH_TLink
2131 const SMDS_MeshNode* _mediumNode;
2132 mutable vector<const QFace* > _faces;
2133 mutable gp_Vec _nodeMove;
2134 mutable int _nbMoves;
2136 QLink(const SMDS_MeshNode* n1, const SMDS_MeshNode* n2, const SMDS_MeshNode* nm):
2137 SMESH_TLink( n1,n2 ), _mediumNode(nm), _nodeMove(0,0,0), _nbMoves(0) {
2139 //if ( MediumPos() != SMDS_TOP_3DSPACE )
2140 _nodeMove = MediumPnt() - MiddlePnt();
2142 void SetContinuesFaces() const;
2143 const QFace* GetContinuesFace( const QFace* face ) const;
2144 bool OnBoundary() const;
2145 gp_XYZ MiddlePnt() const { return ( XYZ( node1() ) + XYZ( node2() )) / 2.; }
2146 gp_XYZ MediumPnt() const { return XYZ( _mediumNode ); }
2148 SMDS_TypeOfPosition MediumPos() const
2149 { return _mediumNode->GetPosition()->GetTypeOfPosition(); }
2150 SMDS_TypeOfPosition EndPos(bool isSecond) const
2151 { return (isSecond ? node2() : node1())->GetPosition()->GetTypeOfPosition(); }
2152 const SMDS_MeshNode* EndPosNode(SMDS_TypeOfPosition pos) const
2153 { return EndPos(0) == pos ? node1() : EndPos(1) == pos ? node2() : 0; }
2155 void Move(const gp_Vec& move, bool sum=false) const
2156 { _nodeMove += move; _nbMoves += sum ? (_nbMoves==0) : 1; }
2157 gp_XYZ Move() const { return _nodeMove.XYZ() / _nbMoves; }
2158 bool IsMoved() const { return (_nbMoves > 0 /*&& !IsStraight()*/); }
2159 bool IsStraight() const
2160 { return isStraightLink( (XYZ(node1())-XYZ(node2())).SquareModulus(),
2161 _nodeMove.SquareMagnitude());
2163 bool operator<(const QLink& other) const {
2164 return (node1()->GetID() == other.node1()->GetID() ?
2165 node2()->GetID() < other.node2()->GetID() :
2166 node1()->GetID() < other.node1()->GetID());
2168 // struct PtrComparator {
2169 // bool operator() (const QLink* l1, const QLink* l2 ) const { return *l1 < *l2; }
2172 // ---------------------------------------------------------
2174 * \brief Link in the chain of links; it connects two faces
2178 const QLink* _qlink;
2179 mutable const QFace* _qfaces[2];
2181 TChainLink(const QLink* qlink=0):_qlink(qlink) {
2182 _qfaces[0] = _qfaces[1] = 0;
2184 void SetFace(const QFace* face) const { int iF = _qfaces[0] ? 1 : 0; _qfaces[iF]=face; }
2186 bool IsBoundary() const { return !_qfaces[1]; }
2188 void RemoveFace( const QFace* face ) const
2189 { _qfaces[(face == _qfaces[1])] = 0; if (!_qfaces[0]) std::swap(_qfaces[0],_qfaces[1]); }
2191 const QFace* NextFace( const QFace* f ) const
2192 { return _qfaces[0]==f ? _qfaces[1] : _qfaces[0]; }
2194 const SMDS_MeshNode* NextNode( const SMDS_MeshNode* n ) const
2195 { return n == _qlink->node1() ? _qlink->node2() : _qlink->node1(); }
2197 bool operator<(const TChainLink& other) const { return *_qlink < *other._qlink; }
2199 operator bool() const { return (_qlink); }
2201 const QLink* operator->() const { return _qlink; }
2203 gp_Vec Normal() const;
2205 bool IsStraight() const;
2207 // --------------------------------------------------------------------
2208 typedef list< TChainLink > TChain;
2209 typedef set < TChainLink > TLinkSet;
2210 typedef TLinkSet::const_iterator TLinkInSet;
2212 const int theFirstStep = 5;
2214 enum { ERR_OK, ERR_TRI, ERR_PRISM, ERR_UNKNOWN }; // errors of QFace::GetLinkChain()
2215 // --------------------------------------------------------------------
2217 * \brief Face shared by two volumes and bound by QLinks
2219 struct QFace: public TIDSortedNodeSet
2221 mutable const SMDS_MeshElement* _volumes[2];
2222 mutable vector< const QLink* > _sides;
2223 mutable bool _sideIsAdded[4]; // added in chain of links
2226 mutable const SMDS_MeshElement* _face;
2229 QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face=0 );
2231 void SetVolume(const SMDS_MeshElement* v) const { _volumes[ _volumes[0] ? 1 : 0 ] = v; }
2233 int NbVolumes() const { return !_volumes[0] ? 0 : !_volumes[1] ? 1 : 2; }
2235 void AddSelfToLinks() const {
2236 for ( int i = 0; i < _sides.size(); ++i )
2237 _sides[i]->_faces.push_back( this );
2239 int LinkIndex( const QLink* side ) const {
2240 for (int i=0; i<_sides.size(); ++i ) if ( _sides[i] == side ) return i;
2243 bool GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& err) const;
2245 bool GetLinkChain( TChainLink& link, TChain& chain, SMDS_TypeOfPosition pos, int& err) const
2247 int i = LinkIndex( link._qlink );
2248 if ( i < 0 ) return true;
2249 _sideIsAdded[i] = true;
2250 link.SetFace( this );
2251 // continue from opposite link
2252 return GetLinkChain( (i+2)%_sides.size(), chain, pos, err );
2254 bool IsBoundary() const { return !_volumes[1]; }
2256 bool Contains( const SMDS_MeshNode* node ) const { return count(node); }
2258 bool IsSpoiled(const QLink* bentLink ) const;
2260 TLinkInSet GetBoundaryLink( const TLinkSet& links,
2261 const TChainLink& avoidLink,
2262 TLinkInSet * notBoundaryLink = 0,
2263 const SMDS_MeshNode* nodeToContain = 0,
2264 bool * isAdjacentUsed = 0,
2265 int nbRecursionsLeft = -1) const;
2267 TLinkInSet GetLinkByNode( const TLinkSet& links,
2268 const TChainLink& avoidLink,
2269 const SMDS_MeshNode* nodeToContain) const;
2271 const SMDS_MeshNode* GetNodeInFace() const {
2272 for ( int iL = 0; iL < _sides.size(); ++iL )
2273 if ( _sides[iL]->MediumPos() == SMDS_TOP_FACE ) return _sides[iL]->_mediumNode;
2277 gp_Vec LinkNorm(const int i, SMESH_MesherHelper* theFaceHelper=0) const;
2279 double MoveByBoundary( const TChainLink& theLink,
2280 const gp_Vec& theRefVec,
2281 const TLinkSet& theLinks,
2282 SMESH_MesherHelper* theFaceHelper=0,
2283 const double thePrevLen=0,
2284 const int theStep=theFirstStep,
2285 gp_Vec* theLinkNorm=0,
2286 double theSign=1.0) const;
2289 //================================================================================
2291 * \brief Dump QLink and QFace
2293 ostream& operator << (ostream& out, const QLink& l)
2295 out <<"QLink nodes: "
2296 << l.node1()->GetID() << " - "
2297 << l._mediumNode->GetID() << " - "
2298 << l.node2()->GetID() << endl;
2301 ostream& operator << (ostream& out, const QFace& f)
2303 out <<"QFace nodes: "/*<< &f << " "*/;
2304 for ( TIDSortedNodeSet::const_iterator n = f.begin(); n != f.end(); ++n )
2305 out << (*n)->GetID() << " ";
2306 out << " \tvolumes: "
2307 << (f._volumes[0] ? f._volumes[0]->GetID() : 0) << " "
2308 << (f._volumes[1] ? f._volumes[1]->GetID() : 0);
2309 out << " \tNormal: "<< f._normal.X() <<", "<<f._normal.Y() <<", "<<f._normal.Z() << endl;
2313 //================================================================================
2315 * \brief Construct QFace from QLinks
2317 //================================================================================
2319 QFace::QFace( const vector< const QLink*>& links, const SMDS_MeshElement* face )
2321 _volumes[0] = _volumes[1] = 0;
2323 _sideIsAdded[0]=_sideIsAdded[1]=_sideIsAdded[2]=_sideIsAdded[3]=false;
2324 _normal.SetCoord(0,0,0);
2325 for ( int i = 1; i < _sides.size(); ++i ) {
2326 const QLink *l1 = _sides[i-1], *l2 = _sides[i];
2327 insert( l1->node1() ); insert( l1->node2() );
2329 gp_Vec v1( XYZ( l1->node2()), XYZ( l1->node1()));
2330 gp_Vec v2( XYZ( l2->node1()), XYZ( l2->node2()));
2331 if ( l1->node1() != l2->node1() && l1->node2() != l2->node2() )
2335 double normSqSize = _normal.SquareMagnitude();
2336 if ( normSqSize > numeric_limits<double>::min() )
2337 _normal /= sqrt( normSqSize );
2339 _normal.SetCoord(1e-33,0,0);
2345 //================================================================================
2347 * \brief Make up a chain of links
2348 * \param iSide - link to add first
2349 * \param chain - chain to fill in
2350 * \param pos - postion of medium nodes the links should have
2351 * \param error - out, specifies what is wrong
2352 * \retval bool - false if valid chain can't be built; "valid" means that links
2353 * of the chain belongs to rectangles bounding hexahedrons
2355 //================================================================================
2357 bool QFace::GetLinkChain( int iSide, TChain& chain, SMDS_TypeOfPosition pos, int& error) const
2359 if ( iSide >= _sides.size() ) // wrong argument iSide
2361 if ( _sideIsAdded[ iSide ]) // already in chain
2364 if ( _sides.size() != 4 ) { // triangle - visit all my continous faces
2367 list< const QFace* > faces( 1, this );
2368 while ( !faces.empty() ) {
2369 const QFace* face = faces.front();
2370 for ( int i = 0; i < face->_sides.size(); ++i ) {
2371 if ( !face->_sideIsAdded[i] && face->_sides[i] ) {
2372 face->_sideIsAdded[i] = true;
2373 // find a face side in the chain
2374 TLinkInSet chLink = links.insert( TChainLink(face->_sides[i])).first;
2375 // TChain::iterator chLink = chain.begin();
2376 // for ( ; chLink != chain.end(); ++chLink )
2377 // if ( chLink->_qlink == face->_sides[i] )
2379 // if ( chLink == chain.end() )
2380 // chLink = chain.insert( chain.begin(), TChainLink(face->_sides[i]));
2381 // add a face to a chained link and put a continues face in the queue
2382 chLink->SetFace( face );
2383 if ( face->_sides[i]->MediumPos() == pos )
2384 if ( const QFace* contFace = face->_sides[i]->GetContinuesFace( face ))
2385 if ( contFace->_sides.size() == 3 )
2386 faces.push_back( contFace );
2391 if ( error < ERR_TRI )
2393 chain.insert( chain.end(), links.begin(),links.end() );
2396 _sideIsAdded[iSide] = true; // not to add this link to chain again
2397 const QLink* link = _sides[iSide];
2401 // add link into chain
2402 TChain::iterator chLink = chain.insert( chain.begin(), TChainLink(link));
2403 chLink->SetFace( this );
2406 // propagate from quadrangle to neighbour faces
2407 if ( link->MediumPos() >= pos ) {
2408 int nbLinkFaces = link->_faces.size();
2409 if ( nbLinkFaces == 4 || (/*nbLinkFaces < 4 && */link->OnBoundary())) {
2410 // hexahedral mesh or boundary quadrangles - goto a continous face
2411 if ( const QFace* f = link->GetContinuesFace( this ))
2412 if ( f->_sides.size() == 4 )
2413 return f->GetLinkChain( *chLink, chain, pos, error );
2416 TChainLink chLink(link); // side face of prismatic mesh - visit all faces of iSide
2417 for ( int i = 0; i < nbLinkFaces; ++i )
2418 if ( link->_faces[i] )
2419 link->_faces[i]->GetLinkChain( chLink, chain, pos, error );
2420 if ( error < ERR_PRISM )
2428 //================================================================================
2430 * \brief Return a boundary link of the triangle face
2431 * \param links - set of all links
2432 * \param avoidLink - link not to return
2433 * \param notBoundaryLink - out, neither the returned link nor avoidLink
2434 * \param nodeToContain - node the returned link must contain; if provided, search
2435 * also performed on adjacent faces
2436 * \param isAdjacentUsed - returns true if link is found in adjacent faces
2437 * \param nbRecursionsLeft - to limit recursion
2439 //================================================================================
2441 TLinkInSet QFace::GetBoundaryLink( const TLinkSet& links,
2442 const TChainLink& avoidLink,
2443 TLinkInSet * notBoundaryLink,
2444 const SMDS_MeshNode* nodeToContain,
2445 bool * isAdjacentUsed,
2446 int nbRecursionsLeft) const
2448 TLinkInSet linksEnd = links.end(), boundaryLink = linksEnd;
2450 typedef list< pair< const QFace*, TLinkInSet > > TFaceLinkList;
2451 TFaceLinkList adjacentFaces;
2453 for ( int iL = 0; iL < _sides.size(); ++iL )
2455 if ( avoidLink._qlink == _sides[iL] )
2457 TLinkInSet link = links.find( _sides[iL] );
2458 if ( link == linksEnd ) continue;
2459 if ( (*link)->MediumPos() > SMDS_TOP_FACE )
2460 continue; // We work on faces here, don't go inside a solid
2463 if ( link->IsBoundary() ) {
2464 if ( !nodeToContain ||
2465 (*link)->node1() == nodeToContain ||
2466 (*link)->node2() == nodeToContain )
2468 boundaryLink = link;
2469 if ( !notBoundaryLink ) break;
2472 else if ( notBoundaryLink ) {
2473 *notBoundaryLink = link;
2474 if ( boundaryLink != linksEnd ) break;
2477 if ( boundaryLink == linksEnd && nodeToContain ) // collect adjacent faces
2478 if ( const QFace* adj = link->NextFace( this ))
2479 if ( adj->Contains( nodeToContain ))
2480 adjacentFaces.push_back( make_pair( adj, link ));
2483 if ( isAdjacentUsed ) *isAdjacentUsed = false;
2484 if ( boundaryLink == linksEnd && nodeToContain && nbRecursionsLeft) // check adjacent faces
2486 if ( nbRecursionsLeft < 0 )
2487 nbRecursionsLeft = nodeToContain->NbInverseElements();
2488 TFaceLinkList::iterator adj = adjacentFaces.begin();
2489 for ( ; boundaryLink == linksEnd && adj != adjacentFaces.end(); ++adj )
2490 boundaryLink = adj->first->GetBoundaryLink( links, *(adj->second), 0, nodeToContain,
2491 isAdjacentUsed, nbRecursionsLeft-1);
2492 if ( isAdjacentUsed ) *isAdjacentUsed = true;
2494 return boundaryLink;
2496 //================================================================================
2498 * \brief Return a link ending at the given node but not avoidLink
2500 //================================================================================
2502 TLinkInSet QFace::GetLinkByNode( const TLinkSet& links,
2503 const TChainLink& avoidLink,
2504 const SMDS_MeshNode* nodeToContain) const
2506 for ( int i = 0; i < _sides.size(); ++i )
2507 if ( avoidLink._qlink != _sides[i] &&
2508 (_sides[i]->node1() == nodeToContain || _sides[i]->node2() == nodeToContain ))
2509 return links.find( _sides[ i ]);
2513 //================================================================================
2515 * \brief Return normal to the i-th side pointing outside the face
2517 //================================================================================
2519 gp_Vec QFace::LinkNorm(const int i, SMESH_MesherHelper* /*uvHelper*/) const
2521 gp_Vec norm, vecOut;
2522 // if ( uvHelper ) {
2523 // TopoDS_Face face = TopoDS::Face( uvHelper->GetSubShape());
2524 // const SMDS_MeshNode* inFaceNode = uvHelper->GetNodeUVneedInFaceNode() ? GetNodeInFace() : 0;
2525 // gp_XY uv1 = uvHelper->GetNodeUV( face, _sides[i]->node1(), inFaceNode );
2526 // gp_XY uv2 = uvHelper->GetNodeUV( face, _sides[i]->node2(), inFaceNode );
2527 // norm.SetCoord( uv1.Y() - uv2.Y(), uv2.X() - uv1.X(), 0 );
2529 // const QLink* otherLink = _sides[(i + 1) % _sides.size()];
2530 // const SMDS_MeshNode* otherNode =
2531 // otherLink->node1() == _sides[i]->node1() ? otherLink->node2() : otherLink->node1();
2532 // gp_XY pIn = uvHelper->GetNodeUV( face, otherNode, inFaceNode );
2533 // vecOut.SetCoord( uv1.X() - pIn.X(), uv1.Y() - pIn.Y(), 0 );
2536 norm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2537 gp_XYZ pIn = ( XYZ( _sides[0]->node1() ) +
2538 XYZ( _sides[0]->node2() ) +
2539 XYZ( _sides[1]->node1() )) / 3.;
2540 vecOut.SetXYZ( _sides[i]->MiddlePnt() - pIn );
2542 if ( norm * vecOut < 0 )
2544 double mag2 = norm.SquareMagnitude();
2545 if ( mag2 > numeric_limits<double>::min() )
2546 norm /= sqrt( mag2 );
2549 //================================================================================
2551 * \brief Move medium node of theLink according to its distance from boundary
2552 * \param theLink - link to fix
2553 * \param theRefVec - movement of boundary
2554 * \param theLinks - all adjacent links of continous triangles
2555 * \param theFaceHelper - helper is not used so far
2556 * \param thePrevLen - distance from the boundary
2557 * \param theStep - number of steps till movement propagation limit
2558 * \param theLinkNorm - out normal to theLink
2559 * \param theSign - 1 or -1 depending on movement of boundary
2560 * \retval double - distance from boundary to propagation limit or other boundary
2562 //================================================================================
2564 double QFace::MoveByBoundary( const TChainLink& theLink,
2565 const gp_Vec& theRefVec,
2566 const TLinkSet& theLinks,
2567 SMESH_MesherHelper* theFaceHelper,
2568 const double thePrevLen,
2570 gp_Vec* theLinkNorm,
2571 double theSign) const
2574 return thePrevLen; // propagation limit reached
2576 int iL; // index of theLink
2577 for ( iL = 0; iL < _sides.size(); ++iL )
2578 if ( theLink._qlink == _sides[ iL ])
2581 MSG(string(theStep,'.')<<" Ref( "<<theRefVec.X()<<","<<theRefVec.Y()<<","<<theRefVec.Z()<<" )"
2582 <<" thePrevLen " << thePrevLen);
2583 MSG(string(theStep,'.')<<" "<<*theLink._qlink);
2585 gp_Vec linkNorm = -LinkNorm( iL/*, theFaceHelper*/ ); // normal to theLink
2586 double refProj = theRefVec * linkNorm; // project movement vector to normal of theLink
2587 if ( theStep == theFirstStep )
2588 theSign = refProj < 0. ? -1. : 1.;
2589 else if ( theSign * refProj < 0.4 * theRefVec.Magnitude())
2590 return thePrevLen; // to propagate movement forward only, not in side dir or backward
2592 int iL1 = (iL + 1) % 3, iL2 = (iL + 2) % 3; // indices of the two other links of triangle
2593 TLinkInSet link1 = theLinks.find( _sides[iL1] );
2594 TLinkInSet link2 = theLinks.find( _sides[iL2] );
2595 if ( link1 == theLinks.end() || link2 == theLinks.end() )
2597 const QFace* f1 = link1->NextFace( this ); // adjacent faces
2598 const QFace* f2 = link2->NextFace( this );
2600 // propagate to adjacent faces till limit step or boundary
2601 double len1 = thePrevLen + (theLink->MiddlePnt() - _sides[iL1]->MiddlePnt()).Modulus();
2602 double len2 = thePrevLen + (theLink->MiddlePnt() - _sides[iL2]->MiddlePnt()).Modulus();
2603 gp_Vec linkDir1(0,0,0); // initialize to avoid valgrind error ("Conditional jump...")
2604 gp_Vec linkDir2(0,0,0);
2607 if ( f1 && theLink->MediumPos() <= (*link1)->MediumPos() )
2608 len1 = f1->MoveByBoundary
2609 ( *link1, theRefVec, theLinks, theFaceHelper, len1, theStep-1, &linkDir1, theSign);
2611 linkDir1 = LinkNorm( iL1/*, theFaceHelper*/ );
2613 MSG( " --------------- EXCEPTION");
2618 if ( f2 && theLink->MediumPos() <= (*link2)->MediumPos() )
2619 len2 = f2->MoveByBoundary
2620 ( *link2, theRefVec, theLinks, theFaceHelper, len2, theStep-1, &linkDir2, theSign);
2622 linkDir2 = LinkNorm( iL2/*, theFaceHelper*/ );
2624 MSG( " --------------- EXCEPTION");
2629 if ( theStep != theFirstStep )
2631 // choose chain length by direction of propagation most codirected with theRefVec
2632 bool choose1 = ( theRefVec * linkDir1 * theSign > theRefVec * linkDir2 * theSign );
2633 fullLen = choose1 ? len1 : len2;
2634 double r = thePrevLen / fullLen;
2636 gp_Vec move = linkNorm * refProj * ( 1 - r );
2637 theLink->Move( move, true );
2639 MSG(string(theStep,'.')<<" Move "<< theLink->_mediumNode->GetID()<<
2640 " by " << refProj * ( 1 - r ) << " following " <<
2641 (choose1 ? *link1->_qlink : *link2->_qlink));
2643 if ( theLinkNorm ) *theLinkNorm = linkNorm;
2648 //================================================================================
2650 * \brief Checks if the face is distorted due to bentLink
2652 //================================================================================
2654 bool QFace::IsSpoiled(const QLink* bentLink ) const
2656 // code is valid for convex faces only
2658 for ( TIDSortedNodeSet::const_iterator n = begin(); n!=end(); ++n)
2659 gc += XYZ( *n ) / size();
2660 for (unsigned i = 0; i < _sides.size(); ++i )
2662 if ( _sides[i] == bentLink ) continue;
2663 gp_Vec linkNorm = _normal ^ gp_Vec( XYZ(_sides[i]->node1()), XYZ(_sides[i]->node2()));
2664 gp_Vec vecOut( gc, _sides[i]->MiddlePnt() );
2665 if ( linkNorm * vecOut < 0 )
2667 double mag2 = linkNorm.SquareMagnitude();
2668 if ( mag2 > numeric_limits<double>::min() )
2669 linkNorm /= sqrt( mag2 );
2670 gp_Vec vecBent ( _sides[i]->MiddlePnt(), bentLink->MediumPnt());
2671 gp_Vec vecStraight( _sides[i]->MiddlePnt(), bentLink->MiddlePnt());
2672 if ( vecBent * linkNorm > -0.1*vecStraight.Magnitude() )
2679 //================================================================================
2681 * \brief Find pairs of continues faces
2683 //================================================================================
2685 void QLink::SetContinuesFaces() const
2687 // x0 x - QLink, [-|] - QFace, v - volume
2689 // | Between _faces of link x2 two vertical faces are continues
2690 // x1----x2-----x3 and two horizontal faces are continues. We set vertical faces
2691 // | to _faces[0] and _faces[1] and horizontal faces to
2692 // v2 | v3 _faces[2] and _faces[3] (or vise versa).
2695 if ( _faces.empty() )
2697 int iFaceCont = -1, nbBoundary = 0, iBoundary[2]={-1,-1};
2698 if ( _faces[0]->IsBoundary() )
2699 iBoundary[ nbBoundary++ ] = 0;
2700 for ( int iF = 1; iFaceCont < 0 && iF < _faces.size(); ++iF )
2702 // look for a face bounding none of volumes bound by _faces[0]
2703 bool sameVol = false;
2704 int nbVol = _faces[iF]->NbVolumes();
2705 for ( int iV = 0; !sameVol && iV < nbVol; ++iV )
2706 sameVol = ( _faces[iF]->_volumes[iV] == _faces[0]->_volumes[0] ||
2707 _faces[iF]->_volumes[iV] == _faces[0]->_volumes[1]);
2710 if ( _faces[iF]->IsBoundary() )
2711 iBoundary[ nbBoundary++ ] = iF;
2713 // Set continues faces: arrange _faces to have
2714 // _faces[0] continues to _faces[1]
2715 // _faces[2] continues to _faces[3]
2716 if ( nbBoundary == 2 ) // bnd faces are continues
2718 if (( iBoundary[0] < 2 ) != ( iBoundary[1] < 2 ))
2720 int iNear0 = iBoundary[0] < 2 ? 1-iBoundary[0] : 5-iBoundary[0];
2721 std::swap( _faces[ iBoundary[1] ], _faces[iNear0] );
2724 else if ( iFaceCont > 0 ) // continues faces found
2726 if ( iFaceCont != 1 )
2727 std::swap( _faces[1], _faces[iFaceCont] );
2729 else if ( _faces.size() > 1 ) // not found, set NULL by the first face
2731 _faces.insert( ++_faces.begin(), 0 );
2734 //================================================================================
2736 * \brief Return a face continues to the given one
2738 //================================================================================
2740 const QFace* QLink::GetContinuesFace( const QFace* face ) const
2742 for ( int i = 0; i < _faces.size(); ++i ) {
2743 if ( _faces[i] == face ) {
2744 int iF = i < 2 ? 1-i : 5-i;
2745 return iF < _faces.size() ? _faces[iF] : 0;
2750 //================================================================================
2752 * \brief True if link is on mesh boundary
2754 //================================================================================
2756 bool QLink::OnBoundary() const
2758 for ( int i = 0; i < _faces.size(); ++i )
2759 if (_faces[i] && _faces[i]->IsBoundary()) return true;
2762 //================================================================================
2764 * \brief Return normal of link of the chain
2766 //================================================================================
2768 gp_Vec TChainLink::Normal() const {
2770 if (_qfaces[0]) norm = _qfaces[0]->_normal;
2771 if (_qfaces[1]) norm += _qfaces[1]->_normal;
2774 //================================================================================
2776 * \brief Test link curvature taking into account size of faces
2778 //================================================================================
2780 bool TChainLink::IsStraight() const
2782 bool isStraight = _qlink->IsStraight();
2783 if ( isStraight && _qfaces[0] && !_qfaces[1] )
2785 int i = _qfaces[0]->LinkIndex( _qlink );
2786 int iOpp = ( i + 2 ) % _qfaces[0]->_sides.size();
2787 gp_XYZ mid1 = _qlink->MiddlePnt();
2788 gp_XYZ mid2 = _qfaces[0]->_sides[ iOpp ]->MiddlePnt();
2789 double faceSize2 = (mid1-mid2).SquareModulus();
2790 isStraight = _qlink->_nodeMove.SquareMagnitude() < 1/10./10. * faceSize2;
2795 //================================================================================
2797 * \brief Move medium nodes of vertical links of pentahedrons adjacent by side faces
2799 //================================================================================
2801 void fixPrism( TChain& allLinks )
2803 // separate boundary links from internal ones
2804 typedef set<const QLink*/*, QLink::PtrComparator*/> QLinkSet;
2805 QLinkSet interLinks, bndLinks1, bndLink2;
2807 bool isCurved = false;
2808 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2809 if ( (*lnk)->OnBoundary() )
2810 bndLinks1.insert( lnk->_qlink );
2812 interLinks.insert( lnk->_qlink );
2813 isCurved = isCurved || !lnk->IsStraight();
2816 return; // no need to move
2818 QLinkSet *curBndLinks = &bndLinks1, *newBndLinks = &bndLink2;
2820 while ( !interLinks.empty() && !curBndLinks->empty() )
2822 // propagate movement from boundary links to connected internal links
2823 QLinkSet::iterator bnd = curBndLinks->begin(), bndEnd = curBndLinks->end();
2824 for ( ; bnd != bndEnd; ++bnd )
2826 const QLink* bndLink = *bnd;
2827 for ( int i = 0; i < bndLink->_faces.size(); ++i ) // loop on faces of bndLink
2829 const QFace* face = bndLink->_faces[i]; // quadrange lateral face of a prism
2830 if ( !face ) continue;
2831 // find and move internal link opposite to bndLink within the face
2832 int interInd = ( face->LinkIndex( bndLink ) + 2 ) % face->_sides.size();
2833 const QLink* interLink = face->_sides[ interInd ];
2834 QLinkSet::iterator pInterLink = interLinks.find( interLink );
2835 if ( pInterLink == interLinks.end() ) continue; // not internal link
2836 interLink->Move( bndLink->_nodeMove );
2837 // treated internal links become new boundary ones
2838 interLinks. erase( pInterLink );
2839 newBndLinks->insert( interLink );
2842 curBndLinks->clear();
2843 std::swap( curBndLinks, newBndLinks );
2847 //================================================================================
2849 * \brief Fix links of continues triangles near curved boundary
2851 //================================================================================
2853 void fixTriaNearBoundary( TChain & allLinks, SMESH_MesherHelper& /*helper*/)
2855 if ( allLinks.empty() ) return;
2857 TLinkSet linkSet( allLinks.begin(), allLinks.end());
2858 TLinkInSet linkIt = linkSet.begin(), linksEnd = linkSet.end();
2860 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt)
2862 if ( linkIt->IsBoundary() && !linkIt->IsStraight() && linkIt->_qfaces[0])
2864 // move iff a boundary link is bent towards inside of a face (issue 0021084)
2865 const QFace* face = linkIt->_qfaces[0];
2866 gp_XYZ pIn = ( face->_sides[0]->MiddlePnt() +
2867 face->_sides[1]->MiddlePnt() +
2868 face->_sides[2]->MiddlePnt() ) / 3.;
2869 gp_XYZ insideDir( pIn - (*linkIt)->MiddlePnt());
2870 bool linkBentInside = ((*linkIt)->_nodeMove.Dot( insideDir ) > 0 );
2871 //if ( face->IsSpoiled( linkIt->_qlink ))
2872 if ( linkBentInside )
2873 face->MoveByBoundary( *linkIt, (*linkIt)->_nodeMove, linkSet );
2878 //================================================================================
2880 * \brief Detect rectangular structure of links and build chains from them
2882 //================================================================================
2884 enum TSplitTriaResult {
2885 _OK, _NO_CORNERS, _FEW_ROWS, _MANY_ROWS, _NO_SIDELINK, _BAD_MIDQUAD, _NOT_RECT,
2886 _NO_MIDQUAD, _NO_UPTRIA, _BAD_SET_SIZE, _BAD_CORNER, _BAD_START, _NO_BOTLINK, _TWISTED_CHAIN };
2888 TSplitTriaResult splitTrianglesIntoChains( TChain & allLinks,
2889 vector< TChain> & resultChains,
2890 SMDS_TypeOfPosition pos )
2892 // put links in the set and evalute number of result chains by number of boundary links
2895 for ( TChain::iterator lnk = allLinks.begin(); lnk != allLinks.end(); ++lnk ) {
2896 linkSet.insert( *lnk );
2897 nbBndLinks += lnk->IsBoundary();
2899 resultChains.clear();
2900 resultChains.reserve( nbBndLinks / 2 );
2902 TLinkInSet linkIt, linksEnd = linkSet.end();
2904 // find a boundary link with corner node; corner node has position pos-2
2905 // i.e. SMDS_TOP_VERTEX for links on faces and SMDS_TOP_EDGE for
2907 SMDS_TypeOfPosition cornerPos = SMDS_TypeOfPosition(pos-2);
2908 const SMDS_MeshNode* corner = 0;
2909 for ( linkIt = linkSet.begin(); linkIt != linksEnd; ++linkIt )
2910 if ( linkIt->IsBoundary() && (corner = (*linkIt)->EndPosNode(cornerPos)))
2915 TLinkInSet startLink = linkIt;
2916 const SMDS_MeshNode* startCorner = corner;
2917 vector< TChain* > rowChains;
2920 while ( startLink != linksEnd) // loop on columns
2922 // We suppose we have a rectangular structure like shown here. We have found a
2923 // corner of the rectangle (startCorner) and a boundary link sharing
2924 // |/ |/ | the startCorner (startLink). We are going to loop on rows of the
2925 // --o---o---o structure making several chains at once. One chain (columnChain)
2926 // |\ | /| starts at startLink and continues upward (we look at the structure
2927 // \ | \ | / | from such point that startLink is on the bottom of the structure).
2928 // \| \|/ | While going upward we also fill horizontal chains (rowChains) we
2929 // --o---o---o encounter.
2931 // / | \ | \ | startCorner
2936 if ( resultChains.size() == nbBndLinks / 2 )
2938 resultChains.push_back( TChain() );
2939 TChain& columnChain = resultChains.back();
2941 TLinkInSet botLink = startLink; // current horizontal link to go up from
2942 corner = startCorner; // current corner the botLink ends at
2944 while ( botLink != linksEnd ) // loop on rows
2946 // add botLink to the columnChain
2947 columnChain.push_back( *botLink );
2949 const QFace* botTria = botLink->_qfaces[0]; // bottom triangle bound by botLink
2951 { // the column ends
2952 if ( botLink == startLink )
2953 return _TWISTED_CHAIN; // issue 0020951
2954 linkSet.erase( botLink );
2955 if ( iRow != rowChains.size() )
2956 return _FEW_ROWS; // different nb of rows in columns
2959 // find the link dividing the quadrangle (midQuadLink) and vertical boundary
2960 // link ending at <corner> (sideLink); there are two cases:
2961 // 1) midQuadLink does not end at <corner>, then we easily find it by botTria,
2962 // since midQuadLink is not at boundary while sideLink is.
2963 // 2) midQuadLink ends at <corner>
2965 TLinkInSet midQuadLink = linksEnd;
2966 TLinkInSet sideLink = botTria->GetBoundaryLink( linkSet, *botLink, &midQuadLink,
2968 if ( isCase2 ) { // find midQuadLink among links of botTria
2969 midQuadLink = botTria->GetLinkByNode( linkSet, *botLink, corner );
2970 if ( midQuadLink->IsBoundary() )
2971 return _BAD_MIDQUAD;
2973 if ( sideLink == linksEnd || midQuadLink == linksEnd || sideLink == midQuadLink )
2974 return sideLink == linksEnd ? _NO_SIDELINK : _NO_MIDQUAD;
2977 columnChain.push_back( *midQuadLink );
2978 if ( iRow >= rowChains.size() ) {
2980 return _MANY_ROWS; // different nb of rows in columns
2981 if ( resultChains.size() == nbBndLinks / 2 )
2983 resultChains.push_back( TChain() );
2984 rowChains.push_back( & resultChains.back() );
2986 rowChains[iRow]->push_back( *sideLink );
2987 rowChains[iRow]->push_back( *midQuadLink );
2989 const QFace* upTria = midQuadLink->NextFace( botTria ); // upper tria of the rectangle
2993 // prepare startCorner and startLink for the next column
2994 startCorner = startLink->NextNode( startCorner );
2996 startLink = botTria->GetBoundaryLink( linkSet, *botLink, 0, startCorner );
2998 startLink = upTria->GetBoundaryLink( linkSet, *midQuadLink, 0, startCorner );
2999 // check if no more columns remains
3000 if ( startLink != linksEnd ) {
3001 const SMDS_MeshNode* botNode = startLink->NextNode( startCorner );
3002 if ( (isCase2 ? botTria : upTria)->Contains( botNode ))
3003 startLink = linksEnd; // startLink bounds upTria or botTria
3004 else if ( startLink == botLink || startLink == midQuadLink || startLink == sideLink )
3008 // find bottom link and corner for the next row
3009 corner = sideLink->NextNode( corner );
3010 // next bottom link ends at the new corner
3011 linkSet.erase( botLink );
3012 botLink = upTria->GetLinkByNode( linkSet, (isCase2 ? *sideLink : *midQuadLink), corner );
3013 if ( botLink == linksEnd || botLink == midQuadLink || botLink == sideLink)
3015 if ( midQuadLink == startLink || sideLink == startLink )
3016 return _TWISTED_CHAIN; // issue 0020951
3017 linkSet.erase( midQuadLink );
3018 linkSet.erase( sideLink );
3020 // make faces neighboring the found ones be boundary
3021 if ( startLink != linksEnd ) {
3022 const QFace* tria = isCase2 ? botTria : upTria;
3023 for ( int iL = 0; iL < 3; ++iL ) {
3024 linkIt = linkSet.find( tria->_sides[iL] );
3025 if ( linkIt != linksEnd )
3026 linkIt->RemoveFace( tria );
3029 if ( botLink->_qfaces[0] == upTria || botLink->_qfaces[1] == upTria )
3030 botLink->RemoveFace( upTria ); // make next botTria first in vector
3037 // In the linkSet, there must remain the last links of rowChains; add them
3038 if ( linkSet.size() != rowChains.size() )
3039 return _BAD_SET_SIZE;
3040 for ( int iRow = 0; iRow < rowChains.size(); ++iRow ) {
3041 // find the link (startLink) ending at startCorner
3043 for ( startLink = linkSet.begin(); startLink != linksEnd; ++startLink ) {
3044 if ( (*startLink)->node1() == startCorner ) {
3045 corner = (*startLink)->node2(); break;
3047 else if ( (*startLink)->node2() == startCorner) {
3048 corner = (*startLink)->node1(); break;
3051 if ( startLink == linksEnd )
3053 rowChains[ iRow ]->push_back( *startLink );
3054 linkSet.erase( startLink );
3055 startCorner = corner;
3062 //=======================================================================
3064 * \brief Move medium nodes of faces and volumes to fix distorted elements
3065 * \param volumeOnly - to fix nodes on faces or not, if the shape is solid
3067 * Issue 0020307: EDF 992 SMESH : Linea/Quadratic with Medium Node on Geometry
3069 //=======================================================================
3071 void SMESH_MesherHelper::FixQuadraticElements(bool volumeOnly)
3073 // setenv NO_FixQuadraticElements to know if FixQuadraticElements() is guilty of bad conversion
3074 if ( getenv("NO_FixQuadraticElements") )
3077 // 0. Apply algorithm to SOLIDs or FACEs
3078 // ----------------------------------------------
3079 if ( myShape.IsNull() ) {
3080 if ( !myMesh->HasShapeToMesh() ) return;
3081 SetSubShape( myMesh->GetShapeToMesh() );
3085 TopTools_IndexedMapOfShape solids;
3086 TopExp::MapShapes(myShape,TopAbs_SOLID,solids);
3087 nbSolids = solids.Extent();
3089 TopTools_MapOfShape faces; // faces not in solid or in not meshed solid
3090 for ( TopExp_Explorer f(myShape,TopAbs_FACE,TopAbs_SOLID); f.More(); f.Next() ) {
3091 faces.Add( f.Current() ); // not in solid
3093 for ( TopExp_Explorer s(myShape,TopAbs_SOLID); s.More(); s.Next() ) {
3094 if ( myMesh->GetSubMesh( s.Current() )->IsEmpty() ) { // get faces of solid
3095 for ( TopExp_Explorer f( s.Current(), TopAbs_FACE); f.More(); f.Next() )
3096 faces.Add( f.Current() ); // in not meshed solid
3098 else { // fix nodes in the solid and its faces
3100 MSG("FIX SOLID " << nbSolids-- << " #" << GetMeshDS()->ShapeToIndex(s.Current()));
3102 SMESH_MesherHelper h(*myMesh);
3103 h.SetSubShape( s.Current() );
3104 h.FixQuadraticElements(false);
3107 // fix nodes on geom faces
3109 int nbfaces = faces.Extent(); /*avoid "unused varianbles": */ nbfaces++, nbfaces--;
3111 for ( TopTools_MapIteratorOfMapOfShape fIt( faces ); fIt.More(); fIt.Next() ) {
3112 MSG("FIX FACE " << nbfaces-- << " #" << GetMeshDS()->ShapeToIndex(fIt.Key()));
3113 SMESH_MesherHelper h(*myMesh);
3114 h.SetSubShape( fIt.Key() );
3115 h.FixQuadraticElements(true);
3116 h.ToFixNodeParameters(true);
3118 //perf_print_all_meters(1);
3122 // 1. Find out type of elements and get iterator on them
3123 // ---------------------------------------------------
3125 SMDS_ElemIteratorPtr elemIt;
3126 SMDSAbs_ElementType elemType = SMDSAbs_All;
3128 SMESH_subMesh* submesh = myMesh->GetSubMeshContaining( myShapeID );
3131 if ( SMESHDS_SubMesh* smDS = submesh->GetSubMeshDS() ) {
3132 elemIt = smDS->GetElements();
3133 if ( elemIt->more() ) {
3134 elemType = elemIt->next()->GetType();
3135 elemIt = smDS->GetElements();
3138 if ( !elemIt || !elemIt->more() || elemType < SMDSAbs_Face )
3141 // 2. Fill in auxiliary data structures
3142 // ----------------------------------
3146 set< QLink >::iterator pLink;
3147 set< QFace >::iterator pFace;
3149 bool isCurved = false;
3150 //bool hasRectFaces = false;
3151 //set<int> nbElemNodeSet;
3152 SMDS_VolumeTool volTool;
3154 TIDSortedNodeSet apexOfPyramid;
3155 const int apexIndex = 4;
3157 if ( elemType == SMDSAbs_Volume )
3159 while ( elemIt->more() ) // loop on volumes
3161 const SMDS_MeshElement* vol = elemIt->next();
3162 if ( !vol->IsQuadratic() || !volTool.Set( vol ))
3164 double volMinSize2 = -1.;
3165 for ( int iF = 0; iF < volTool.NbFaces(); ++iF ) // loop on faces of volume
3167 int nbN = volTool.NbFaceNodes( iF );
3168 //nbElemNodeSet.insert( nbN );
3169 const SMDS_MeshNode** faceNodes = volTool.GetFaceNodes( iF );
3170 vector< const QLink* > faceLinks( nbN/2 );
3171 for ( int iN = 0; iN < nbN; iN += 2 ) // loop on links of a face
3174 QLink link( faceNodes[iN], faceNodes[iN+2], faceNodes[iN+1] );
3175 pLink = links.insert( link ).first;
3176 faceLinks[ iN/2 ] = & *pLink;
3178 if ( link.MediumPos() == SMDS_TOP_3DSPACE )
3180 if ( !link.IsStraight() )
3181 return; // already fixed
3183 else if ( !isCurved )
3185 if ( volMinSize2 < 0 ) volMinSize2 = volTool.MinLinearSize2();
3186 isCurved = !isStraightLink( volMinSize2, link._nodeMove.SquareMagnitude() );
3190 pFace = faces.insert( QFace( faceLinks )).first;
3191 if ( pFace->NbVolumes() == 0 )
3192 pFace->AddSelfToLinks();
3193 pFace->SetVolume( vol );
3194 // hasRectFaces = hasRectFaces ||
3195 // ( volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_HEXA ||
3196 // volTool.GetVolumeType() == SMDS_VolumeTool::QUAD_PENTA );
3199 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],faceNodes[4]);
3201 pFace->_face = GetMeshDS()->FindFace(faceNodes[0],faceNodes[2],
3202 faceNodes[4],faceNodes[6] );
3205 // collect pyramid apexes for further correction
3206 if ( vol->NbCornerNodes() == 5 )
3207 apexOfPyramid.insert( vol->GetNode( apexIndex ));
3209 set< QLink >::iterator pLink = links.begin();
3210 for ( ; pLink != links.end(); ++pLink )
3211 pLink->SetContinuesFaces();
3215 while ( elemIt->more() ) // loop on faces
3217 const SMDS_MeshElement* face = elemIt->next();
3218 if ( !face->IsQuadratic() )
3220 //nbElemNodeSet.insert( face->NbNodes() );
3221 int nbN = face->NbNodes()/2;
3222 vector< const QLink* > faceLinks( nbN );
3223 for ( int iN = 0; iN < nbN; ++iN ) // loop on links of a face
3226 QLink link( face->GetNode(iN), face->GetNode((iN+1)%nbN), face->GetNode(iN+nbN) );
3227 pLink = links.insert( link ).first;
3228 faceLinks[ iN ] = & *pLink;
3230 isCurved = !link.IsStraight();
3233 pFace = faces.insert( QFace( faceLinks )).first;
3234 pFace->AddSelfToLinks();
3235 //hasRectFaces = ( hasRectFaces || nbN == 4 );
3239 return; // no curved edges of faces
3241 // 3. Compute displacement of medium nodes
3242 // ---------------------------------------
3244 // two loops on QFaces: the first is to treat boundary links, the second is for internal ones
3245 TopLoc_Location loc;
3246 // not treat boundary of volumic submesh
3247 int isInside = ( elemType == SMDSAbs_Volume && volumeOnly ) ? 1 : 0;
3248 for ( ; isInside < 2; ++isInside ) {
3249 MSG( "--------------- LOOP (inside=" << isInside << ") ------------------");
3250 SMDS_TypeOfPosition pos = isInside ? SMDS_TOP_3DSPACE : SMDS_TOP_FACE;
3251 SMDS_TypeOfPosition bndPos = isInside ? SMDS_TOP_FACE : SMDS_TOP_EDGE;
3253 for ( pFace = faces.begin(); pFace != faces.end(); ++pFace ) {
3254 if ( bool(isInside) == pFace->IsBoundary() )
3256 for ( int dir = 0; dir < 2; ++dir ) // 2 directions of propagation from the quadrangle
3259 // make chain of links connected via continues faces
3262 if ( !pFace->GetLinkChain( dir, rawChain, pos, error) && error ==ERR_UNKNOWN ) continue;
3264 if ( !pFace->GetLinkChain( dir+2, rawChain, pos, error ) && error ==ERR_UNKNOWN ) continue;
3266 vector< TChain > chains;
3267 if ( error == ERR_OK ) { // chain contains continues rectangles
3269 chains[0].splice( chains[0].begin(), rawChain );
3271 else if ( error == ERR_TRI ) { // chain contains continues triangles
3272 TSplitTriaResult res = splitTrianglesIntoChains( rawChain, chains, pos );
3273 if ( res != _OK ) { // not quadrangles split into triangles
3274 fixTriaNearBoundary( rawChain, *this );
3278 else if ( error == ERR_PRISM ) { // quadrangle side faces of prisms
3279 fixPrism( rawChain );
3285 for ( int iC = 0; iC < chains.size(); ++iC )
3287 TChain& chain = chains[iC];
3288 if ( chain.empty() ) continue;
3289 if ( chain.front().IsStraight() && chain.back().IsStraight() ) {
3290 MSG("3D straight - ignore");
3293 if ( chain.front()->MediumPos() > bndPos ||
3294 chain.back() ->MediumPos() > bndPos ) {
3295 MSG("Internal chain - ignore");
3298 // mesure chain length and compute link position along the chain
3299 double chainLen = 0;
3300 vector< double > linkPos;
3301 MSGBEG( "Link medium nodes: ");
3302 TChain::iterator link0 = chain.begin(), link1 = chain.begin(), link2;
3303 for ( ++link1; link1 != chain.end(); ++link1, ++link0 ) {
3304 MSGBEG( (*link0)->_mediumNode->GetID() << "-" <<(*link1)->_mediumNode->GetID()<<" ");
3305 double len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3306 while ( len < numeric_limits<double>::min() ) { // remove degenerated link
3307 link1 = chain.erase( link1 );
3308 if ( link1 == chain.end() )
3310 len = ((*link0)->MiddlePnt() - (*link1)->MiddlePnt()).Modulus();
3313 linkPos.push_back( chainLen );
3316 if ( linkPos.size() < 2 )
3319 gp_Vec move0 = chain.front()->_nodeMove;
3320 gp_Vec move1 = chain.back ()->_nodeMove;
3323 bool checkUV = true;
3326 // compute node displacement of end links of chain in parametric space of face
3327 TChainLink& linkOnFace = *(++chain.begin());
3328 const SMDS_MeshNode* nodeOnFace = linkOnFace->_mediumNode;
3329 TopoDS_Shape f = GetSubShapeByNode( nodeOnFace, GetMeshDS() );
3330 if ( !f.IsNull() && f.ShapeType() == TopAbs_FACE )
3332 face = TopoDS::Face( f );
3333 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
3335 for ( int is1 = 0; is1 < 2; ++is1 ) // move0 or move1
3337 TChainLink& link = is1 ? chain.back() : chain.front();
3338 gp_XY uvm = GetNodeUV( face, link->_mediumNode, nodeOnFace, &checkUV);
3339 gp_XY uv1 = GetNodeUV( face, link->node1(), nodeOnFace, &checkUV);
3340 gp_XY uv2 = GetNodeUV( face, link->node2(), nodeOnFace, &checkUV);
3341 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3342 // uvMove = uvm - uv12
3343 gp_XY uvMove = applyIn2D(surf, uvm, uv12, gp_XY_Subtracted, /*inPeriod=*/false);
3344 ( is1 ? move1 : move0 ).SetCoord( uvMove.X(), uvMove.Y(), 0 );
3345 if ( !is1 ) // correct nodeOnFace for move1 (issue 0020919)
3346 nodeOnFace = (*(++chain.rbegin()))->_mediumNode;
3347 isStraight[is1] = isStraightLink( (uv2-uv1).SquareModulus(),
3348 10 * uvMove.SquareModulus());
3350 if ( isStraight[0] && isStraight[1] ) {
3351 MSG("2D straight - ignore");
3352 continue; // straight - no need to move nodes of internal links
3355 // check if a chain is already fixed
3356 gp_XY uvm = GetNodeUV( face, linkOnFace->_mediumNode, 0, &checkUV);
3357 gp_XY uv1 = GetNodeUV( face, linkOnFace->node1(), nodeOnFace, &checkUV);
3358 gp_XY uv2 = GetNodeUV( face, linkOnFace->node2(), nodeOnFace, &checkUV);
3359 gp_XY uv12 = GetMiddleUV( surf, uv1, uv2);
3360 if (( uvm - uv12 ).SquareModulus() > 1e-10 )
3362 MSG("Already fixed - ignore");
3368 if ( isInside || face.IsNull() )
3370 // compute node displacement of end links in their local coord systems
3372 TChainLink& ln0 = chain.front(), ln1 = *(++chain.begin());
3373 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln0.Normal(),
3374 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
3375 move0.Transform(trsf);
3378 TChainLink& ln0 = *(++chain.rbegin()), ln1 = chain.back();
3379 trsf.SetTransformation( gp_Ax3( gp::Origin(), ln1.Normal(),
3380 gp_Vec( ln0->MiddlePnt(), ln1->MiddlePnt() )));
3381 move1.Transform(trsf);
3384 // compute displacement of medium nodes
3385 link2 = chain.begin();
3388 for ( int i = 0; link2 != chain.end(); ++link0, ++link1, ++link2, ++i )
3390 double r = linkPos[i] / chainLen;
3391 // displacement in local coord system
3392 gp_Vec move = (1. - r) * move0 + r * move1;
3393 if ( isInside || face.IsNull()) {
3394 // transform to global
3395 gp_Vec x01( (*link0)->MiddlePnt(), (*link1)->MiddlePnt() );
3396 gp_Vec x12( (*link1)->MiddlePnt(), (*link2)->MiddlePnt() );
3397 gp_Vec x = x01.Normalized() + x12.Normalized();
3398 trsf.SetTransformation( gp_Ax3( gp::Origin(), link1->Normal(), x), gp_Ax3() );
3399 move.Transform(trsf);
3402 // compute 3D displacement by 2D one
3403 Handle(Geom_Surface) s = BRep_Tool::Surface(face,loc);
3404 gp_XY oldUV = GetNodeUV( face, (*link1)->_mediumNode, 0, &checkUV);
3405 gp_XY newUV = applyIn2D( s, oldUV, gp_XY( move.X(),move.Y()), gp_XY_Added);
3406 gp_Pnt newPnt = s->Value( newUV.X(), newUV.Y());
3407 move = gp_Vec( XYZ((*link1)->_mediumNode), newPnt.Transformed(loc) );
3409 if ( (XYZ((*link1)->node1()) - XYZ((*link1)->node2())).SquareModulus() <
3410 move.SquareMagnitude())
3412 gp_XY uv0 = GetNodeUV( face, (*link0)->_mediumNode, 0, &checkUV);
3413 gp_XY uv2 = GetNodeUV( face, (*link2)->_mediumNode, 0, &checkUV);
3414 MSG( "TOO LONG MOVE \t" <<
3415 "uv0: "<<uv0.X()<<", "<<uv0.Y()<<" \t" <<
3416 "uv2: "<<uv2.X()<<", "<<uv2.Y()<<" \t" <<
3417 "uvOld: "<<oldUV.X()<<", "<<oldUV.Y()<<" \t" <<
3418 "newUV: "<<newUV.X()<<", "<<newUV.Y()<<" \t");
3422 (*link1)->Move( move );
3423 MSG( "Move " << (*link1)->_mediumNode->GetID() << " following "
3424 << chain.front()->_mediumNode->GetID() <<"-"
3425 << chain.back ()->_mediumNode->GetID() <<
3426 " by " << move.Magnitude());
3428 } // loop on chains of links
3429 } // loop on 2 directions of propagation from quadrangle
3436 // vector<const SMDS_MeshElement*> vols( 100 );
3437 // vector<double> volSize( 100 );
3440 for ( pLink = links.begin(); pLink != links.end(); ++pLink ) {
3441 if ( pLink->IsMoved() ) {
3442 gp_Pnt p = pLink->MiddlePnt() + pLink->Move();
3443 GetMeshDS()->MoveNode( pLink->_mediumNode, p.X(), p.Y(), p.Z());
3445 // gp_Pnt pNew = pLink->MiddlePnt() + pLink->Move();
3446 // if ( pLink->MediumPos() != SMDS_TOP_3DSPACE )
3448 // // avoid making distorted volumes near boundary
3449 // SMDS_ElemIteratorPtr volIt =
3450 // (*pLink)._mediumNode->GetInverseElementIterator( SMDSAbs_Volume );
3451 // for ( nbVols = 0; volIt->more() && volTool.Set( volIt->next() ); ++nbVols )
3453 // vols [ nbVols ] = volTool.Element();
3454 // volSize[ nbVols ] = volTool.GetSize();
3456 // gp_Pnt pOld = pLink->MediumPnt();
3457 // const_cast<SMDS_MeshNode*>( pLink->_mediumNode )->setXYZ( pNew.X(), pNew.Y(), pNew.Z() );
3459 // while ( nbVols-- && ok )
3461 // volTool.Set( vols[ nbVols ]);
3462 // ok = ( volSize[ nbVols ] * volTool.GetSize() > 1e-20 );
3466 // const_cast<SMDS_MeshNode*>( pLink->_mediumNode )->setXYZ( pOld.X(), pOld.Y(), pOld.Z() );
3467 // MSG( "Do NOT move \t" << pLink->_mediumNode->GetID()
3468 // << " because of distortion of volume " << vols[ nbVols+1 ]->GetID());
3472 // GetMeshDS()->MoveNode( pLink->_mediumNode, pNew.X(), pNew.Y(), pNew.Z() );
3479 // Move the apex of pyramid together with the most curved link
3481 TIDSortedNodeSet::iterator apexIt = apexOfPyramid.begin();
3482 for ( ; apexIt != apexOfPyramid.end(); ++apexIt )
3484 SMESH_TNodeXYZ apex = *apexIt;
3486 gp_Vec maxMove( 0,0,0 );
3487 double maxMoveSize2 = 0;
3489 // shift of node index to get medium nodes between the base nodes
3490 const int base2MediumShift = 5;
3492 // find maximal movement of medium node
3493 SMDS_ElemIteratorPtr volIt = apex._node->GetInverseElementIterator( SMDSAbs_Volume );
3494 vector< const SMDS_MeshElement* > pyramids;
3495 while ( volIt->more() )
3497 const SMDS_MeshElement* pyram = volIt->next();
3498 if ( pyram->GetEntityType() != SMDSEntity_Quad_Pyramid ) continue;
3499 pyramids.push_back( pyram );
3501 for ( int iBase = 0; iBase < apexIndex; ++iBase )
3503 SMESH_TNodeXYZ medium = pyram->GetNode( iBase + base2MediumShift );
3504 if ( medium._node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_3DSPACE )
3506 SMESH_TNodeXYZ n1 = pyram->GetNode( iBase );
3507 SMESH_TNodeXYZ n2 = pyram->GetNode( ( iBase+1 ) % 4 );
3508 gp_Pnt middle = 0.5 * ( n1 + n2 );
3509 gp_Vec move( middle, medium );
3510 double moveSize2 = move.SquareMagnitude();
3511 if ( moveSize2 > maxMoveSize2 )
3512 maxMove = move, maxMoveSize2 = moveSize2;
3518 if ( maxMoveSize2 > 1e-20 )
3520 apex += maxMove.XYZ();
3521 GetMeshDS()->MoveNode( apex._node, apex.X(), apex.Y(), apex.Z());
3523 // move medium nodes neighboring the apex to the middle
3524 const int base2MediumShift_2 = 9;
3525 for ( unsigned i = 0; i < pyramids.size(); ++i )
3526 for ( int iBase = 0; iBase < apexIndex; ++iBase )
3528 SMESH_TNodeXYZ base = pyramids[i]->GetNode( iBase );
3529 const SMDS_MeshNode* medium = pyramids[i]->GetNode( iBase + base2MediumShift_2 );
3530 gp_XYZ middle = 0.5 * ( apex + base );
3531 GetMeshDS()->MoveNode( medium, middle.X(), middle.Y(), middle.Z());