1 // Copyright (C) 2007-2008 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
22 // SMESH SMESH : implementaion of SMESH idl descriptions
23 // File : StdMeshers_MEFISTO_2D.cxx
24 // Moved here from SMESH_MEFISTO_2D.cxx
25 // Author : Paul RASCLE, EDF
28 #include "StdMeshers_MEFISTO_2D.hxx"
30 #include "SMESH_Gen.hxx"
31 #include "SMESH_Mesh.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_Block.hxx"
34 #include "SMESH_MesherHelper.hxx"
35 #include "SMESH_Comment.hxx"
37 #include "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_MaxElementArea.hxx"
39 #include "StdMeshers_LengthFromEdges.hxx"
44 #include "SMDS_MeshElement.hxx"
45 #include "SMDS_MeshNode.hxx"
46 #include "SMDS_EdgePosition.hxx"
47 #include "SMDS_FacePosition.hxx"
49 #include "utilities.h"
51 #include <BRepTools.hxx>
52 #include <BRep_Tool.hxx>
53 #include <Geom2d_Curve.hxx>
54 #include <Geom_Surface.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopTools_ListIteratorOfListOfShape.hxx>
58 #include <TopTools_ListOfShape.hxx>
59 #include <TopTools_MapOfShape.hxx>
61 #include <TopoDS_Edge.hxx>
62 #include <TopoDS_Face.hxx>
63 #include <TopoDS_Iterator.hxx>
64 #include <gp_Pnt2d.hxx>
68 //=============================================================================
72 //=============================================================================
74 StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D(int hypId, int studyId, SMESH_Gen * gen):
75 SMESH_2D_Algo(hypId, studyId, gen)
77 MESSAGE("StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D");
79 _shapeType = (1 << TopAbs_FACE);
80 _compatibleHypothesis.push_back("MaxElementArea");
81 _compatibleHypothesis.push_back("LengthFromEdges");
85 _hypMaxElementArea = NULL;
86 _hypLengthFromEdges = NULL;
90 //=============================================================================
94 //=============================================================================
96 StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D()
98 MESSAGE("StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D");
101 //=============================================================================
105 //=============================================================================
107 bool StdMeshers_MEFISTO_2D::CheckHypothesis
109 const TopoDS_Shape& aShape,
110 SMESH_Hypothesis::Hypothesis_Status& aStatus)
112 _hypMaxElementArea = NULL;
113 _hypLengthFromEdges = NULL;
117 list <const SMESHDS_Hypothesis * >::const_iterator itl;
118 const SMESHDS_Hypothesis *theHyp;
120 const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
121 int nbHyp = hyps.size();
124 aStatus = SMESH_Hypothesis::HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
125 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
129 theHyp = (*itl); // use only the first hypothesis
131 string hypName = theHyp->GetName();
135 if (hypName == "MaxElementArea")
137 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea *>(theHyp);
138 ASSERT(_hypMaxElementArea);
139 _maxElementArea = _hypMaxElementArea->GetMaxArea();
141 aStatus = SMESH_Hypothesis::HYP_OK;
144 else if (hypName == "LengthFromEdges")
146 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges *>(theHyp);
147 ASSERT(_hypLengthFromEdges);
149 aStatus = SMESH_Hypothesis::HYP_OK;
152 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
157 if (_maxElementArea > 0)
159 //_edgeLength = 2 * sqrt(_maxElementArea); // triangles : minorant
160 _edgeLength = sqrt(2. * _maxElementArea/sqrt(3.0));
164 isOk = (_hypLengthFromEdges != NULL); // **** check mode
166 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
172 //=============================================================================
176 //=============================================================================
178 bool StdMeshers_MEFISTO_2D::Compute(SMESH_Mesh & aMesh, const TopoDS_Shape & aShape)
180 MESSAGE("StdMeshers_MEFISTO_2D::Compute");
182 TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
184 // helper builds quadratic mesh if necessary
185 SMESH_MesherHelper helper(aMesh);
187 _quadraticMesh = myTool->IsQuadraticSubMesh(aShape);
188 const bool ignoreMediumNodes = _quadraticMesh;
190 // get all edges of a face
192 TWireVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
193 int nbWires = wires.size();
194 if ( problem && !problem->IsOK() ) return error( problem );
195 if ( nbWires == 0 ) return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
196 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
197 return error(COMPERR_BAD_INPUT_MESH,
198 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
200 // compute average edge length
201 if (!_hypMaxElementArea)
205 for ( int iW = 0; iW < nbWires; ++iW )
207 StdMeshers_FaceSidePtr wire = wires[ iW ];
208 _edgeLength += wire->Length();
209 nbSegments += wire->NbSegments();
212 _edgeLength /= nbSegments;
215 if (/*_hypLengthFromEdges &&*/ _edgeLength < DBL_MIN )
218 Z nblf; //nombre de lignes fermees (enveloppe en tete)
219 Z *nudslf = NULL; //numero du dernier sommet de chaque ligne fermee
221 Z nbpti = 0; //nombre points internes futurs sommets de la triangulation
230 Z nutysu = 1; // 1: il existe un fonction areteideale_()
231 // Z nutysu=0; // 0: on utilise aretmx
232 R aretmx = _edgeLength; // longueur max aretes future triangulation
236 nudslf = new Z[1 + nblf];
241 // count nb of input points
242 for ( int iW = 0; iW < nbWires; ++iW )
244 nbpnt += wires[iW]->NbPoints() - 1;
245 nudslf[iw++] = nbpnt;
248 uvslf = new R2[nudslf[nblf]];
250 double scalex, scaley;
251 ComputeScaleOnFace(aMesh, F, scalex, scaley);
253 // correspondence mefisto index --> Nodes
254 vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);
258 // fill input points UV
259 if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
262 aptrte(nutysu, aretmx,
263 nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);
267 MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
268 MESSAGE(" Node Number " << nbst);
269 StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
274 error(ierr,"Error in Triangulation (aptrte())");
277 if (nudslf != NULL) delete[]nudslf;
278 if (uvslf != NULL) delete[]uvslf;
279 if (uvst != NULL) delete[]uvst;
280 if (nust != NULL) delete[]nust;
285 //=======================================================================
286 //function : fixOverlappedLinkUV
287 //purpose : prevent failure due to overlapped adjacent links
288 //=======================================================================
290 static bool fixOverlappedLinkUV( R2& uv0, const R2& uv1, const R2& uv2 )
292 gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
293 gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );
295 double tol2 = DBL_MIN * DBL_MIN;
296 double sqMod1 = v1.SquareModulus();
297 if ( sqMod1 <= tol2 ) return false;
298 double sqMod2 = v2.SquareModulus();
299 if ( sqMod2 <= tol2 ) return false;
303 // check sinus >= 1.e-3
304 const double minSin = 1.e-3;
305 if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
306 MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
307 v1.SetCoord( -v1.Y(), v1.X() );
308 double delta = sqrt( sqMod1 ) * minSin;
318 // MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
319 // MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
320 // "v2( " << v2.X() << " " << v2.Y() << " ) ");
321 // MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
322 // v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
323 // v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
324 // gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
325 // sqMod1 = v1.SquareModulus();
326 // sqMod2 = v2.SquareModulus();
328 // double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
329 // MESSAGE("NEW SIN: " << sin);
336 //=======================================================================
337 //function : fixCommonVertexUV
339 //=======================================================================
341 static bool fixCommonVertexUV (R2 & theUV,
342 const TopoDS_Vertex& theV,
343 const TopoDS_Face& theF,
344 const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
345 SMESH_Mesh & theMesh,
346 const double theScaleX,
347 const double theScaleY,
348 const bool theCreateQuadratic)
350 if( !theVWMap.Contains( theV )) return false;
352 // check if there is another wire sharing theV
353 const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
354 TopTools_ListIteratorOfListOfShape aWIt;
355 TopTools_MapOfShape aWires;
356 for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
357 aWires.Add( aWIt.Value() );
358 if ( aWires.Extent() < 2 ) return false;
360 TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
361 TopoDS_Shape anInnerWire;
362 for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
363 if ( !anOuterWire.IsSame( aWIt.Value() ))
364 anInnerWire = aWIt.Value();
366 TopTools_ListOfShape EList;
367 list< double > UList;
369 // find edges of theW sharing theV
370 // and find 2d normal to them at theV
372 TopoDS_Iterator itE( anInnerWire );
373 for ( ; itE.More(); itE.Next() )
375 const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
376 TopoDS_Iterator itV( E );
377 for ( ; itV.More(); itV.Next() )
379 const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
380 if ( !V.IsSame( theV ))
383 Standard_Real u = BRep_Tool::Parameter( V, E );
384 UList.push_back( u );
386 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
390 gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
391 if ( E.Orientation() == TopAbs_REVERSED )
397 // define step size by which to move theUV
399 gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
400 gp_Pnt2d thisUV( theUV.x, theUV.y );
401 double maxDist = -DBL_MAX;
402 TopTools_ListIteratorOfListOfShape aEIt (EList);
403 list< double >::iterator aUIt = UList.begin();
404 for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
406 const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
408 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
410 double umin = DBL_MAX, umax = -DBL_MAX;
411 SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
412 if ( !nIt->more() ) // no nodes on edge, only on vertices
418 while ( nIt->more() ) {
419 const SMDS_MeshNode* node = nIt->next();
420 // check if node is medium
421 if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
423 const SMDS_EdgePosition* epos =
424 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
425 double u = epos->GetUParameter();
432 bool isFirstCommon = ( *aUIt == f );
433 gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
434 double dist = thisUV.SquareDistance( uv );
435 if ( dist > maxDist ) {
441 uv0.x = thisUV.X(); uv0.y = thisUV.Y();
442 uv1.x = nextUV.X(); uv1.y = nextUV.Y();
443 uv2.x = thisUV.X(); uv2.y = thisUV.Y();
445 uv1.x *= theScaleX; uv1.y *= theScaleY;
447 if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
449 double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));
451 // move theUV along the normal by the step
455 MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
456 << ") by (" << N.X() << " " << N.Y() << ")"
457 << endl << "--- MAX DIST " << maxDist);
467 //=============================================================================
471 //=============================================================================
473 bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector & wires,
475 vector<const SMDS_MeshNode*>& mefistoToDS,
479 // to avoid passing same uv points for a vertex common to 2 wires
481 TopTools_IndexedDataMapOfShapeListOfShape VWMap;
482 if ( wires.size() > 1 )
484 F = TopoDS::Face( myTool->GetSubShape() );
485 TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
487 for ( int iW = 0; iW < wires.size(); ++iW )
488 nbVertices += wires[ iW ]->NbEdges();
489 if ( nbVertices == VWMap.Extent() )
490 VWMap.Clear(); // wires have no common vertices
495 for ( int iW = 0; iW < wires.size(); ++iW )
497 const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
498 if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
499 return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
500 << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
501 << ", probably because of invalid node parameters on geom edges");
503 if ( m + uvPtVec.size()-1 > mefistoToDS.size() ) {
504 MESSAGE("Wrong mefistoToDS.size: "<<mefistoToDS.size()<<" < "<<m + uvPtVec.size()-1);
505 return error("Internal error");
508 list< int > mOnVertex;
509 vector<UVPtStruct>::const_iterator uvPt = uvPtVec.begin();
510 for ( ++uvPt; uvPt != uvPtVec.end(); ++uvPt )
512 // bind mefisto ID to node
513 mefistoToDS[m] = uvPt->node;
515 uvslf[m].x = uvPt->u * scalex;
516 uvslf[m].y = uvPt->v * scaley;
517 if ( uvPt->node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
518 mOnVertex.push_back( m );
522 int mFirst = mOnVertex.front(), mLast = m - 1;
523 list< int >::iterator mIt = mOnVertex.begin();
524 for ( ; mIt != mOnVertex.end(); ++mIt)
527 if ( iW && !VWMap.IsEmpty()) { // except outer wire
528 // avoid passing same uv point for a vertex common to 2 wires
529 int vID = mefistoToDS[m]->GetPosition()->GetShapeId();
530 TopoDS_Vertex V = TopoDS::Vertex( myTool->GetMeshDS()->IndexToShape( vID ));
531 if ( fixCommonVertexUV( uvslf[m], V, F, VWMap, *myTool->GetMesh(),
532 scalex, scaley, _quadraticMesh )) {
533 myNodesOnCommonV.push_back( mefistoToDS[m] );
537 // prevent failure on overlapped adjacent links,
538 // check only links ending in vertex nodes
539 int mB = m - 1, mA = m + 1; // indices Before and After
540 if ( mB < mFirst ) mB = mLast;
541 if ( mA > mLast ) mA = mFirst;
542 fixOverlappedLinkUV (uvslf[ mB ], uvslf[ m ], uvslf[ mA ]);
549 //=============================================================================
553 //=============================================================================
555 void StdMeshers_MEFISTO_2D::ComputeScaleOnFace(SMESH_Mesh & aMesh,
556 const TopoDS_Face & aFace,
560 TopoDS_Wire W = BRepTools::OuterWire(aFace);
562 double xmin = 1.e300; // min & max of face 2D parametric coord.
563 double xmax = -1.e300;
564 double ymin = 1.e300;
565 double ymax = -1.e300;
570 TopExp_Explorer wexp(W, TopAbs_EDGE);
571 for ( ; wexp.More(); wexp.Next())
573 const TopoDS_Edge & E = TopoDS::Edge( wexp.Current() );
575 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, aFace, f, l);
576 if ( C2d.IsNull() ) continue;
577 double du = (l - f) / double (nbp);
578 for (int i = 0; i <= nbp; i++)
580 double param = f + double (i) * du;
581 gp_Pnt2d p = C2d->Value(param);
590 // MESSAGE(" "<< f<<" "<<l<<" "<<param<<" "<<xmin<<" "<<xmax<<" "<<ymin<<" "<<ymax);
597 double xmoy = (xmax + xmin) / 2.;
598 double ymoy = (ymax + ymin) / 2.;
599 double xsize = xmax - xmin;
600 double ysize = ymax - ymin;
603 Handle(Geom_Surface) S = BRep_Tool::Surface(aFace,L); // 3D surface
607 gp_Pnt PX0 = S->Value(xmin, ymoy);
608 gp_Pnt PY0 = S->Value(xmoy, ymin);
609 double dx = xsize / double (nbp);
610 double dy = ysize / double (nbp);
611 for (int i = 1; i <= nbp; i++)
613 double x = xmin + double (i) * dx;
614 gp_Pnt PX = S->Value(x, ymoy);
615 double y = ymin + double (i) * dy;
616 gp_Pnt PY = S->Value(xmoy, y);
617 length_x += PX.Distance(PX0);
618 length_y += PY.Distance(PY0);
622 scalex = length_x / xsize;
623 scaley = length_y / ysize;
626 double xyratio = xsize*scalex/(ysize*scaley);
627 const double maxratio = 1.e2;
629 if (xyratio > maxratio) {
631 scaley *= xyratio / maxratio;
634 else if (xyratio < 1./maxratio) {
636 scalex *= 1 / xyratio / maxratio;
643 //=============================================================================
647 //=============================================================================
649 void StdMeshers_MEFISTO_2D::StoreResult(Z nbst, R2 * uvst, Z nbt, Z * nust,
650 vector< const SMDS_MeshNode*>&mefistoToDS,
651 double scalex, double scaley)
653 SMESHDS_Mesh * meshDS = myTool->GetMeshDS();
654 int faceID = myTool->GetSubShapeID();
656 TopoDS_Face F = TopoDS::Face( myTool->GetSubShape() );
657 Handle(Geom_Surface) S = BRep_Tool::Surface( F );
659 Z n = mefistoToDS.size(); // nb input points
660 mefistoToDS.resize( nbst );
661 for ( ; n < nbst; n++)
665 double u = uvst[n][0] / scalex;
666 double v = uvst[n][1] / scaley;
667 gp_Pnt P = S->Value(u, v);
669 SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
670 meshDS->SetNodeOnFace(node, faceID, u, v);
672 //MESSAGE(P.X()<<" "<<P.Y()<<" "<<P.Z());
673 mefistoToDS[n] = node;
674 //MESSAGE("NEW: "<<n<<" "<<mefistoToDS[n+1]);
680 // triangle points must be in trigonometric order if face is Forward
681 // else they must be put clockwise
683 bool triangleIsWellOriented = ( F.Orientation() == TopAbs_FORWARD );
685 for (n = 1; n <= nbt; n++)
687 const SMDS_MeshNode * n1 = mefistoToDS[ nust[m++] - 1 ];
688 const SMDS_MeshNode * n2 = mefistoToDS[ nust[m++] - 1 ];
689 const SMDS_MeshNode * n3 = mefistoToDS[ nust[m++] - 1 ];
691 SMDS_MeshElement * elt;
692 if (triangleIsWellOriented)
693 elt = myTool->AddFace(n1, n2, n3);
695 elt = myTool->AddFace(n1, n3, n2);
697 meshDS->SetMeshElementOnShape(elt, faceID);
701 // remove bad elements built on vertices shared by wires
703 list<const SMDS_MeshNode*>::iterator itN = myNodesOnCommonV.begin();
704 for ( ; itN != myNodesOnCommonV.end(); itN++ )
706 const SMDS_MeshNode* node = *itN;
707 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
708 while ( invElemIt->more() )
710 const SMDS_MeshElement* elem = invElemIt->next();
711 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
713 while ( itN->more() )
714 if ( itN->next() == node)
717 MESSAGE( "RM bad element " << elem->GetID());
718 meshDS->RemoveElement( elem );