Salome HOME
[SALOME platform 0013410]: SubMesh not taken into account with Netgen 1D-2D et 1D...
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
1 // Copyright (C) 2005  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS, L3S, LJLL, MENSI
3 //
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License.
8 //
9 // This library is distributed in the hope that it will be useful
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 // Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 //
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 //
20 // File      : NETGENPlugin_NETGEN_2D_ONLY.cxx
21 // Author    : Edward AGAPOV (OCC)
22 // Project   : SALOME
23
24
25 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
26
27 #include "NETGENPlugin_Mesher.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 "StdMeshers_FaceSide.hxx"
37 #include "StdMeshers_MaxElementArea.hxx"
38 #include "StdMeshers_LengthFromEdges.hxx"
39 #include "StdMeshers_QuadranglePreference.hxx"
40
41 #include <Standard_ErrorHandler.hxx>
42 #include <Standard_Failure.hxx>
43
44 #include "utilities.h"
45
46 #include <list>
47 #include <vector>
48
49 /*
50   Netgen include files
51 */
52 namespace nglib {
53 #include <nglib.h>
54 }
55 #define OCCGEOMETRY
56 #include <occgeom.hpp>
57 #include <meshing.hpp>
58 //#include <meshtype.hpp>
59 namespace netgen {
60   extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
61   /*extern*/ MeshingParameters mparam;
62 }
63
64 using namespace std;
65 using namespace netgen;
66 using namespace nglib;
67
68 //=============================================================================
69 /*!
70  *  
71  */
72 //=============================================================================
73
74 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId, int studyId,
75                                                          SMESH_Gen* gen)
76   : SMESH_2D_Algo(hypId, studyId, gen)
77 {
78   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY");
79   _name = "NETGEN_2D_ONLY";
80
81   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
82
83   _compatibleHypothesis.push_back("MaxElementArea");
84   _compatibleHypothesis.push_back("LengthFromEdges");
85   _compatibleHypothesis.push_back("QuadranglePreference");
86
87   _hypMaxElementArea = 0;
88   _hypLengthFromEdges = 0;
89   _hypQuadranglePreference = 0;
90 }
91
92 //=============================================================================
93 /*!
94  *  
95  */
96 //=============================================================================
97
98 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
99 {
100   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
101 }
102
103 //=============================================================================
104 /*!
105  *  
106  */
107 //=============================================================================
108
109 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
110                                                    const TopoDS_Shape& aShape,
111                                                    Hypothesis_Status&  aStatus)
112 {
113   _hypMaxElementArea = 0;
114   _hypLengthFromEdges = 0;
115   _hypQuadranglePreference = 0;
116
117   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
118
119   if (hyps.empty())
120   {
121     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
122     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
123   }
124
125   aStatus = HYP_MISSING;
126
127   list<const SMESHDS_Hypothesis*>::const_iterator ith;
128   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
129   {
130     const SMESHDS_Hypothesis* hyp = (*ith);
131
132     string hypName = hyp->GetName();
133
134     if      ( hypName == "MaxElementArea")
135       _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
136     else if ( hypName == "LengthFromEdges" )
137       _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
138     else if ( hypName == "QuadranglePreference" )
139       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
140     else {
141       aStatus = HYP_INCOMPATIBLE;
142       return false;
143     }
144   }
145
146   if ( _hypMaxElementArea && _hypLengthFromEdges ) {
147     aStatus = HYP_CONCURENT;
148     return false;
149   }
150
151   if ( _hypMaxElementArea || _hypLengthFromEdges )
152     aStatus = HYP_OK;
153
154   return aStatus == HYP_OK;
155 }
156
157 //================================================================================
158 /*!
159  * \brief Fill netgen mesh with segments
160   * \retval SMESH_ComputeErrorPtr - error description
161  */
162 //================================================================================
163
164 static TError AddSegmentsToMesh(netgen::Mesh&                    ngMesh,
165                                 OCCGeometry&                     geom,
166                                 const TSideVector&               wires,
167                                 SMESH_MesherHelper&              helper,
168                                 vector< const SMDS_MeshNode* > & nodeVec)
169 {
170   // ----------------------------
171   // Check wires and count nodes
172   // ----------------------------
173   int nbNodes = 0;
174   for ( int iW = 0; iW < wires.size(); ++iW )
175   {
176     StdMeshers_FaceSidePtr wire = wires[ iW ];
177     if ( wire->MissVertexNode() )
178       return TError
179         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
180       
181     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
182     if ( uvPtVec.size() != wire->NbPoints() )
183       return TError
184         (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,
185                                 SMESH_Comment("Unexpected nb of points on wire ") << iW
186                                 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints()));
187     nbNodes += wire->NbSegments();
188   }
189   nodeVec.reserve( nbNodes );
190
191   // -----------------
192   // Fill netgen mesh
193   // -----------------
194
195 //   netgen::Box<3> bb = geom.GetBoundingBox();
196 //   bb.Increase (bb.Diam()/10);
197 //   ngMesh.SetLocalH (bb.PMin(), bb.PMax(), 0.5); // set grading
198
199   const int faceID = 1, solidID = 0;
200   ngMesh.AddFaceDescriptor (FaceDescriptor(faceID, solidID, solidID, 0));
201
202   for ( int iW = 0; iW < wires.size(); ++iW )
203   {
204     StdMeshers_FaceSidePtr wire = wires[ iW ];
205     const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
206
207     int firstPointID = ngMesh.GetNP() + 1;
208     int edgeID = 1, posID = -2;
209     for ( int i = 0; i < wire->NbSegments(); ++i ) // loop on segments
210     {
211       // Add the first point of a segment
212       const SMDS_MeshNode * n = uvPtVec[ i ].node;
213       const int posShapeID = n->GetPosition()->GetShapeId();
214
215       // skip nodes on degenerated edges
216       if ( helper.IsDegenShape( posShapeID ) &&
217            helper.IsDegenShape( uvPtVec[ i+1 ].node->GetPosition()->GetShapeId() ))
218         continue;
219
220       nodeVec.push_back( n );
221
222       MeshPoint mp( Point<3> (n->X(), n->Y(), n->Z()) );
223       ngMesh.AddPoint ( mp, 1, EDGEPOINT );
224
225       // Add the segment
226       Segment seg;
227
228       seg.p1 = ngMesh.GetNP();          // ng node id
229       seg.p2 = seg.p1 + 1;              // ng node id
230       seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
231       seg.si = faceID;                  // = geom.fmap.FindIndex (face);
232
233       for ( int iEnd = 0; iEnd < 2; ++iEnd)
234       {
235         const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
236
237         seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
238         seg.epgeominfo[ iEnd ].u    = pnt.u;
239         seg.epgeominfo[ iEnd ].v    = pnt.v;
240
241         // find out edge id and node parameter on edge
242         bool onVertex = ( pnt.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
243         if ( onVertex || posShapeID != posID )
244         {
245           // get edge id
246           double normParam = pnt.normParam;
247           if ( onVertex )
248             normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
249           const TopoDS_Edge& edge = wire->Edge( wire->EdgeIndex( normParam ));
250           edgeID = geom.emap.FindIndex( edge );
251           posID  = posShapeID;
252           if ( onVertex ) // param on curve is different on each of two edges
253             seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
254         }
255         seg.epgeominfo[ iEnd ].edgenr = edgeID; //  = geom.emap.FindIndex(edge);
256       }
257
258       ngMesh.AddSegment (seg);
259
260 //       cout << "Segment: " << seg.edgenr << endl
261 //            << "\tp1: " << seg.p1 << endl
262 //            << "\tp2: " << seg.p2 << endl
263 //            << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
264 //            << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
265 //            << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
266 //            << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
267 //            << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
268 //            << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
269     }
270     Segment& seg = ngMesh.LineSegment( ngMesh.GetNSeg() );
271     seg.p2 = firstPointID;
272   }
273
274   ngMesh.CalcSurfacesOfNode();  
275
276   return TError();
277 }
278
279 //=============================================================================
280 /*!
281  *Here we are going to use the NETGEN mesher
282  */
283 //=============================================================================
284
285 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
286                                           const TopoDS_Shape& aShape)
287 {
288   MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::Compute()");
289
290   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
291   int faceID = meshDS->ShapeToIndex( aShape );
292
293   SMESH_MesherHelper helper(aMesh);
294   _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
295   helper.SetElementsOnShape( true );
296   const bool ignoreMediumNodes = _quadraticMesh;
297   
298   // ------------------------
299   // get all edges of a face
300   // ------------------------
301   const TopoDS_Face F = TopoDS::Face( aShape.Oriented( TopAbs_FORWARD ));
302   TError problem;
303   TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, problem );
304   if ( problem && !problem->IsOK() )
305     return error( problem );
306   int nbWires = wires.size();
307   if ( nbWires == 0 )
308     return error( "Problem in StdMeshers_FaceSide::GetFaceWires()");
309   if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
310     return error(COMPERR_BAD_INPUT_MESH,
311                  SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments());
312
313   // -------------------------
314   // Make input netgen mesh
315   // -------------------------
316
317   Ng_Init();
318   netgen::Mesh * ngMesh = new netgen::Mesh ();
319
320   netgen::OCCGeometry occgeo;
321   NETGENPlugin_Mesher::PrepareOCCgeometry( occgeo, F, aMesh );
322
323   vector< const SMDS_MeshNode* > nodeVec;
324   problem = AddSegmentsToMesh( *ngMesh, occgeo, wires, helper, nodeVec );
325   if ( problem && !problem->IsOK() ) {
326     delete ngMesh; Ng_Exit();
327     return error( problem );
328   }
329
330   // --------------------
331   // compute edge length
332   // --------------------
333
334   double edgeLength = 0;
335   if (_hypLengthFromEdges || !_hypLengthFromEdges && !_hypMaxElementArea)
336   {
337     int nbSegments = 0;
338     for ( int iW = 0; iW < nbWires; ++iW )
339     {
340       edgeLength += wires[ iW ]->Length();
341       nbSegments += wires[ iW ]->NbSegments();
342     }
343     if ( nbSegments )
344       edgeLength /= nbSegments;
345   }
346   if ( _hypMaxElementArea )
347   {
348     double maxArea = _hypMaxElementArea->GetMaxArea();
349     edgeLength = sqrt(2. * maxArea/sqrt(3.0));
350   }
351   if ( edgeLength < DBL_MIN )
352     edgeLength = occgeo.GetBoundingBox().Diam();
353
354   //cout << " edgeLength = " << edgeLength << endl;
355
356   netgen::mparam.maxh = edgeLength;
357   netgen::mparam.quad = _hypQuadranglePreference ? 1 : 0;
358   //ngMesh->SetGlobalH ( edgeLength );
359
360   // -------------------------
361   // Generate surface mesh
362   // -------------------------
363
364   char *optstr;
365   int startWith = MESHCONST_MESHSURFACE;
366   int endWith   = MESHCONST_OPTSURFACE;
367   int err = 1;
368
369   try {
370 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
371     OCC_CATCH_SIGNALS;
372 #endif
373     err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
374   }
375   catch (Standard_Failure& ex) {
376     string comment = ex.DynamicType()->Name();
377     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
378       comment += ": ";
379       comment += ex.GetMessageString();
380     }
381     error(COMPERR_OCC_EXCEPTION, comment);
382   }
383   catch (NgException exc) {
384     error( SMESH_Comment("NgException: ") << exc.What() );
385   }
386   catch (...) {
387     error(COMPERR_EXCEPTION,"Exception in netgen::OCCGenerateMesh()");
388   }
389
390   // ----------------------------------------------------
391   // Fill the SMESHDS with the generated nodes and faces
392   // ----------------------------------------------------
393
394   int nbNodes = ngMesh->GetNP();
395   int nbFaces = ngMesh->GetNSE();
396
397   int nbInputNodes = nodeVec.size();
398   nodeVec.resize( nbNodes, 0 );
399
400   // add nodes
401   for ( int i = nbInputNodes + 1; i <= nbNodes; ++i )
402   {
403     const MeshPoint& ngPoint = ngMesh->Point(i);
404     SMDS_MeshNode * node = meshDS->AddNode(ngPoint.X(), ngPoint.Y(), ngPoint.Z());
405     nodeVec[ i-1 ] = node;
406   }
407
408   // create faces
409   bool reverse = ( aShape.Orientation() == TopAbs_REVERSED );
410   for ( int i = 1; i <= nbFaces ; ++i )
411   {
412     const Element2d& elem = ngMesh->SurfaceElement(i);
413     vector<const SMDS_MeshNode*> nodes( elem.GetNP() );
414     for (int j=1; j <= elem.GetNP(); ++j)
415     {
416       int pind = elem.PNum(j);
417       const SMDS_MeshNode* node = nodeVec.at(pind-1);
418       if ( reverse )
419         nodes[ nodes.size()-j ] = node;
420       else
421         nodes[ j-1 ] = node;
422       if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
423       {
424         const PointGeomInfo& pgi = elem.GeomInfoPi(j);
425         meshDS->SetNodeOnFace((SMDS_MeshNode*)node, faceID, pgi.u, pgi.v);
426       }
427     }
428     SMDS_MeshFace* face = 0;
429     if ( elem.GetType() == TRIG )
430       face = helper.AddFace(nodes[0],nodes[1],nodes[2]);
431     else
432       face = helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
433   }
434
435   Ng_DeleteMesh((nglib::Ng_Mesh*)ngMesh);
436   Ng_Exit();
437
438   NETGENPlugin_Mesher::RemoveTmpFiles();
439
440   return !err;
441 }