1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : NETGENPlugin_NETGEN_2D_ONLY.cxx
21 // Author : Edward AGAPOV (OCC)
24 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
26 #include "NETGENPlugin_Mesher.hxx"
27 #include "NETGENPlugin_Hypothesis_2D.hxx"
29 #include <SMDS_MeshElement.hxx>
30 #include <SMDS_MeshNode.hxx>
31 #include <SMESHDS_Mesh.hxx>
32 #include <SMESH_Comment.hxx>
33 #include <SMESH_Gen.hxx>
34 #include <SMESH_Mesh.hxx>
35 #include <SMESH_MesherHelper.hxx>
36 #include <SMESH_subMesh.hxx>
37 #include <StdMeshers_FaceSide.hxx>
38 #include <StdMeshers_LengthFromEdges.hxx>
39 #include <StdMeshers_MaxElementArea.hxx>
40 #include <StdMeshers_QuadranglePreference.hxx>
41 #include <StdMeshers_ViscousLayers2D.hxx>
43 #include <Precision.hxx>
44 #include <Standard_ErrorHandler.hxx>
45 #include <Standard_Failure.hxx>
47 #include <utilities.h>
62 #include <occgeom.hpp>
63 #include <meshing.hpp>
64 //#include <meshtype.hpp>
67 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
69 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
71 extern MeshingParameters mparam;
72 extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
76 using namespace netgen;
77 using namespace nglib;
79 //=============================================================================
83 //=============================================================================
85 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId,
88 : SMESH_2D_Algo(hypId, studyId, gen)
90 _name = "NETGEN_2D_ONLY";
92 _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
93 _onlyUnaryInput = false; // treat all FACEs at once
95 _compatibleHypothesis.push_back("MaxElementArea");
96 _compatibleHypothesis.push_back("LengthFromEdges");
97 _compatibleHypothesis.push_back("QuadranglePreference");
98 _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
99 _compatibleHypothesis.push_back("ViscousLayers2D");
101 _hypMaxElementArea = 0;
102 _hypLengthFromEdges = 0;
103 _hypQuadranglePreference = 0;
107 //=============================================================================
111 //=============================================================================
113 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
115 MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
118 //=============================================================================
122 //=============================================================================
124 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh& aMesh,
125 const TopoDS_Shape& aShape,
126 Hypothesis_Status& aStatus)
128 _hypMaxElementArea = 0;
129 _hypLengthFromEdges = 0;
130 _hypQuadranglePreference = 0;
134 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
138 aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
139 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
142 aStatus = HYP_MISSING;
145 list<const SMESHDS_Hypothesis*>::const_iterator ith;
146 for (ith = hyps.begin(); ith != hyps.end(); ++ith )
148 const SMESHDS_Hypothesis* hyp = (*ith);
150 string hypName = hyp->GetName();
152 if ( hypName == "MaxElementArea")
153 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
154 else if ( hypName == "LengthFromEdges" )
155 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
156 else if ( hypName == "QuadranglePreference" )
157 _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
158 else if ( hypName == "NETGEN_Parameters_2D" )
159 _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
160 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
163 aStatus = HYP_INCOMPATIBLE;
168 int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
170 aStatus = HYP_CONCURENT;
172 error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus ));
176 if ( aStatus == HYP_OK && _hypParameters && _hypQuadranglePreference )
178 aStatus = HYP_INCOMPAT_HYPS;
179 return error(SMESH_Comment("\"") << _hypQuadranglePreference->GetName()
180 << "\" and \"" << _hypParameters->GetName()
181 << "\" are incompatible hypotheses");
184 return ( aStatus == HYP_OK );
187 //=============================================================================
189 *Here we are going to use the NETGEN mesher
191 //=============================================================================
193 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
194 const TopoDS_Shape& aShape)
196 netgen::multithread.terminate = 0;
197 //netgen::multithread.task = "Surface meshing";
199 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
200 SMESH_MesherHelper helper(aMesh);
201 helper.SetElementsOnShape( true );
203 NETGENPlugin_NetgenLibWrapper ngLib;
204 ngLib._isComputeOk = false;
206 netgen::Mesh ngMeshNoLocSize;
207 netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh, & ngMeshNoLocSize };
208 netgen::OCCGeometry occgeoComm;
210 // min / max sizes are set as follows:
211 // if ( _hypParameters )
212 // min and max are defined by the user
213 // else if ( _hypLengthFromEdges )
214 // min = aMesher.GetDefaultMinSize()
215 // max = average segment len of a FACE
216 // else if ( _hypMaxElementArea )
217 // min = aMesher.GetDefaultMinSize()
218 // max = f( _hypMaxElementArea )
220 // min = aMesher.GetDefaultMinSize()
221 // max = max segment len of a FACE
223 NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
224 aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
225 const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
226 if ( _hypMaxElementArea )
228 netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
231 // local size is common for all FACEs in aShape?
232 const bool isCommonLocalSize = ( !_hypLengthFromEdges && netgen::mparam.uselocalh );
233 const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
235 if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
237 //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
238 aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
240 // local size set at MESHCONST_ANALYSE step depends on
241 // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
242 if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
244 if ( !_hypMaxElementArea )
245 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
246 netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
248 // set local size depending on curvature and NOT closeness of EDGEs
249 netgen::occparam.resthcloseedgeenable = false;
250 //netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
251 occgeoComm.face_maxh = netgen::mparam.maxh;
252 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
253 occgeoComm.emap.Clear();
254 occgeoComm.vmap.Clear();
256 // set local size according to size of existing segments
257 const double factor = netgen::occparam.resthcloseedgefac;
258 TopTools_IndexedMapOfShape edgeMap;
259 TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
260 for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
262 const TopoDS_Shape& edge = edgeMap( iE );
263 if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge ))/* ||
264 helper.IsSubShape( edge, aShape )*/)
266 SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
267 if ( !smDS ) continue;
268 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
269 while ( segIt->more() )
271 const SMDS_MeshElement* seg = segIt->next();
272 SMESH_TNodeXYZ n1 = seg->GetNode(0);
273 SMESH_TNodeXYZ n2 = seg->GetNode(1);
274 gp_XYZ p = 0.5 * ( n1 + n2 );
275 netgen::Point3d pi(p.X(), p.Y(), p.Z());
276 ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
280 netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
282 // ==================
284 // ==================
286 vector< const SMDS_MeshNode* > nodeVec;
288 TopExp_Explorer fExp( aShape, TopAbs_FACE );
289 for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
291 TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
292 int faceID = meshDS->ShapeToIndex( aShape );
293 SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
295 _quadraticMesh = helper.IsQuadraticSubMesh( F );
296 const bool ignoreMediumNodes = _quadraticMesh;
298 // build viscous layers if required
299 if ( F.Orientation() != TopAbs_FORWARD &&
300 F.Orientation() != TopAbs_REVERSED )
301 F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
302 SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
306 // ------------------------
307 // get all EDGEs of a FACE
308 // ------------------------
310 StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, proxyMesh );
311 if ( faceErr && !faceErr->IsOK() )
313 int nbWires = wires.size();
317 ( new SMESH_ComputeError
318 ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
321 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
324 ( new SMESH_ComputeError
325 ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
329 // ----------------------
330 // compute maxh of a FACE
331 // ----------------------
333 if ( !_hypParameters )
335 double edgeLength = 0;
336 if (_hypLengthFromEdges )
338 // compute edgeLength as an average segment length
340 for ( int iW = 0; iW < nbWires; ++iW )
342 edgeLength += wires[ iW ]->Length();
343 nbSegments += wires[ iW ]->NbSegments();
346 edgeLength /= nbSegments;
347 netgen::mparam.maxh = edgeLength;
349 else if ( isDefaultHyp )
351 // set edgeLength by a longest segment
353 for ( int iW = 0; iW < nbWires; ++iW )
355 const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
356 gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
357 for ( size_t i = 1; i < points.size(); ++i )
359 gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
360 maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
364 edgeLength = sqrt( maxSeg2 ) * 1.05;
365 netgen::mparam.maxh = edgeLength;
367 if ( netgen::mparam.maxh < DBL_MIN )
368 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
370 if ( !isCommonLocalSize )
372 netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
377 netgen::OCCGeometry occgeom;
379 occgeom.fmap.Add( F );
380 occgeom.CalcBoundingBox();
381 occgeom.facemeshstatus.SetSize(1);
382 occgeom.facemeshstatus = 0;
383 occgeom.face_maxh_modified.SetSize(1);
384 occgeom.face_maxh_modified = 0;
385 occgeom.face_maxh.SetSize(1);
386 occgeom.face_maxh = netgen::mparam.maxh;
388 // -------------------------
390 // -------------------------
392 // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
393 // w/o MESHCONST_ANALYSE at the second loop
395 enum { LOC_SIZE, NO_LOC_SIZE };
396 int iLoop = isCommonLocalSize ? 0 : 1;
397 for ( ; iLoop < 2; iLoop++ )
399 //bool isMESHCONST_ANALYSE = false;
402 netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
403 ngMesh->DeleteMesh();
405 if ( iLoop == NO_LOC_SIZE )
407 ngMesh->SetGlobalH ( mparam.maxh );
408 ngMesh->SetMinimalH( mparam.minh );
409 Box<3> bb = occgeom.GetBoundingBox();
410 bb.Increase (bb.Diam()/10);
411 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparam.grading);
415 faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
416 /*overrideMinH=*/!_hypParameters);
417 if ( faceErr && !faceErr->IsOK() )
420 // -------------------------
421 // Generate surface mesh
422 // -------------------------
424 const int startWith = MESHCONST_MESHSURFACE;
425 const int endWith = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
432 err = netgen::OCCGenerateMesh(occgeom, ngMesh, netgen::mparam, startWith, endWith);
435 err = netgen::OCCGenerateMesh(occgeom, ngMesh, startWith, endWith, optstr);
437 if ( netgen::multithread.terminate )
440 str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
442 catch (Standard_Failure& ex)
445 str << "Exception in netgen::OCCGenerateMesh()"
446 << " at " << netgen::multithread.task
447 << ": " << ex.DynamicType()->Name();
448 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
449 str << ": " << ex.GetMessageString();
453 str << "Exception in netgen::OCCGenerateMesh()"
454 << " at " << netgen::multithread.task;
458 if ( iLoop == LOC_SIZE )
460 netgen::mparam.minh = netgen::mparam.maxh;
461 netgen::mparam.maxh = 0;
462 for ( int iW = 0; iW < wires.size(); ++iW )
464 StdMeshers_FaceSidePtr wire = wires[ iW ];
465 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
466 for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
468 SMESH_TNodeXYZ p( uvPtVec[ iP ].node );
469 netgen::Point3d np( p.X(),p.Y(),p.Z());
470 double segLen = p.Distance( uvPtVec[ iP-1 ].node );
471 double size = ngMesh->GetH( np );
472 netgen::mparam.minh = Min( netgen::mparam.minh, size );
473 netgen::mparam.maxh = Max( netgen::mparam.maxh, segLen );
476 //cerr << "min " << netgen::mparam.minh << " max " << netgen::mparam.maxh << endl;
477 netgen::mparam.minh *= 0.9;
478 netgen::mparam.maxh *= 1.1;
483 faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
488 // ----------------------------------------------------
489 // Fill the SMESHDS with the generated nodes and faces
490 // ----------------------------------------------------
492 int nbNodes = ngMesh->GetNP();
493 int nbFaces = ngMesh->GetNSE();
495 int nbInputNodes = nodeVec.size()-1;
496 nodeVec.resize( nbNodes+1, 0 );
499 for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
501 const MeshPoint& ngPoint = ngMesh->Point( ngID );
502 SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
503 nodeVec[ ngID ] = node;
508 vector<const SMDS_MeshNode*> nodes;
509 for ( i = 1; i <= nbFaces ; ++i )
511 const Element2d& elem = ngMesh->SurfaceElement(i);
512 nodes.resize( elem.GetNP() );
513 for (j=1; j <= elem.GetNP(); ++j)
515 int pind = elem.PNum(j);
518 nodes[ j-1 ] = nodeVec[ pind ];
519 if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
521 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
522 meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
525 if ( j > elem.GetNP() )
527 SMDS_MeshFace* face = 0;
528 if ( elem.GetType() == TRIG )
529 face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
531 face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
542 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
544 SMESH_Algo::CancelCompute();
545 netgen::multithread.terminate = 1;
548 //================================================================================
550 * \brief Return progress of Compute() [0.,1]
552 //================================================================================
554 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
557 // const char* task1 = "Surface meshing";
558 // //const char* task2 = "Optimizing surface";
559 // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
560 // if ( _progressByTic < 0. &&
561 // strncmp( netgen::multithread.task, task1, 3 ) == 0 )
563 // progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
565 // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
567 // if ( _progressByTic < 0 )
569 // NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
570 // me->_progressByTic = 0.25 / (_progressTic+1);
572 // const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
573 // progress = Max( progress, _progressByTic * _progressTic );
575 // //cout << netgen::multithread.task << " " << _progressTic << endl;
576 // return Min( progress, 0.99 );
579 //=============================================================================
583 //=============================================================================
585 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
586 const TopoDS_Shape& aShape,
587 MapShapeNbElems& aResMap)
589 TopoDS_Face F = TopoDS::Face(aShape);
593 // collect info from edges
594 int nb0d = 0, nb1d = 0;
595 bool IsQuadratic = false;
597 double fullLen = 0.0;
598 TopTools_MapOfShape tmpMap;
599 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
600 TopoDS_Edge E = TopoDS::Edge(exp.Current());
601 if( tmpMap.Contains(E) )
604 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
605 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
606 if( anIt==aResMap.end() ) {
607 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
608 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
609 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
612 std::vector<int> aVec = (*anIt).second;
613 nb0d += aVec[SMDSEntity_Node];
614 nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
615 double aLen = SMESH_Algo::EdgeLength(E);
618 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
624 // compute edge length
626 if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
628 ELen = fullLen / nb1d;
630 if ( _hypMaxElementArea ) {
631 double maxArea = _hypMaxElementArea->GetMaxArea();
632 ELen = sqrt(2. * maxArea/sqrt(3.0));
635 BRepGProp::SurfaceProperties(F,G);
636 double anArea = G.Mass();
638 const int hugeNb = numeric_limits<int>::max()/10;
639 if ( anArea / hugeNb > ELen*ELen )
641 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
642 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
643 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
646 int nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
647 int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
648 std::vector<int> aVec(SMDSEntity_Last);
649 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
651 aVec[SMDSEntity_Node] = nbNodes;
652 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
655 aVec[SMDSEntity_Node] = nbNodes;
656 aVec[SMDSEntity_Triangle] = nbFaces;
658 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
659 aResMap.insert(std::make_pair(sm,aVec));