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