1 // SMESH SMESH : implementaion of SMESH idl descriptions
3 // Copyright (C) 2003 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
24 // File : StdMeshers_MEFISTO_2D.cxx
25 // Moved here from SMESH_MEFISTO_2D.cxx
26 // Author : Paul RASCLE, EDF
30 #include "StdMeshers_MEFISTO_2D.hxx"
32 #include "SMESH_Gen.hxx"
33 #include "SMESH_Mesh.hxx"
34 #include "SMESH_subMesh.hxx"
35 #include "SMESH_Block.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "SMESH_Comment.hxx"
39 #include "StdMeshers_FaceSide.hxx"
40 #include "StdMeshers_MaxElementArea.hxx"
41 #include "StdMeshers_LengthFromEdges.hxx"
46 #include "SMDS_MeshElement.hxx"
47 #include "SMDS_MeshNode.hxx"
48 #include "SMDS_EdgePosition.hxx"
49 #include "SMDS_FacePosition.hxx"
51 #include "utilities.h"
53 #include <BRepTools.hxx>
54 #include <BRep_Tool.hxx>
55 #include <Geom2d_Curve.hxx>
56 #include <Geom_Surface.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
60 #include <TopTools_ListOfShape.hxx>
61 #include <TopTools_MapOfShape.hxx>
63 #include <TopoDS_Edge.hxx>
64 #include <TopoDS_Face.hxx>
65 #include <TopoDS_Iterator.hxx>
66 #include <gp_Pnt2d.hxx>
70 //=============================================================================
74 //=============================================================================
76 StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D(int hypId, int studyId, SMESH_Gen * gen):
77 SMESH_2D_Algo(hypId, studyId, gen)
79 MESSAGE("StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D");
81 _shapeType = (1 << TopAbs_FACE);
82 _compatibleHypothesis.push_back("MaxElementArea");
83 _compatibleHypothesis.push_back("LengthFromEdges");
87 _hypMaxElementArea = NULL;
88 _hypLengthFromEdges = NULL;
92 //=============================================================================
96 //=============================================================================
98 StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D()
100 MESSAGE("StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D");
103 //=============================================================================
107 //=============================================================================
109 bool StdMeshers_MEFISTO_2D::CheckHypothesis
111 const TopoDS_Shape& aShape,
112 SMESH_Hypothesis::Hypothesis_Status& aStatus)
114 _hypMaxElementArea = NULL;
115 _hypLengthFromEdges = NULL;
119 list <const SMESHDS_Hypothesis * >::const_iterator itl;
120 const SMESHDS_Hypothesis *theHyp;
122 const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
123 int nbHyp = hyps.size();
126 aStatus = SMESH_Hypothesis::HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
127 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
131 theHyp = (*itl); // use only the first hypothesis
133 string hypName = theHyp->GetName();
137 if (hypName == "MaxElementArea")
139 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea *>(theHyp);
140 ASSERT(_hypMaxElementArea);
141 _maxElementArea = _hypMaxElementArea->GetMaxArea();
143 aStatus = SMESH_Hypothesis::HYP_OK;
146 else if (hypName == "LengthFromEdges")
148 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges *>(theHyp);
149 ASSERT(_hypLengthFromEdges);
151 aStatus = SMESH_Hypothesis::HYP_OK;
154 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
159 if (_maxElementArea > 0)
161 //_edgeLength = 2 * sqrt(_maxElementArea); // triangles : minorant
162 _edgeLength = sqrt(2. * _maxElementArea/sqrt(3.0));
166 isOk = (_hypLengthFromEdges != NULL); // **** check mode
168 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
174 //=============================================================================
178 //=============================================================================
180 bool StdMeshers_MEFISTO_2D::Compute(SMESH_Mesh & aMesh, const TopoDS_Shape & aShape)
182 MESSAGE("StdMeshers_MEFISTO_2D::Compute");
184 TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
186 // helper builds quadratic mesh if necessary
187 SMESH_MesherHelper helper(aMesh);
189 _quadraticMesh = myTool->IsQuadraticSubMesh(aShape);
190 const bool ignoreMediumNodes = _quadraticMesh;
192 // get all edges of a face
194 TWireVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
195 int nbWires = wires.size();
196 if ( problem && !problem->IsOK() ) return error( problem );
197 if ( nbWires == 0 ) return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
198 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
199 return error(COMPERR_BAD_INPUT_MESH,
200 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
202 // compute average edge length
203 if (!_hypMaxElementArea)
207 for ( int iW = 0; iW < nbWires; ++iW )
209 StdMeshers_FaceSidePtr wire = wires[ iW ];
210 _edgeLength += wire->Length();
211 nbSegments += wire->NbSegments();
214 _edgeLength /= nbSegments;
217 if (/*_hypLengthFromEdges &&*/ _edgeLength < DBL_MIN )
220 Z nblf; //nombre de lignes fermees (enveloppe en tete)
221 Z *nudslf = NULL; //numero du dernier sommet de chaque ligne fermee
223 Z nbpti = 0; //nombre points internes futurs sommets de la triangulation
232 Z nutysu = 1; // 1: il existe un fonction areteideale_()
233 // Z nutysu=0; // 0: on utilise aretmx
234 R aretmx = _edgeLength; // longueur max aretes future triangulation
238 nudslf = new Z[1 + nblf];
243 // count nb of input points
244 for ( int iW = 0; iW < nbWires; ++iW )
246 nbpnt += wires[iW]->NbPoints() - 1;
247 nudslf[iw++] = nbpnt;
250 uvslf = new R2[nudslf[nblf]];
252 double scalex, scaley;
253 ComputeScaleOnFace(aMesh, F, scalex, scaley);
255 // correspondence mefisto index --> Nodes
256 vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);
260 // fill input points UV
261 if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
264 aptrte(nutysu, aretmx,
265 nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);
269 MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
270 MESSAGE(" Node Number " << nbst);
271 StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
276 error(ierr,"Error in Triangulation (aptrte())");
279 if (nudslf != NULL) delete[]nudslf;
280 if (uvslf != NULL) delete[]uvslf;
281 if (uvst != NULL) delete[]uvst;
282 if (nust != NULL) delete[]nust;
287 //=======================================================================
288 //function : fixOverlappedLinkUV
289 //purpose : prevent failure due to overlapped adjacent links
290 //=======================================================================
292 static bool fixOverlappedLinkUV( R2& uv0, const R2& uv1, const R2& uv2 )
294 gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
295 gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );
297 double tol2 = DBL_MIN * DBL_MIN;
298 double sqMod1 = v1.SquareModulus();
299 if ( sqMod1 <= tol2 ) return false;
300 double sqMod2 = v2.SquareModulus();
301 if ( sqMod2 <= tol2 ) return false;
305 // check sinus >= 1.e-3
306 const double minSin = 1.e-3;
307 if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
308 MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
309 v1.SetCoord( -v1.Y(), v1.X() );
310 double delta = sqrt( sqMod1 ) * minSin;
320 // MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
321 // MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
322 // "v2( " << v2.X() << " " << v2.Y() << " ) ");
323 // MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
324 // v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
325 // v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
326 // gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
327 // sqMod1 = v1.SquareModulus();
328 // sqMod2 = v2.SquareModulus();
330 // double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
331 // MESSAGE("NEW SIN: " << sin);
338 //=======================================================================
339 //function : fixCommonVertexUV
341 //=======================================================================
343 static bool fixCommonVertexUV (R2 & theUV,
344 const TopoDS_Vertex& theV,
345 const TopoDS_Face& theF,
346 const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
347 SMESH_Mesh & theMesh,
348 const double theScaleX,
349 const double theScaleY,
350 const bool theCreateQuadratic)
352 if( !theVWMap.Contains( theV )) return false;
354 // check if there is another wire sharing theV
355 const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
356 TopTools_ListIteratorOfListOfShape aWIt;
357 TopTools_MapOfShape aWires;
358 for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
359 aWires.Add( aWIt.Value() );
360 if ( aWires.Extent() < 2 ) return false;
362 TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
363 TopoDS_Shape anInnerWire;
364 for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
365 if ( !anOuterWire.IsSame( aWIt.Value() ))
366 anInnerWire = aWIt.Value();
368 TopTools_ListOfShape EList;
369 list< double > UList;
371 // find edges of theW sharing theV
372 // and find 2d normal to them at theV
374 TopoDS_Iterator itE( anInnerWire );
375 for ( ; itE.More(); itE.Next() )
377 const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
378 TopoDS_Iterator itV( E );
379 for ( ; itV.More(); itV.Next() )
381 const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
382 if ( !V.IsSame( theV ))
385 Standard_Real u = BRep_Tool::Parameter( V, E );
386 UList.push_back( u );
388 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
392 gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
393 if ( E.Orientation() == TopAbs_REVERSED )
399 // define step size by which to move theUV
401 gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
402 gp_Pnt2d thisUV( theUV.x, theUV.y );
403 double maxDist = -DBL_MAX;
404 TopTools_ListIteratorOfListOfShape aEIt (EList);
405 list< double >::iterator aUIt = UList.begin();
406 for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
408 const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
410 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
412 double umin = DBL_MAX, umax = -DBL_MAX;
413 SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
414 if ( !nIt->more() ) // no nodes on edge, only on vertices
420 while ( nIt->more() ) {
421 const SMDS_MeshNode* node = nIt->next();
422 // check if node is medium
423 if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
425 const SMDS_EdgePosition* epos =
426 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
427 double u = epos->GetUParameter();
434 bool isFirstCommon = ( *aUIt == f );
435 gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
436 double dist = thisUV.SquareDistance( uv );
437 if ( dist > maxDist ) {
443 uv0.x = thisUV.X(); uv0.y = thisUV.Y();
444 uv1.x = nextUV.X(); uv1.y = nextUV.Y();
445 uv2.x = thisUV.X(); uv2.y = thisUV.Y();
447 uv1.x *= theScaleX; uv1.y *= theScaleY;
449 if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
451 double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));
453 // move theUV along the normal by the step
457 MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
458 << ") by (" << N.X() << " " << N.Y() << ")"
459 << endl << "--- MAX DIST " << maxDist);
469 //=============================================================================
473 //=============================================================================
475 bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector & wires,
477 vector<const SMDS_MeshNode*>& mefistoToDS,
481 // to avoid passing same uv points for a vertex common to 2 wires
483 TopTools_IndexedDataMapOfShapeListOfShape VWMap;
484 if ( wires.size() > 1 )
486 F = TopoDS::Face( myTool->GetSubShape() );
487 TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
489 for ( int iW = 0; iW < wires.size(); ++iW )
490 nbVertices += wires[ iW ]->NbEdges();
491 if ( nbVertices == VWMap.Extent() )
492 VWMap.Clear(); // wires have no common vertices
496 list< int > mOnVertex;
498 for ( int iW = 0; iW < wires.size(); ++iW )
500 const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
501 if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
502 return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
503 << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
504 << ", probably because of invalid node parameters on geom edges");
506 if ( m + uvPtVec.size()-1 > mefistoToDS.size() ) {
507 MESSAGE("Wrong mefistoToDS.size: "<<mefistoToDS.size()<<" < "<<m + uvPtVec.size()-1);
508 return error("Internal error");
511 vector<UVPtStruct>::const_iterator uvPt = uvPtVec.begin();
512 for ( ++uvPt; uvPt != uvPtVec.end(); ++uvPt )
514 // bind mefisto ID to node
515 mefistoToDS[m] = uvPt->node;
517 uvslf[m].x = uvPt->u * scalex;
518 uvslf[m].y = uvPt->v * scaley;
519 if ( uvPt->node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
520 mOnVertex.push_back( m );
524 int mFirst = mOnVertex.front(), mLast = m - 1;
525 list< int >::iterator mIt = mOnVertex.begin();
526 for ( ; mIt != mOnVertex.end(); ++mIt)
529 if ( iW && !VWMap.IsEmpty()) { // except outer wire
530 // avoid passing same uv point for a vertex common to 2 wires
531 int vID = mefistoToDS[m]->GetPosition()->GetShapeId();
532 TopoDS_Vertex V = TopoDS::Vertex( myTool->GetMeshDS()->IndexToShape( vID ));
533 if ( fixCommonVertexUV( uvslf[m], V, F, VWMap, *myTool->GetMesh(),
534 scalex, scaley, _quadraticMesh )) {
535 myNodesOnCommonV.push_back( mefistoToDS[m] );
539 // prevent failure on overlapped adjacent links,
540 // check only links ending in vertex nodes
541 int mB = m - 1, mA = m + 1; // indices Before and After
542 if ( mB < mFirst ) mB = mLast;
543 if ( mA > mLast ) mA = mFirst;
544 fixOverlappedLinkUV (uvslf[ mB ], uvslf[ m ], uvslf[ mA ]);
551 //=============================================================================
555 //=============================================================================
557 void StdMeshers_MEFISTO_2D::ComputeScaleOnFace(SMESH_Mesh & aMesh,
558 const TopoDS_Face & aFace,
562 TopoDS_Wire W = BRepTools::OuterWire(aFace);
564 double xmin = 1.e300; // min & max of face 2D parametric coord.
565 double xmax = -1.e300;
566 double ymin = 1.e300;
567 double ymax = -1.e300;
572 TopExp_Explorer wexp(W, TopAbs_EDGE);
573 for ( ; wexp.More(); wexp.Next())
575 const TopoDS_Edge & E = TopoDS::Edge( wexp.Current() );
577 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, aFace, f, l);
578 if ( C2d.IsNull() ) continue;
579 double du = (l - f) / double (nbp);
580 for (int i = 0; i <= nbp; i++)
582 double param = f + double (i) * du;
583 gp_Pnt2d p = C2d->Value(param);
592 // MESSAGE(" "<< f<<" "<<l<<" "<<param<<" "<<xmin<<" "<<xmax<<" "<<ymin<<" "<<ymax);
599 double xmoy = (xmax + xmin) / 2.;
600 double ymoy = (ymax + ymin) / 2.;
601 double xsize = xmax - xmin;
602 double ysize = ymax - ymin;
605 Handle(Geom_Surface) S = BRep_Tool::Surface(aFace,L); // 3D surface
609 gp_Pnt PX0 = S->Value(xmin, ymoy);
610 gp_Pnt PY0 = S->Value(xmoy, ymin);
611 double dx = xsize / double (nbp);
612 double dy = ysize / double (nbp);
613 for (int i = 1; i <= nbp; i++)
615 double x = xmin + double (i) * dx;
616 gp_Pnt PX = S->Value(x, ymoy);
617 double y = ymin + double (i) * dy;
618 gp_Pnt PY = S->Value(xmoy, y);
619 length_x += PX.Distance(PX0);
620 length_y += PY.Distance(PY0);
624 scalex = length_x / xsize;
625 scaley = length_y / ysize;
628 double xyratio = xsize*scalex/(ysize*scaley);
629 const double maxratio = 1.e2;
631 if (xyratio > maxratio) {
633 scaley *= xyratio / maxratio;
636 else if (xyratio < 1./maxratio) {
638 scalex *= 1 / xyratio / maxratio;
645 //=============================================================================
649 //=============================================================================
651 void StdMeshers_MEFISTO_2D::StoreResult(Z nbst, R2 * uvst, Z nbt, Z * nust,
652 vector< const SMDS_MeshNode*>&mefistoToDS,
653 double scalex, double scaley)
655 SMESHDS_Mesh * meshDS = myTool->GetMeshDS();
656 int faceID = myTool->GetSubShapeID();
658 TopoDS_Face F = TopoDS::Face( myTool->GetSubShape() );
659 Handle(Geom_Surface) S = BRep_Tool::Surface( F );
661 Z n = mefistoToDS.size(); // nb input points
662 mefistoToDS.resize( nbst );
663 for ( ; n < nbst; n++)
667 double u = uvst[n][0] / scalex;
668 double v = uvst[n][1] / scaley;
669 gp_Pnt P = S->Value(u, v);
671 SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
672 meshDS->SetNodeOnFace(node, faceID, u, v);
674 //MESSAGE(P.X()<<" "<<P.Y()<<" "<<P.Z());
675 mefistoToDS[n] = node;
676 //MESSAGE("NEW: "<<n<<" "<<mefistoToDS[n+1]);
682 // triangle points must be in trigonometric order if face is Forward
683 // else they must be put clockwise
685 bool triangleIsWellOriented = ( F.Orientation() == TopAbs_FORWARD );
687 for (n = 1; n <= nbt; n++)
689 const SMDS_MeshNode * n1 = mefistoToDS[ nust[m++] - 1 ];
690 const SMDS_MeshNode * n2 = mefistoToDS[ nust[m++] - 1 ];
691 const SMDS_MeshNode * n3 = mefistoToDS[ nust[m++] - 1 ];
693 SMDS_MeshElement * elt;
694 if (triangleIsWellOriented)
695 elt = myTool->AddFace(n1, n2, n3);
697 elt = myTool->AddFace(n1, n3, n2);
699 meshDS->SetMeshElementOnShape(elt, faceID);
703 // remove bad elements built on vertices shared by wires
705 list<const SMDS_MeshNode*>::iterator itN = myNodesOnCommonV.begin();
706 for ( ; itN != myNodesOnCommonV.end(); itN++ )
708 const SMDS_MeshNode* node = *itN;
709 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
710 while ( invElemIt->more() )
712 const SMDS_MeshElement* elem = invElemIt->next();
713 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
715 while ( itN->more() )
716 if ( itN->next() == node)
719 MESSAGE( "RM bad element " << elem->GetID());
720 meshDS->RemoveElement( elem );