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
29 #include "StdMeshers_MEFISTO_2D.hxx"
31 #include "SMESH_Gen.hxx"
32 #include "SMESH_Mesh.hxx"
33 #include "SMESH_subMesh.hxx"
34 #include "SMESH_Block.hxx"
35 #include "SMESH_MesherHelper.hxx"
36 #include "SMESH_Comment.hxx"
38 #include "StdMeshers_FaceSide.hxx"
39 #include "StdMeshers_MaxElementArea.hxx"
40 #include "StdMeshers_LengthFromEdges.hxx"
45 #include "SMDS_MeshElement.hxx"
46 #include "SMDS_MeshNode.hxx"
47 #include "SMDS_EdgePosition.hxx"
48 #include "SMDS_FacePosition.hxx"
50 #include "utilities.h"
52 #include <BRepTools.hxx>
53 #include <BRep_Tool.hxx>
54 #include <Geom2d_Curve.hxx>
55 #include <Geom_Surface.hxx>
57 #include <TopExp_Explorer.hxx>
58 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <TopTools_ListOfShape.hxx>
60 #include <TopTools_MapOfShape.hxx>
62 #include <TopoDS_Edge.hxx>
63 #include <TopoDS_Face.hxx>
64 #include <TopoDS_Iterator.hxx>
65 #include <gp_Pnt2d.hxx>
69 //=============================================================================
73 //=============================================================================
75 StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D(int hypId, int studyId, SMESH_Gen * gen):
76 SMESH_2D_Algo(hypId, studyId, gen)
78 MESSAGE("StdMeshers_MEFISTO_2D::StdMeshers_MEFISTO_2D");
80 _shapeType = (1 << TopAbs_FACE);
81 _compatibleHypothesis.push_back("MaxElementArea");
82 _compatibleHypothesis.push_back("LengthFromEdges");
86 _hypMaxElementArea = NULL;
87 _hypLengthFromEdges = NULL;
91 //=============================================================================
95 //=============================================================================
97 StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D()
99 MESSAGE("StdMeshers_MEFISTO_2D::~StdMeshers_MEFISTO_2D");
102 //=============================================================================
106 //=============================================================================
108 bool StdMeshers_MEFISTO_2D::CheckHypothesis
110 const TopoDS_Shape& aShape,
111 SMESH_Hypothesis::Hypothesis_Status& aStatus)
113 _hypMaxElementArea = NULL;
114 _hypLengthFromEdges = NULL;
118 list <const SMESHDS_Hypothesis * >::const_iterator itl;
119 const SMESHDS_Hypothesis *theHyp;
121 const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
122 int nbHyp = hyps.size();
125 aStatus = SMESH_Hypothesis::HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
126 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
130 theHyp = (*itl); // use only the first hypothesis
132 string hypName = theHyp->GetName();
136 if (hypName == "MaxElementArea")
138 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea *>(theHyp);
139 ASSERT(_hypMaxElementArea);
140 _maxElementArea = _hypMaxElementArea->GetMaxArea();
142 aStatus = SMESH_Hypothesis::HYP_OK;
145 else if (hypName == "LengthFromEdges")
147 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges *>(theHyp);
148 ASSERT(_hypLengthFromEdges);
150 aStatus = SMESH_Hypothesis::HYP_OK;
153 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
158 if (_maxElementArea > 0)
160 //_edgeLength = 2 * sqrt(_maxElementArea); // triangles : minorant
161 _edgeLength = sqrt(2. * _maxElementArea/sqrt(3.0));
165 isOk = (_hypLengthFromEdges != NULL); // **** check mode
167 aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
173 //=============================================================================
177 //=============================================================================
179 bool StdMeshers_MEFISTO_2D::Compute(SMESH_Mesh & aMesh, const TopoDS_Shape & aShape)
181 MESSAGE("StdMeshers_MEFISTO_2D::Compute");
183 TopoDS_Face F = TopoDS::Face(aShape.Oriented(TopAbs_FORWARD));
185 // helper builds quadratic mesh if necessary
186 SMESH_MesherHelper helper(aMesh);
188 _quadraticMesh = myTool->IsQuadraticSubMesh(aShape);
189 const bool ignoreMediumNodes = _quadraticMesh;
191 // get all edges of a face
193 TWireVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
194 int nbWires = wires.size();
195 if ( problem && !problem->IsOK() ) return error( problem );
196 if ( nbWires == 0 ) return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
197 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
198 return error(COMPERR_BAD_INPUT_MESH,
199 SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
201 // compute average edge length
202 if (!_hypMaxElementArea)
206 for ( int iW = 0; iW < nbWires; ++iW )
208 StdMeshers_FaceSidePtr wire = wires[ iW ];
209 _edgeLength += wire->Length();
210 nbSegments += wire->NbSegments();
213 _edgeLength /= nbSegments;
216 if (/*_hypLengthFromEdges &&*/ _edgeLength < DBL_MIN )
219 Z nblf; //nombre de lignes fermees (enveloppe en tete)
220 Z *nudslf = NULL; //numero du dernier sommet de chaque ligne fermee
222 Z nbpti = 0; //nombre points internes futurs sommets de la triangulation
231 Z nutysu = 1; // 1: il existe un fonction areteideale_()
232 // Z nutysu=0; // 0: on utilise aretmx
233 R aretmx = _edgeLength; // longueur max aretes future triangulation
237 nudslf = new Z[1 + nblf];
242 // count nb of input points
243 for ( int iW = 0; iW < nbWires; ++iW )
245 nbpnt += wires[iW]->NbPoints() - 1;
246 nudslf[iw++] = nbpnt;
249 uvslf = new R2[nudslf[nblf]];
251 double scalex, scaley;
252 ComputeScaleOnFace(aMesh, F, scalex, scaley);
254 // correspondence mefisto index --> Nodes
255 vector< const SMDS_MeshNode*> mefistoToDS(nbpnt, (const SMDS_MeshNode*)0);
259 // fill input points UV
260 if ( LoadPoints(wires, uvslf, mefistoToDS, scalex, scaley) )
263 aptrte(nutysu, aretmx,
264 nblf, nudslf, uvslf, nbpti, uvpti, nbst, uvst, nbt, nust, ierr);
268 MESSAGE("... End Triangulation Generated Triangle Number " << nbt);
269 MESSAGE(" Node Number " << nbst);
270 StoreResult(nbst, uvst, nbt, nust, mefistoToDS, scalex, scaley);
275 error(ierr,"Error in Triangulation (aptrte())");
278 if (nudslf != NULL) delete[]nudslf;
279 if (uvslf != NULL) delete[]uvslf;
280 if (uvst != NULL) delete[]uvst;
281 if (nust != NULL) delete[]nust;
286 //=======================================================================
287 //function : fixOverlappedLinkUV
288 //purpose : prevent failure due to overlapped adjacent links
289 //=======================================================================
291 static bool fixOverlappedLinkUV( R2& uv0, const R2& uv1, const R2& uv2 )
293 gp_XY v1( uv0.x - uv1.x, uv0.y - uv1.y );
294 gp_XY v2( uv2.x - uv1.x, uv2.y - uv1.y );
296 double tol2 = DBL_MIN * DBL_MIN;
297 double sqMod1 = v1.SquareModulus();
298 if ( sqMod1 <= tol2 ) return false;
299 double sqMod2 = v2.SquareModulus();
300 if ( sqMod2 <= tol2 ) return false;
304 // check sinus >= 1.e-3
305 const double minSin = 1.e-3;
306 if ( dot > 0 && 1 - dot * dot / ( sqMod1 * sqMod2 ) < minSin * minSin ) {
307 MESSAGE(" ___ FIX UV ____" << uv0.x << " " << uv0.y);
308 v1.SetCoord( -v1.Y(), v1.X() );
309 double delta = sqrt( sqMod1 ) * minSin;
319 // MESSAGE(" -> " << uv0.x << " " << uv0.y << " ");
320 // MESSAGE("v1( " << v1.X() << " " << v1.Y() << " ) " <<
321 // "v2( " << v2.X() << " " << v2.Y() << " ) ");
322 // MESSAGE("SIN: " << sqrt(1 - dot * dot / (sqMod1 * sqMod2)));
323 // v1.SetCoord( uv0.x - uv1.x, uv0.y - uv1.y );
324 // v2.SetCoord( uv2.x - uv1.x, uv2.y - uv1.y );
325 // gp_XY v3( uv2.x - uv0.x, uv2.y - uv0.y );
326 // sqMod1 = v1.SquareModulus();
327 // sqMod2 = v2.SquareModulus();
329 // double sin = sqrt(1 - dot * dot / (sqMod1 * sqMod2));
330 // MESSAGE("NEW SIN: " << sin);
337 //=======================================================================
338 //function : fixCommonVertexUV
340 //=======================================================================
342 static bool fixCommonVertexUV (R2 & theUV,
343 const TopoDS_Vertex& theV,
344 const TopoDS_Face& theF,
345 const TopTools_IndexedDataMapOfShapeListOfShape & theVWMap,
346 SMESH_Mesh & theMesh,
347 const double theScaleX,
348 const double theScaleY,
349 const bool theCreateQuadratic)
351 if( !theVWMap.Contains( theV )) return false;
353 // check if there is another wire sharing theV
354 const TopTools_ListOfShape& WList = theVWMap.FindFromKey( theV );
355 TopTools_ListIteratorOfListOfShape aWIt;
356 TopTools_MapOfShape aWires;
357 for ( aWIt.Initialize( WList ); aWIt.More(); aWIt.Next() )
358 aWires.Add( aWIt.Value() );
359 if ( aWires.Extent() < 2 ) return false;
361 TopoDS_Shape anOuterWire = BRepTools::OuterWire(theF);
362 TopoDS_Shape anInnerWire;
363 for ( aWIt.Initialize( WList ); aWIt.More() && anInnerWire.IsNull(); aWIt.Next() )
364 if ( !anOuterWire.IsSame( aWIt.Value() ))
365 anInnerWire = aWIt.Value();
367 TopTools_ListOfShape EList;
368 list< double > UList;
370 // find edges of theW sharing theV
371 // and find 2d normal to them at theV
373 TopoDS_Iterator itE( anInnerWire );
374 for ( ; itE.More(); itE.Next() )
376 const TopoDS_Edge& E = TopoDS::Edge( itE.Value() );
377 TopoDS_Iterator itV( E );
378 for ( ; itV.More(); itV.Next() )
380 const TopoDS_Vertex & V = TopoDS::Vertex( itV.Value() );
381 if ( !V.IsSame( theV ))
384 Standard_Real u = BRep_Tool::Parameter( V, E );
385 UList.push_back( u );
387 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
391 gp_Vec2d n( d1.Y() * theScaleX, -d1.X() * theScaleY);
392 if ( E.Orientation() == TopAbs_REVERSED )
398 // define step size by which to move theUV
400 gp_Pnt2d nextUV; // uv of next node on edge, most distant of the four
401 gp_Pnt2d thisUV( theUV.x, theUV.y );
402 double maxDist = -DBL_MAX;
403 TopTools_ListIteratorOfListOfShape aEIt (EList);
404 list< double >::iterator aUIt = UList.begin();
405 for ( ; aEIt.More(); aEIt.Next(), aUIt++ )
407 const TopoDS_Edge& E = TopoDS::Edge( aEIt.Value() );
409 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, theF, f, l);
411 double umin = DBL_MAX, umax = -DBL_MAX;
412 SMDS_NodeIteratorPtr nIt = theMesh.GetSubMesh(E)->GetSubMeshDS()->GetNodes();
413 if ( !nIt->more() ) // no nodes on edge, only on vertices
419 while ( nIt->more() ) {
420 const SMDS_MeshNode* node = nIt->next();
421 // check if node is medium
422 if ( theCreateQuadratic && SMESH_MesherHelper::IsMedium( node, SMDSAbs_Edge ))
424 const SMDS_EdgePosition* epos =
425 static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
426 double u = epos->GetUParameter();
433 bool isFirstCommon = ( *aUIt == f );
434 gp_Pnt2d uv = C2d->Value( isFirstCommon ? umin : umax );
435 double dist = thisUV.SquareDistance( uv );
436 if ( dist > maxDist ) {
442 uv0.x = thisUV.X(); uv0.y = thisUV.Y();
443 uv1.x = nextUV.X(); uv1.y = nextUV.Y();
444 uv2.x = thisUV.X(); uv2.y = thisUV.Y();
446 uv1.x *= theScaleX; uv1.y *= theScaleY;
448 if ( fixOverlappedLinkUV( uv0, uv1, uv2 ))
450 double step = thisUV.Distance( gp_Pnt2d( uv0.x, uv0.y ));
452 // move theUV along the normal by the step
456 MESSAGE("--fixCommonVertexUV move(" << theUV.x << " " << theUV.x
457 << ") by (" << N.X() << " " << N.Y() << ")"
458 << endl << "--- MAX DIST " << maxDist);
468 //=============================================================================
472 //=============================================================================
474 bool StdMeshers_MEFISTO_2D::LoadPoints(TWireVector & wires,
476 vector<const SMDS_MeshNode*>& mefistoToDS,
480 // to avoid passing same uv points for a vertex common to 2 wires
482 TopTools_IndexedDataMapOfShapeListOfShape VWMap;
483 if ( wires.size() > 1 )
485 F = TopoDS::Face( myTool->GetSubShape() );
486 TopExp::MapShapesAndAncestors( F, TopAbs_VERTEX, TopAbs_WIRE, VWMap );
488 for ( int iW = 0; iW < wires.size(); ++iW )
489 nbVertices += wires[ iW ]->NbEdges();
490 if ( nbVertices == VWMap.Extent() )
491 VWMap.Clear(); // wires have no common vertices
496 for ( int iW = 0; iW < wires.size(); ++iW )
498 const vector<UVPtStruct>& uvPtVec = wires[ iW ]->GetUVPtStruct();
499 if ( uvPtVec.size() != wires[ iW ]->NbPoints() ) {
500 return error(COMPERR_BAD_INPUT_MESH,SMESH_Comment("Unexpected nb of points on wire ")
501 << iW << ": " << uvPtVec.size()<<" != "<<wires[ iW ]->NbPoints()
502 << ", probably because of invalid node parameters on geom edges");
504 if ( m + uvPtVec.size()-1 > mefistoToDS.size() ) {
505 MESSAGE("Wrong mefistoToDS.size: "<<mefistoToDS.size()<<" < "<<m + uvPtVec.size()-1);
506 return error("Internal error");
509 list< int > mOnVertex;
510 vector<UVPtStruct>::const_iterator uvPt = uvPtVec.begin();
511 for ( ++uvPt; uvPt != uvPtVec.end(); ++uvPt )
513 // bind mefisto ID to node
514 mefistoToDS[m] = uvPt->node;
516 uvslf[m].x = uvPt->u * scalex;
517 uvslf[m].y = uvPt->v * scaley;
518 if ( uvPt->node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX )
519 mOnVertex.push_back( m );
523 int mFirst = mOnVertex.front(), mLast = m - 1;
524 list< int >::iterator mIt = mOnVertex.begin();
525 for ( ; mIt != mOnVertex.end(); ++mIt)
528 if ( iW && !VWMap.IsEmpty()) { // except outer wire
529 // avoid passing same uv point for a vertex common to 2 wires
530 int vID = mefistoToDS[m]->GetPosition()->GetShapeId();
531 TopoDS_Vertex V = TopoDS::Vertex( myTool->GetMeshDS()->IndexToShape( vID ));
532 if ( fixCommonVertexUV( uvslf[m], V, F, VWMap, *myTool->GetMesh(),
533 scalex, scaley, _quadraticMesh )) {
534 myNodesOnCommonV.push_back( mefistoToDS[m] );
538 // prevent failure on overlapped adjacent links,
539 // check only links ending in vertex nodes
540 int mB = m - 1, mA = m + 1; // indices Before and After
541 if ( mB < mFirst ) mB = mLast;
542 if ( mA > mLast ) mA = mFirst;
543 fixOverlappedLinkUV (uvslf[ mB ], uvslf[ m ], uvslf[ mA ]);
550 //=============================================================================
554 //=============================================================================
556 void StdMeshers_MEFISTO_2D::ComputeScaleOnFace(SMESH_Mesh & aMesh,
557 const TopoDS_Face & aFace,
561 TopoDS_Wire W = BRepTools::OuterWire(aFace);
563 double xmin = 1.e300; // min & max of face 2D parametric coord.
564 double xmax = -1.e300;
565 double ymin = 1.e300;
566 double ymax = -1.e300;
571 TopExp_Explorer wexp(W, TopAbs_EDGE);
572 for ( ; wexp.More(); wexp.Next())
574 const TopoDS_Edge & E = TopoDS::Edge( wexp.Current() );
576 Handle(Geom2d_Curve) C2d = BRep_Tool::CurveOnSurface(E, aFace, f, l);
577 if ( C2d.IsNull() ) continue;
578 double du = (l - f) / double (nbp);
579 for (int i = 0; i <= nbp; i++)
581 double param = f + double (i) * du;
582 gp_Pnt2d p = C2d->Value(param);
591 // MESSAGE(" "<< f<<" "<<l<<" "<<param<<" "<<xmin<<" "<<xmax<<" "<<ymin<<" "<<ymax);
598 double xmoy = (xmax + xmin) / 2.;
599 double ymoy = (ymax + ymin) / 2.;
600 double xsize = xmax - xmin;
601 double ysize = ymax - ymin;
604 Handle(Geom_Surface) S = BRep_Tool::Surface(aFace,L); // 3D surface
608 gp_Pnt PX0 = S->Value(xmin, ymoy);
609 gp_Pnt PY0 = S->Value(xmoy, ymin);
610 double dx = xsize / double (nbp);
611 double dy = ysize / double (nbp);
612 for (int i = 1; i <= nbp; i++)
614 double x = xmin + double (i) * dx;
615 gp_Pnt PX = S->Value(x, ymoy);
616 double y = ymin + double (i) * dy;
617 gp_Pnt PY = S->Value(xmoy, y);
618 length_x += PX.Distance(PX0);
619 length_y += PY.Distance(PY0);
623 scalex = length_x / xsize;
624 scaley = length_y / ysize;
627 double xyratio = xsize*scalex/(ysize*scaley);
628 const double maxratio = 1.e2;
630 if (xyratio > maxratio) {
632 scaley *= xyratio / maxratio;
635 else if (xyratio < 1./maxratio) {
637 scalex *= 1 / xyratio / maxratio;
644 //=============================================================================
648 //=============================================================================
650 void StdMeshers_MEFISTO_2D::StoreResult(Z nbst, R2 * uvst, Z nbt, Z * nust,
651 vector< const SMDS_MeshNode*>&mefistoToDS,
652 double scalex, double scaley)
654 SMESHDS_Mesh * meshDS = myTool->GetMeshDS();
655 int faceID = myTool->GetSubShapeID();
657 TopoDS_Face F = TopoDS::Face( myTool->GetSubShape() );
658 Handle(Geom_Surface) S = BRep_Tool::Surface( F );
660 Z n = mefistoToDS.size(); // nb input points
661 mefistoToDS.resize( nbst );
662 for ( ; n < nbst; n++)
666 double u = uvst[n][0] / scalex;
667 double v = uvst[n][1] / scaley;
668 gp_Pnt P = S->Value(u, v);
670 SMDS_MeshNode * node = meshDS->AddNode(P.X(), P.Y(), P.Z());
671 meshDS->SetNodeOnFace(node, faceID, u, v);
673 //MESSAGE(P.X()<<" "<<P.Y()<<" "<<P.Z());
674 mefistoToDS[n] = node;
675 //MESSAGE("NEW: "<<n<<" "<<mefistoToDS[n+1]);
681 // triangle points must be in trigonometric order if face is Forward
682 // else they must be put clockwise
684 bool triangleIsWellOriented = ( F.Orientation() == TopAbs_FORWARD );
686 for (n = 1; n <= nbt; n++)
688 const SMDS_MeshNode * n1 = mefistoToDS[ nust[m++] - 1 ];
689 const SMDS_MeshNode * n2 = mefistoToDS[ nust[m++] - 1 ];
690 const SMDS_MeshNode * n3 = mefistoToDS[ nust[m++] - 1 ];
692 SMDS_MeshElement * elt;
693 if (triangleIsWellOriented)
694 elt = myTool->AddFace(n1, n2, n3);
696 elt = myTool->AddFace(n1, n3, n2);
698 meshDS->SetMeshElementOnShape(elt, faceID);
702 // remove bad elements built on vertices shared by wires
704 list<const SMDS_MeshNode*>::iterator itN = myNodesOnCommonV.begin();
705 for ( ; itN != myNodesOnCommonV.end(); itN++ )
707 const SMDS_MeshNode* node = *itN;
708 SMDS_ElemIteratorPtr invElemIt = node->GetInverseElementIterator();
709 while ( invElemIt->more() )
711 const SMDS_MeshElement* elem = invElemIt->next();
712 SMDS_ElemIteratorPtr itN = elem->nodesIterator();
714 while ( itN->more() )
715 if ( itN->next() == node)
718 MESSAGE( "RM bad element " << elem->GetID());
719 meshDS->RemoveElement( elem );