]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
+ virtual double GetProgress() const;
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
1 // Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
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.
7 //
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.
12 //
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
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // File      : NETGENPlugin_NETGEN_2D_ONLY.cxx
21 // Author    : Edward AGAPOV (OCC)
22 // Project   : SALOME
23 //
24 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
25
26 #include "NETGENPlugin_Mesher.hxx"
27 #include "NETGENPlugin_Hypothesis_2D.hxx"
28
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>
42
43 #include <Precision.hxx>
44 #include <Standard_ErrorHandler.hxx>
45 #include <Standard_Failure.hxx>
46
47 #include <utilities.h>
48
49 #include <list>
50 #include <vector>
51 #include <limits>
52
53 /*
54   Netgen include files
55 */
56 namespace nglib {
57 #include <nglib.h>
58 }
59 #ifndef OCCGEOMETRY
60 #define OCCGEOMETRY
61 #endif
62 #include <occgeom.hpp>
63 #include <meshing.hpp>
64 //#include <meshtype.hpp>
65 namespace netgen {
66 #ifdef NETGEN_V5
67   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
68 #else
69   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
70 #endif
71   extern MeshingParameters mparam;
72 }
73
74 using namespace std;
75 using namespace netgen;
76 using namespace nglib;
77
78 //#define DUMP_SEGMENTS
79
80 //=============================================================================
81 /*!
82  *  
83  */
84 //=============================================================================
85
86 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
87                                                          SMESH_Gen* gen)
88   : SMESH_2D_Algo(hypId, studyId, gen)
89 {
90   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
91   _name = "NETGEN_2D_ONLY";
92   
93   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
94
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");
100
101   _hypMaxElementArea = 0;
102   _hypLengthFromEdges = 0;
103   _hypQuadranglePreference = 0;
104   _hypParameters = 0;
105 }
106
107 //=============================================================================
108 /*!
109  *  
110  */
111 //=============================================================================
112
113 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
114 {
115   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
116 }
117
118 //=============================================================================
119 /*!
120  *  
121  */
122 //=============================================================================
123
124 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
125                                                    const TopoDS_Shape& aShape,
126                                                    Hypothesis_Status&  aStatus)
127 {
128   _hypMaxElementArea = 0;
129   _hypLengthFromEdges = 0;
130   _hypQuadranglePreference = 0;
131   _isSurfaceMeshing = true;
132
133   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
134
135   if (hyps.empty())
136   {
137     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
138     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
139   }
140
141   aStatus = HYP_MISSING;
142
143   list<const SMESHDS_Hypothesis*>::const_iterator ith;
144   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
145   {
146     const SMESHDS_Hypothesis* hyp = (*ith);
147
148     string hypName = hyp->GetName();
149
150     if      ( hypName == "MaxElementArea")
151       _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
152     else if ( hypName == "LengthFromEdges" )
153       _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
154     else if ( hypName == "QuadranglePreference" )
155       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
156     else if ( hypName == "NETGEN_Parameters_2D" )
157       _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
158     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
159       continue;
160     else {
161       aStatus = HYP_INCOMPATIBLE;
162       return false;
163     }
164   }
165
166   int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
167   if ( nbHyps > 1 )
168     aStatus = HYP_CONCURENT;
169   else
170     aStatus = HYP_OK;
171
172   return ( aStatus == HYP_OK );
173 }
174
175 //=============================================================================
176 /*!
177  *Here we are going to use the NETGEN mesher
178  */
179 //=============================================================================
180
181 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
182                                           const TopoDS_Shape& aShape)
183 {
184   netgen::multithread.terminate = 0;
185   netgen::multithread.task = "Surface meshing";
186
187   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
188   int faceID = meshDS->ShapeToIndex( aShape );
189
190   SMESH_MesherHelper helper(aMesh);
191   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
192   helper.SetElementsOnShape( true );
193   const bool ignoreMediumNodes = _quadraticMesh;
194   
195   // build viscous layers if required
196   const TopoDS_Face F = TopoDS::Face( aShape/*.Oriented( TopAbs_FORWARD )*/);
197   SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
198   if ( !proxyMesh )
199     return false;
200
201   // ------------------------
202   // get all edges of a face
203   // ------------------------
204   TError problem;
205   TSideVector wires =
206     StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem, proxyMesh );
207   if ( problem && !problem->IsOK() )
208     return error( problem );
209   int nbWires = wires.size();
210   if ( nbWires == 0 )
211     return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
212   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
213     return error(COMPERR_BAD_INPUT_MESH,
214                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
215
216   // --------------------
217   // compute edge length
218   // --------------------
219
220   NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
221   netgen::OCCGeometry occgeo;
222   aMesher.PrepareOCCgeometry( occgeo, F, aMesh );
223   occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
224   occgeo.fmap.Add( F );
225
226   if ( _hypParameters )
227   {
228     aMesher.SetParameters(_hypParameters);
229   }
230   else
231   {
232     double edgeLength = 0;
233     if (_hypLengthFromEdges || (!_hypLengthFromEdges && !_hypMaxElementArea))
234     {
235       int nbSegments = 0;
236       for ( int iW = 0; iW < nbWires; ++iW )
237       {
238         edgeLength += wires[ iW ]->Length();
239         nbSegments += wires[ iW ]->NbSegments();
240       }
241       if ( nbSegments )
242         edgeLength /= nbSegments;
243     }
244     if ( _hypMaxElementArea )
245     {
246       double maxArea = _hypMaxElementArea->GetMaxArea();
247       edgeLength = sqrt(2. * maxArea/sqrt(3.0));
248     }
249     if ( edgeLength < DBL_MIN )
250       edgeLength = occgeo.GetBoundingBox().Diam();
251
252     netgen::mparam.maxh = edgeLength;
253     netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
254     netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
255     netgen::mparam.grading = 0.7; // very coarse mesh by default
256   }
257   occgeo.face_maxh = netgen::mparam.maxh;
258
259   // -------------------------
260   // Make input netgen mesh
261   // -------------------------
262
263   NETGENPlugin_NetgenLibWrapper ngLib;
264   netgen::Mesh * ngMesh = (netgen::Mesh*) ngLib._ngMesh;
265
266   Box<3> bb = occgeo.GetBoundingBox();
267   bb.Increase (bb.Diam()/10);
268   ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
269   ngMesh->SetGlobalH (netgen::mparam.maxh);
270
271   vector< const SMDS_MeshNode* > nodeVec;
272   problem = aMesher.AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
273   if ( problem && !problem->IsOK() )
274     return error( problem );
275
276   // -------------------------
277   // Generate surface mesh
278   // -------------------------
279
280 #ifndef NETGEN_V5
281   char *optstr = 0;
282 #endif
283   int startWith = MESHCONST_MESHSURFACE;
284   int endWith   = MESHCONST_OPTSURFACE;
285   int err = 1;
286
287   try {
288 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
289     OCC_CATCH_SIGNALS;
290 #endif
291 #ifdef NETGEN_V5
292     err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
293 #else
294     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
295 #endif
296     if(netgen::multithread.terminate)
297       return false;
298     if ( err )
299       error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
300   }
301   catch (Standard_Failure& ex)
302   {
303     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
304     str << " at " << netgen::multithread.task
305         << ": " << ex.DynamicType()->Name();
306     if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
307       str << ": " << ex.GetMessageString();
308     error(str);
309   }
310   catch (...) {
311     SMESH_Comment str("Exception in  netgen::OCCGenerateMesh()");
312     str << " at " << netgen::multithread.task;
313     error(str);
314   }
315
316   // ----------------------------------------------------
317   // Fill the SMESHDS with the generated nodes and faces
318   // ----------------------------------------------------
319
320   int nbNodes = ngMesh->GetNP();
321   int nbFaces = ngMesh->GetNSE();
322
323   int nbInputNodes = nodeVec.size()-1;
324   nodeVec.resize( nbNodes+1, 0 );
325
326   // add nodes
327   for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
328   {
329     const MeshPoint& ngPoint = ngMesh->Point( ngID );
330     SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
331     nodeVec[ ngID ] = node;
332   }
333
334   // create faces
335   const bool reverse = false; //( aShape.Orientation() == TopAbs_REVERSED );
336   int i,j;
337   for ( i = 1; i <= nbFaces ; ++i )
338   {
339     const Element2d& elem = ngMesh->SurfaceElement(i);
340     vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
341     for (j=1; j <= elem.GetNP(); ++j)
342     {
343       int pind = elem.PNum(j);
344       if ( pind < 1 )
345         break;
346       const SMDS_MeshNode* node = nodeVec[ pind ];
347       if ( reverse )
348         nodes[ nodes.size()-j ] = node;
349       else
350         nodes[ j-1 ] = node;
351       if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
352       {
353         const PointGeomInfo& pgi = elem.GeomInfoPi(j);
354         meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
355       }
356     }
357     if ( j > elem.GetNP() )
358     {
359       SMDS_MeshFace* face = 0;
360       if ( elem.GetType() == TRIG )
361         face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
362       else
363         face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
364     }
365   }
366
367   ngLib._isComputeOk = !err;
368   return !err;
369 }
370
371 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
372 {
373   SMESH_Algo::CancelCompute();
374   netgen::multithread.terminate = 1;
375 }
376
377 //================================================================================
378 /*!
379  * \brief Return progress of Compute() [0.,1]
380  */
381 //================================================================================
382
383 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
384 {
385   const char* task1 = "Surface meshing";
386   const char* task2 = "Optimizing surface";
387   double res = 0;
388   if ( _isSurfaceMeshing &&
389        strncmp( netgen::multithread.task, task1, 3 ) == 0 )
390   {
391     res = 0.3 * SMESH_Algo::GetProgressByTic(); // [0, 0.3]
392   }
393   else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
394   {
395     if ( _isSurfaceMeshing )
396     {
397       NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
398       me->_isSurfaceMeshing = false;
399       me->_progressTic = 0; // to re-start GetProgressByTic() from 0.
400     }
401     res = 0.3 + 0.7 * SMESH_Algo::GetProgressByTic(); // [0.3, 1.]
402   }
403   //cout << netgen::multithread.task << " " <<res << endl;
404   return res;
405 }
406
407 //=============================================================================
408 /*!
409  *
410  */
411 //=============================================================================
412
413 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
414                                            const TopoDS_Shape& aShape,
415                                            MapShapeNbElems& aResMap)
416 {
417   TopoDS_Face F = TopoDS::Face(aShape);
418   if(F.IsNull())
419     return false;
420
421   // collect info from edges
422   int nb0d = 0, nb1d = 0;
423   bool IsQuadratic = false;
424   bool IsFirst = true;
425   double fullLen = 0.0;
426   TopTools_MapOfShape tmpMap;
427   for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
428     TopoDS_Edge E = TopoDS::Edge(exp.Current());
429     if( tmpMap.Contains(E) )
430       continue;
431     tmpMap.Add(E);
432     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
433     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
434     if( anIt==aResMap.end() ) {
435       SMESH_subMesh *sm = aMesh.GetSubMesh(F);
436       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
437       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
438       return false;
439     }
440     std::vector<int> aVec = (*anIt).second;
441     nb0d += aVec[SMDSEntity_Node];
442     nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
443     double aLen = SMESH_Algo::EdgeLength(E);
444     fullLen += aLen;
445     if(IsFirst) {
446       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
447       IsFirst = false;
448     }
449   }
450   tmpMap.Clear();
451
452   // compute edge length
453   double ELen = 0;
454   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
455     if ( nb1d > 0 )
456       ELen = fullLen / nb1d;
457   }
458   if ( _hypMaxElementArea ) {
459     double maxArea = _hypMaxElementArea->GetMaxArea();
460     ELen = sqrt(2. * maxArea/sqrt(3.0));
461   }
462   GProp_GProps G;
463   BRepGProp::SurfaceProperties(F,G);
464   double anArea = G.Mass();
465
466   const int hugeNb = numeric_limits<int>::max()/10;
467   if ( anArea / hugeNb > ELen*ELen )
468   {
469     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
470     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
471     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
472     return false;
473   }
474   int nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
475   int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
476   std::vector<int> aVec(SMDSEntity_Last);
477   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
478   if( IsQuadratic ) {
479     aVec[SMDSEntity_Node] = nbNodes;
480     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
481   }
482   else {
483     aVec[SMDSEntity_Node] = nbNodes;
484     aVec[SMDSEntity_Triangle] = nbFaces;
485   }
486   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
487   aResMap.insert(std::make_pair(sm,aVec));
488
489   return true;
490 }