]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
Netgen 4.9.11 compatibility
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
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.
10 //
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.
15 //
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
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 // File      : NETGENPlugin_NETGEN_2D_ONLY.cxx
23 // Author    : Edward AGAPOV (OCC)
24 // Project   : SALOME
25 //
26 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
27
28 #include "NETGENPlugin_Mesher.hxx"
29
30 #include "SMDS_MeshElement.hxx"
31 #include "SMDS_MeshNode.hxx"
32 #include "SMESHDS_Mesh.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_Gen.hxx"
35 #include "SMESH_Mesh.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "StdMeshers_FaceSide.hxx"
38 #include "StdMeshers_MaxElementArea.hxx"
39 #include "StdMeshers_LengthFromEdges.hxx"
40 #include "StdMeshers_QuadranglePreference.hxx"
41
42 #include <Precision.hxx>
43 #include <Standard_ErrorHandler.hxx>
44 #include <Standard_Failure.hxx>
45
46 #include "utilities.h"
47
48 #include <list>
49 #include <vector>
50
51 /*
52   Netgen include files
53 */
54 namespace nglib {
55 #include <nglib.h>
56 }
57 #define OCCGEOMETRY
58 #include <occgeom.hpp>
59 #include <meshing.hpp>
60 //#include <meshtype.hpp>
61 namespace netgen {
62   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
63   /*extern*/ MeshingParameters mparam;
64 }
65
66 using namespace std;
67 using namespace netgen;
68 using namespace nglib;
69
70 //=============================================================================
71 /*!
72  *  
73  */
74 //=============================================================================
75
76 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
77                                                          SMESH_Gen* gen)
78   : SMESH_2D_Algo(hypId, studyId, gen)
79 {
80   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
81   _name = "NETGEN_2D_ONLY";
82   
83   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
84
85   _compatibleHypothesis.push_back("MaxElementArea");
86   _compatibleHypothesis.push_back("LengthFromEdges");
87   _compatibleHypothesis.push_back("QuadranglePreference");
88
89   _hypMaxElementArea = 0;
90   _hypLengthFromEdges = 0;
91   _hypQuadranglePreference = 0;
92 }
93
94 //=============================================================================
95 /*!
96  *  
97  */
98 //=============================================================================
99
100 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
101 {
102   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
103 }
104
105 //=============================================================================
106 /*!
107  *  
108  */
109 //=============================================================================
110
111 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
112                                                    const TopoDS_Shape& aShape,
113                                                    Hypothesis_Status&  aStatus)
114 {
115   _hypMaxElementArea = 0;
116   _hypLengthFromEdges = 0;
117   _hypQuadranglePreference = 0;
118
119   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
120
121   if (hyps.empty())
122   {
123     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
124     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
125   }
126
127   aStatus = HYP_MISSING;
128
129   list<const SMESHDS_Hypothesis*>::const_iterator ith;
130   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
131   {
132     const SMESHDS_Hypothesis* hyp = (*ith);
133
134     string hypName = hyp->GetName();
135
136     if      ( hypName == "MaxElementArea")
137       _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
138     else if ( hypName == "LengthFromEdges" )
139       _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
140     else if ( hypName == "QuadranglePreference" )
141       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
142     else {
143       aStatus = HYP_INCOMPATIBLE;
144       return false;
145     }
146   }
147
148   if ( _hypMaxElementArea && _hypLengthFromEdges ) {
149     aStatus = HYP_CONCURENT;
150     return false;
151   }
152
153   if ( _hypMaxElementArea || _hypLengthFromEdges )
154     aStatus = HYP_OK;
155
156   return aStatus == HYP_OK;
157 }
158
159 //================================================================================
160 /*!
161  * \brief Fill netgen mesh with segments
162   * \retval SMESH_ComputeErrorPtr - error description
163  */
164 //================================================================================
165
166 static TError AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
167                                 OCCGeometry&                     geom,
168                                 const TSideVector&               wires,
169                                 SMESH_MesherHelper&              helper,
170                                 vector< const SMDS_MeshNode* > & nodeVec)
171 {
172   // ----------------------------
173   // Check wires and count nodes
174   // ----------------------------
175   int nbNodes = 0;
176   for ( int iW = 0; iW < wires.size(); ++iW )
177   {
178     StdMeshers_FaceSidePtr wire = wires[ iW ];
179     if ( wire->MissVertexNode() )
180       return TError
181         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
182       
183     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
184     if ( uvPtVec.size() != wire->NbPoints() )
185       return TError
186         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,
187                                 SMESH_Comment("Unexpected nb of points on wire ") << iW
188                                 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints()));
189     nbNodes += wire->NbSegments();
190   }
191   nodeVec.reserve( nbNodes );
192
193   // -----------------
194   // Fill netgen mesh
195   // -----------------
196
197 //   netgen::Box<3> bb = geom.GetBoundingBox();
198 //   bb.Increase (bb.Diam()/10);
199 //   ngMesh.SetLocalH (bb.PMin(), bb.PMax(), 0.5); // set grading
200
201   const int faceID = 1, solidID = 0;
202   ngMesh.AddFaceDescriptor (FaceDescriptor(faceID, solidID, solidID, 0));
203
204   for ( int iW = 0; iW < wires.size(); ++iW )
205   {
206     StdMeshers_FaceSidePtr wire = wires[ iW ];
207     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
208
209     bool reverse = // 20526: [CEA] Disk meshing fails
210       ( wire->NbEdges() == 1 && 
211         geom.emap(geom.emap.FindIndex(wire->Edge(0))).Orientation() == TopAbs_REVERSED );
212
213     int firstPointID = ngMesh.GetNP() + 1;
214     int edgeID = 1, posID = -2;
215     for ( int i = 0; i < wire->NbSegments(); ++i ) // loop on segments
216     {
217       // Add the first point of a segment
218       const SMDS_MeshNode * n = uvPtVec[ i ].node;
219       const int posShapeID = n->GetPosition()->GetShapeId();
220
221       // skip nodes on degenerated edges
222       if ( helper.IsDegenShape( posShapeID ) &&
223            helper.IsDegenShape( uvPtVec[ i+1 ].node->GetPosition()->GetShapeId() ))
224         continue;
225
226       nodeVec.push_back( n );
227
228       MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
229       ngMesh.AddPoint ( mp, 1, EDGEPOINT );
230
231       // Add the segment
232       Segment seg;
233
234 #ifdef NETGEN_NEW
235       seg.pnums[0] = ngMesh.GetNP();          // ng node id
236       seg.pnums[1] = seg.pnums[0] + 1;              // ng node id
237 #else
238       seg.p1 = ngMesh.GetNP();          // ng node id
239       seg.p2 = seg.p1 + 1;              // ng node id
240 #endif
241       seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
242       seg.si = faceID;                  // = geom.fmap.FindIndex (face);
243
244       for ( int iEnd = 0; iEnd < 2; ++iEnd)
245       {
246         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
247
248         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
249         seg.epgeominfo[ iEnd ].u    = pnt.u;
250         seg.epgeominfo[ iEnd ].v    = pnt.v;
251
252         // find out edge id and node parameter on edge
253         bool onVertex = ( pnt.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
254         if ( onVertex || posShapeID != posID )
255         {
256           // get edge id
257           double normParam = pnt.normParam;
258           if ( onVertex )
259             normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
260           const TopoDS_Edge& edge = wire->Edge( wire->EdgeIndex( normParam ));
261           edgeID = geom.emap.FindIndex( edge );
262           posID  = posShapeID;
263           if ( onVertex ) // param on curve is different on each of two edges
264             seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
265         }
266         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
267       }
268       // 20526: [CEA] Disk meshing fails
269       if (reverse)
270       {
271 #ifdef NETGEN_NEW
272         swap (seg.pnums[0], seg.pnums[1]);
273 #else
274         swap (seg.p1, seg.p2);
275 #endif
276         swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist);
277         swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
278         swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
279       }
280
281       ngMesh.AddSegment (seg);
282
283 //       cout << "Segment: " << seg.edgenr << endl
284 //            << "\tp1: " << seg.p1 << endl
285 //            << "\tp2: " << seg.p2 << endl
286 //            << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
287 //            << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
288 //            << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
289 //            << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
290 //            << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
291 //            << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
292     }
293     Segment& seg = ngMesh.LineSegment( ngMesh.GetNSeg() );
294 #ifdef NETGEN_NEW
295     seg.pnums[1] = firstPointID;
296 #else
297     seg.p2 = firstPointID;
298 #endif
299   }
300
301   ngMesh.CalcSurfacesOfNode();  
302
303   return TError();
304 }
305
306 //=============================================================================
307 /*!
308  *Here we are going to use the NETGEN mesher
309  */
310 //=============================================================================
311
312 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
313                                           const TopoDS_Shape& aShape)
314 {
315   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
316
317   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
318   int faceID = meshDS->ShapeToIndex( aShape );
319
320   SMESH_MesherHelper helper(aMesh);
321   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
322   helper.SetElementsOnShape( true );
323   const bool ignoreMediumNodes = _quadraticMesh;
324   
325   // ------------------------
326   // get all edges of a face
327   // ------------------------
328   const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
329   TError problem;
330   TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
331   if ( problem && !problem->IsOK() )
332     return error( problem );
333   int nbWires = wires.size();
334   if ( nbWires == 0 )
335     return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
336   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
337     return error(COMPERR_BAD_INPUT_MESH,
338                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
339
340   // -------------------------
341   // Make input netgen mesh
342   // -------------------------
343
344   Ng_Init();
345   netgen::Mesh * ngMesh = new netgen::Mesh ();
346
347   netgen::OCCGeometry occgeo;
348   NETGENPlugin_Mesher::PrepareOCCgeometry( occgeo, F, aMesh );
349   occgeo.fmap.Clear(); // face can be reversed, which is wrong in this case (issue 19978)
350   occgeo.fmap.Add( F );
351
352   vector< const SMDS_MeshNode* > nodeVec;
353   problem = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
354   if ( problem && !problem->IsOK() ) {
355     delete ngMesh; Ng_Exit();
356     return error( problem );
357   }
358
359   // --------------------
360   // compute edge length
361   // --------------------
362
363   double edgeLength = 0;
364   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea)
365   {
366     int nbSegments = 0;
367     for ( int iW = 0; iW < nbWires; ++iW )
368     {
369       edgeLength += wires[ iW ]->Length();
370       nbSegments += wires[ iW ]->NbSegments();
371     }
372     if ( nbSegments )
373       edgeLength /= nbSegments;
374   }
375   if ( _hypMaxElementArea )
376   {
377     double maxArea = _hypMaxElementArea->GetMaxArea();
378     edgeLength = sqrt(2. * maxArea/sqrt(3.0));
379   }
380   if ( edgeLength < DBL_MIN )
381     edgeLength = occgeo.GetBoundingBox().Diam();
382
383   //cout << " edgeLength = " << edgeLength << endl;
384
385   netgen::mparam.maxh = edgeLength;
386   netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
387   //ngMesh->SetGlobalH ( edgeLength );
388
389   // -------------------------
390   // Generate surface mesh
391   // -------------------------
392
393   char *optstr = 0;
394   int startWith = MESHCONST_MESHSURFACE;
395   int endWith   = MESHCONST_OPTSURFACE;
396   int err = 1;
397
398   try {
399 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
400     OCC_CATCH_SIGNALS;
401 #endif
402     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
403   }
404   catch (Standard_Failure& ex) {
405     string comment = ex.DynamicType()->Name();
406     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
407       comment += ": ";
408       comment += ex.GetMessageString();
409     }
410     error(COMPERR_OCC_EXCEPTION, comment);
411   }
412   catch (NgException exc) {
413     error( SMESH_Comment("NgException: ") << exc.What() );
414   }
415   catch (...) {
416     error(COMPERR_EXCEPTION,"Exception in netgen::OCCGenerateMesh()");
417   }
418
419   // ----------------------------------------------------
420   // Fill the SMESHDS with the generated nodes and faces
421   // ----------------------------------------------------
422
423   int nbNodes = ngMesh->GetNP();
424   int nbFaces = ngMesh->GetNSE();
425
426   int nbInputNodes = nodeVec.size();
427   nodeVec.resize( nbNodes, 0 );
428
429   // add nodes
430   for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
431   {
432     const MeshPoint& ngPoint = ngMesh->Point(i);
433 #ifdef NETGEN_NEW
434     SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
435 #else
436     SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
437 #endif
438     nodeVec[ i-1 ] = node;
439   }
440
441   // create faces
442   bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
443   for ( int i = 1; i <= nbFaces ; ++i )
444   {
445     const Element2d& elem = ngMesh->SurfaceElement(i);
446     vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
447     for (int j=1; j <= elem.GetNP(); ++j)
448     {
449       int pind = elem.PNum(j);
450       const SMDS_MeshNode* node = nodeVec.at(pind-1);
451       if ( reverse )
452         nodes[ nodes.size()-j ] = node;
453       else
454         nodes[ j-1 ] = node;
455       if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
456       {
457         const PointGeomInfo& pgi = elem.GeomInfoPi(j);
458         meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
459       }
460     }
461     SMDS_MeshFace* face = 0;
462     if ( elem.GetType() == TRIG )
463       face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
464     else
465       face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
466   }
467
468   Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
469   Ng_Exit();
470
471   NETGENPlugin_Mesher::RemoveTmpFiles();
472
473   return !err;
474 }
475
476
477 //=============================================================================
478 /*!
479  *
480  */
481 //=============================================================================
482
483 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
484                                            const TopoDS_Shape& aShape,
485                                            MapShapeNbElems& aResMap)
486 {
487   TopoDS_Face F = TopoDS::Face(aShape);
488   if(F.IsNull())
489     return false;
490
491   // collect info from edges
492   int nb0d = 0, nb1d = 0;
493   bool IsQuadratic = false;
494   bool IsFirst = true;
495   double fullLen = 0.0;
496   TopTools_MapOfShape tmpMap;
497   for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
498     TopoDS_Edge E = TopoDS::Edge(exp.Current());
499     if( tmpMap.Contains(E) )
500       continue;
501     tmpMap.Add(E);
502     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
503     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
504     if( anIt==aResMap.end() ) {
505       SMESH_subMesh *sm = aMesh.GetSubMesh(F);
506       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
507       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
508       return false;
509     }
510     std::vector<int> aVec = (*anIt).second;
511     nb0d += aVec[SMDSEntity_Node];
512     nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
513     double aLen = SMESH_Algo::EdgeLength(E);
514     fullLen += aLen;
515     if(IsFirst) {
516       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
517       IsFirst = false;
518     }
519   }
520   tmpMap.Clear();
521
522   // compute edge length
523   double ELen = 0;
524   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea) {
525     if ( nb1d > 0 )
526       ELen = fullLen / nb1d;
527   }
528   if ( _hypMaxElementArea ) {
529     double maxArea = _hypMaxElementArea->GetMaxArea();
530     ELen = sqrt(2. * maxArea/sqrt(3.0));
531   }
532   if ( ELen < Precision::Confusion() ) {
533     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
534     if ( sm ) {
535       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
536       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
537     }
538     return false;
539   }
540
541   GProp_GProps G;
542   BRepGProp::SurfaceProperties(F,G);
543   double anArea = G.Mass();
544   int nbFaces = 0;
545   if ( ELen > Precision::Confusion() )
546     nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
547   int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
548   std::vector<int> aVec(SMDSEntity_Last);
549   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
550   if( IsQuadratic ) {
551     aVec[SMDSEntity_Node] = nbNodes;
552     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
553   }
554   else {
555     aVec[SMDSEntity_Node] = nbNodes;
556     aVec[SMDSEntity_Triangle] = nbFaces;
557   }
558   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
559   aResMap.insert(std::make_pair(sm,aVec));
560
561   return true;
562 }