]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
Add possibility to define Local Size via a file
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_2D_ONLY.cxx
1 // Copyright (C) 2007-2016  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, or (at your option) any later version.
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   extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
73 }
74
75 using namespace std;
76 using namespace netgen;
77 using namespace nglib;
78
79 //=============================================================================
80 /*!
81  *  
82  */
83 //=============================================================================
84
85 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int        hypId,
86                                                          int        studyId,
87                                                          SMESH_Gen* gen)
88   : SMESH_2D_Algo(hypId, studyId, gen)
89 {
90   _name = "NETGEN_2D_ONLY";
91   
92   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
93   _onlyUnaryInput = false; // treat all FACEs at once
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   _hypParameters = 0;
132   _progressByTic = -1;
133
134   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
135
136   if (hyps.empty())
137   {
138     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
139     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
140   }
141
142   aStatus = HYP_MISSING;
143
144   bool hasVL = false;
145   list<const SMESHDS_Hypothesis*>::const_iterator ith;
146   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
147   {
148     const SMESHDS_Hypothesis* hyp = (*ith);
149
150     string hypName = hyp->GetName();
151
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() )
161       hasVL = true;
162     else {
163       aStatus = HYP_INCOMPATIBLE;
164       return false;
165     }
166   }
167
168   int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
169   if ( nbHyps > 1 )
170     aStatus = HYP_CONCURENT;
171   else if ( hasVL )
172     error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus ));
173   else
174     aStatus = HYP_OK;
175
176   if ( aStatus == HYP_OK && _hypParameters && _hypQuadranglePreference )
177   {
178     aStatus = HYP_INCOMPAT_HYPS;
179     return error(SMESH_Comment("\"") << _hypQuadranglePreference->GetName()
180                  << "\" and \"" << _hypParameters->GetName()
181                  << "\" are incompatible hypotheses");
182   }
183
184   return ( aStatus == HYP_OK );
185 }
186
187 // namespace
188 // {
189 //   void limitSize( netgen::Mesh* ngMesh,
190 //                   const double  maxh )
191 //   {
192 //     // get bnd box
193 //     netgen::Point3d pmin, pmax;
194 //     ngMesh->GetBox( pmin, pmax, 0 );
195 //     const double dx = pmax.X() - pmin.X();
196 //     const double dy = pmax.Y() - pmin.Y();
197 //     const double dz = pmax.Z() - pmin.Z();
198
199 //     const int nbX = Max( 2, int( dx / maxh * 3 ));
200 //     const int nbY = Max( 2, int( dy / maxh * 3 ));
201 //     const int nbZ = Max( 2, int( dz / maxh * 3 ));
202
203 //     if ( ! & ngMesh->LocalHFunction() )
204 //       ngMesh->SetLocalH( pmin, pmax, 0.1 );
205
206 //     netgen::Point3d p;
207 //     for ( int i = 0; i <= nbX; ++i )
208 //     {
209 //       p.X() = pmin.X() +  i * dx / nbX;
210 //       for ( int j = 0; j <= nbY; ++j )
211 //       {
212 //         p.Y() = pmin.Y() +  j * dy / nbY;
213 //         for ( int k = 0; k <= nbZ; ++k )
214 //         {
215 //           p.Z() = pmin.Z() +  k * dz / nbZ;
216 //           ngMesh->RestrictLocalH( p, maxh );
217 //         }
218 //       }
219 //     }
220 //   }
221 // }
222
223 //=============================================================================
224 /*!
225  *Here we are going to use the NETGEN mesher
226  */
227 //=============================================================================
228
229 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
230                                           const TopoDS_Shape& aShape)
231 {
232   netgen::multithread.terminate = 0;
233   //netgen::multithread.task = "Surface meshing";
234
235   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
236   SMESH_MesherHelper helper(aMesh);
237   helper.SetElementsOnShape( true );
238
239   NETGENPlugin_NetgenLibWrapper ngLib;
240   ngLib._isComputeOk = false;
241
242   netgen::Mesh   ngMeshNoLocSize;
243   netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh,  & ngMeshNoLocSize };
244   netgen::OCCGeometry occgeoComm;
245
246   // min / max sizes are set as follows:
247   // if ( _hypParameters )
248   //    min and max are defined by the user
249   // else if ( _hypLengthFromEdges )
250   //    min = aMesher.GetDefaultMinSize()
251   //    max = average segment len of a FACE
252   // else if ( _hypMaxElementArea )
253   //    min = aMesher.GetDefaultMinSize()
254   //    max = f( _hypMaxElementArea )
255   // else
256   //    min = aMesher.GetDefaultMinSize()
257   //    max = max segment len of a FACE
258
259   NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
260   aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
261   const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
262   if ( _hypMaxElementArea )
263   {
264     netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
265   }
266   if ( _hypQuadranglePreference )
267     netgen::mparam.quad = true;
268
269   // local size is common for all FACEs in aShape?
270   const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
271   const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
272
273   if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
274   {
275     //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
276     aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
277
278     // local size set at MESHCONST_ANALYSE step depends on
279     // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
280     if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
281     {
282       if ( !_hypParameters )
283         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
284       netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
285     }
286     // set local size depending on curvature and NOT closeness of EDGEs
287     netgen::occparam.resthcloseedgeenable = false;
288     //netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
289     occgeoComm.face_maxh = netgen::mparam.maxh;
290     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
291     occgeoComm.emap.Clear();
292     occgeoComm.vmap.Clear();
293
294     // set local size according to size of existing segments
295     const double factor = netgen::occparam.resthcloseedgefac;
296     TopTools_IndexedMapOfShape edgeMap;
297     TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
298     for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
299     {
300       const TopoDS_Shape& edge = edgeMap( iE );
301       if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
302         continue;
303       SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
304       if ( !smDS ) continue;
305       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
306       while ( segIt->more() )
307       {
308         const SMDS_MeshElement* seg = segIt->next();
309         SMESH_TNodeXYZ n1 = seg->GetNode(0);
310         SMESH_TNodeXYZ n2 = seg->GetNode(1);
311         gp_XYZ p = 0.5 * ( n1 + n2 );
312         netgen::Point3d pi(p.X(), p.Y(), p.Z());
313         ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
314       }
315     }
316
317     // set local size defined on shapes
318     aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
319     try {
320       ngMeshes[0]->LoadLocalMeshSize( mparam.meshsizefilename );
321     } catch (NgException & ex) {
322       return error( COMPERR_BAD_PARMETERS, ex.What() );
323     }
324   }
325   netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
326
327   // ==================
328   // Loop on all FACEs
329   // ==================
330
331   vector< const SMDS_MeshNode* > nodeVec;
332
333   TopExp_Explorer fExp( aShape, TopAbs_FACE );
334   for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
335   {
336     TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
337     int    faceID = meshDS->ShapeToIndex( F );
338     SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
339
340     _quadraticMesh = helper.IsQuadraticSubMesh( F );
341     const bool ignoreMediumNodes = _quadraticMesh;
342
343     // build viscous layers if required
344     if ( F.Orientation() != TopAbs_FORWARD &&
345          F.Orientation() != TopAbs_REVERSED )
346       F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
347     SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
348     if ( !proxyMesh )
349       continue;
350
351     // ------------------------
352     // get all EDGEs of a FACE
353     // ------------------------
354     TSideVector wires =
355       StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, proxyMesh );
356     if ( faceErr && !faceErr->IsOK() )
357       continue;
358     int nbWires = wires.size();
359     if ( nbWires == 0 )
360     {
361       faceErr.reset
362         ( new SMESH_ComputeError
363           ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
364       continue;
365     }
366     if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
367     {
368       faceErr.reset
369         ( new SMESH_ComputeError
370           ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
371       continue;
372     }
373
374     // ----------------------
375     // compute maxh of a FACE
376     // ----------------------
377
378     if ( !_hypParameters )
379     {
380       double edgeLength = 0;
381       if (_hypLengthFromEdges )
382       {
383         // compute edgeLength as an average segment length
384         int nbSegments = 0;
385         for ( int iW = 0; iW < nbWires; ++iW )
386         {
387           edgeLength += wires[ iW ]->Length();
388           nbSegments += wires[ iW ]->NbSegments();
389         }
390         if ( nbSegments )
391           edgeLength /= nbSegments;
392         netgen::mparam.maxh = edgeLength;
393       }
394       else if ( isDefaultHyp )
395       {
396         // set edgeLength by a longest segment
397         double maxSeg2 = 0;
398         for ( int iW = 0; iW < nbWires; ++iW )
399         {
400           const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
401           if ( points.empty() )
402             return error( COMPERR_BAD_INPUT_MESH );
403           gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
404           for ( size_t i = 1; i < points.size(); ++i )
405           {
406             gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
407             maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
408             pPrev = p;
409           }
410         }
411         edgeLength = sqrt( maxSeg2 ) * 1.05;
412         netgen::mparam.maxh = edgeLength;
413       }
414       if ( netgen::mparam.maxh < DBL_MIN )
415         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
416
417       if ( !isCommonLocalSize )
418       {
419         netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
420       }
421     }
422
423     // prepare occgeom
424     netgen::OCCGeometry occgeom;
425     occgeom.shape = F;
426     occgeom.fmap.Add( F );
427     occgeom.CalcBoundingBox();
428     occgeom.facemeshstatus.SetSize(1);
429     occgeom.facemeshstatus = 0;
430     occgeom.face_maxh_modified.SetSize(1);
431     occgeom.face_maxh_modified = 0;
432     occgeom.face_maxh.SetSize(1);
433     occgeom.face_maxh = netgen::mparam.maxh;
434
435     // -------------------------
436     // Fill netgen mesh
437     // -------------------------
438
439     // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
440     // w/o MESHCONST_ANALYSE at the second loop
441     int err = 0;
442     enum { LOC_SIZE, NO_LOC_SIZE };
443     int iLoop = isCommonLocalSize ? 0 : 1;
444     for ( ; iLoop < 2; iLoop++ )
445     {
446       //bool isMESHCONST_ANALYSE = false;
447       InitComputeError();
448
449       netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
450       ngMesh->DeleteMesh();
451
452       if ( iLoop == NO_LOC_SIZE )
453       {
454         ngMesh->SetGlobalH ( mparam.maxh );
455         ngMesh->SetMinimalH( mparam.minh );
456         Box<3> bb = occgeom.GetBoundingBox();
457         bb.Increase (bb.Diam()/10);
458         ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparam.grading);
459         aMesher.SetLocalSize( occgeom, *ngMesh );
460         try {
461           ngMesh->LoadLocalMeshSize( mparam.meshsizefilename );
462         } catch (NgException & ex) {
463           return error( COMPERR_BAD_PARMETERS, ex.What() );
464         }
465       }
466
467       nodeVec.clear();
468       faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
469                                            /*overrideMinH=*/!_hypParameters);
470       if ( faceErr && !faceErr->IsOK() )
471         break;
472
473       //if ( !isCommonLocalSize )
474       //limitSize( ngMesh, mparam.maxh * 0.8);
475
476       // -------------------------
477       // Generate surface mesh
478       // -------------------------
479
480       const int startWith = MESHCONST_MESHSURFACE;
481       const int endWith   = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
482
483       SMESH_Comment str;
484       try {
485         OCC_CATCH_SIGNALS;
486
487 #ifdef NETGEN_V5
488         err = netgen::OCCGenerateMesh(occgeom, ngMesh, netgen::mparam, startWith, endWith);
489 #else
490         char *optstr = 0;
491         err = netgen::OCCGenerateMesh(occgeom, ngMesh, startWith, endWith, optstr);
492 #endif
493         if ( netgen::multithread.terminate )
494           return false;
495         if ( err )
496           str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
497       }
498       catch (Standard_Failure& ex)
499       {
500         err = 1;
501         str << "Exception in  netgen::OCCGenerateMesh()"
502             << " at " << netgen::multithread.task
503             << ": " << ex.DynamicType()->Name();
504         if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
505           str << ": " << ex.GetMessageString();
506       }
507       catch (...) {
508         err = 1;
509         str << "Exception in  netgen::OCCGenerateMesh()"
510             << " at " << netgen::multithread.task;
511       }
512       if ( err )
513       {
514         if ( aMesher.FixFaceMesh( occgeom, *ngMesh, 1 ))
515           break;
516         if ( iLoop == LOC_SIZE )
517         {
518           netgen::mparam.minh = netgen::mparam.maxh;
519           netgen::mparam.maxh = 0;
520           for ( size_t iW = 0; iW < wires.size(); ++iW )
521           {
522             StdMeshers_FaceSidePtr wire = wires[ iW ];
523             const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
524             for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
525             {
526               SMESH_TNodeXYZ   p( uvPtVec[ iP ].node );
527               netgen::Point3d np( p.X(),p.Y(),p.Z());
528               double segLen = p.Distance( uvPtVec[ iP-1 ].node );
529               double   size = ngMesh->GetH( np );
530               netgen::mparam.minh = Min( netgen::mparam.minh, size );
531               netgen::mparam.maxh = Max( netgen::mparam.maxh, segLen );
532             }
533           }
534           //cerr << "min " << netgen::mparam.minh << " max " << netgen::mparam.maxh << endl;
535           netgen::mparam.minh *= 0.9;
536           netgen::mparam.maxh *= 1.1;
537           continue;
538         }
539         else
540         {
541           faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
542         }
543       }
544
545
546       // ----------------------------------------------------
547       // Fill the SMESHDS with the generated nodes and faces
548       // ----------------------------------------------------
549
550       int nbNodes = ngMesh->GetNP();
551       int nbFaces = ngMesh->GetNSE();
552
553       int nbInputNodes = nodeVec.size()-1;
554       nodeVec.resize( nbNodes+1, 0 );
555
556       // add nodes
557       for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
558       {
559         const MeshPoint& ngPoint = ngMesh->Point( ngID );
560         SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
561         nodeVec[ ngID ] = node;
562       }
563
564       // create faces
565       int i,j;
566       vector<const SMDS_MeshNode*> nodes;
567       for ( i = 1; i <= nbFaces ; ++i )
568       {
569         const Element2d& elem = ngMesh->SurfaceElement(i);
570         nodes.resize( elem.GetNP() );
571         for (j=1; j <= elem.GetNP(); ++j)
572         {
573           int pind = elem.PNum(j);
574           if ( pind < 1 )
575             break;
576           nodes[ j-1 ] = nodeVec[ pind ];
577           if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
578           {
579             const PointGeomInfo& pgi = elem.GeomInfoPi(j);
580             meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
581           }
582         }
583         if ( j > elem.GetNP() )
584         {
585           if ( elem.GetType() == TRIG )
586             helper.AddFace(nodes[0],nodes[1],nodes[2]);
587           else
588             helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
589         }
590       }
591
592       break;
593     } // two attempts
594   } // loop on FACEs
595
596   return true;
597 }
598
599 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
600 {
601   SMESH_Algo::CancelCompute();
602   netgen::multithread.terminate = 1;
603 }
604
605 //================================================================================
606 /*!
607  * \brief Return progress of Compute() [0.,1]
608  */
609 //================================================================================
610
611 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
612 {
613   return -1;
614   // const char* task1 = "Surface meshing";
615   // //const char* task2 = "Optimizing surface";
616   // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
617   // if ( _progressByTic < 0. &&
618   //      strncmp( netgen::multithread.task, task1, 3 ) == 0 )
619   // {
620   //   progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
621   // }
622   // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
623   // {
624   //   if ( _progressByTic < 0 )
625   //   {
626   //     NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
627   //     me->_progressByTic = 0.25 / (_progressTic+1);
628   //   }
629   //   const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
630   //   progress = Max( progress, _progressByTic * _progressTic );
631   // }
632   // //cout << netgen::multithread.task << " " << _progressTic << endl;
633   // return Min( progress, 0.99 );
634 }
635
636 //=============================================================================
637 /*!
638  *
639  */
640 //=============================================================================
641
642 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
643                                            const TopoDS_Shape& aShape,
644                                            MapShapeNbElems& aResMap)
645 {
646   TopoDS_Face F = TopoDS::Face(aShape);
647   if(F.IsNull())
648     return false;
649
650   // collect info from edges
651   int nb0d = 0, nb1d = 0;
652   bool IsQuadratic = false;
653   bool IsFirst = true;
654   double fullLen = 0.0;
655   TopTools_MapOfShape tmpMap;
656   for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
657     TopoDS_Edge E = TopoDS::Edge(exp.Current());
658     if( tmpMap.Contains(E) )
659       continue;
660     tmpMap.Add(E);
661     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
662     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
663     if( anIt==aResMap.end() ) {
664       SMESH_subMesh *sm = aMesh.GetSubMesh(F);
665       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
666       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
667       return false;
668     }
669     std::vector<int> aVec = (*anIt).second;
670     nb0d += aVec[SMDSEntity_Node];
671     nb1d += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
672     double aLen = SMESH_Algo::EdgeLength(E);
673     fullLen += aLen;
674     if(IsFirst) {
675       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
676       IsFirst = false;
677     }
678   }
679   tmpMap.Clear();
680
681   // compute edge length
682   double ELen = 0;
683   if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
684     if ( nb1d > 0 )
685       ELen = fullLen / nb1d;
686   }
687   if ( _hypMaxElementArea ) {
688     double maxArea = _hypMaxElementArea->GetMaxArea();
689     ELen = sqrt(2. * maxArea/sqrt(3.0));
690   }
691   GProp_GProps G;
692   BRepGProp::SurfaceProperties(F,G);
693   double anArea = G.Mass();
694
695   const int hugeNb = numeric_limits<int>::max()/10;
696   if ( anArea / hugeNb > ELen*ELen )
697   {
698     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
699     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
700     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
701     return false;
702   }
703   int nbFaces = (int) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
704   int nbNodes = (int) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
705   std::vector<int> aVec(SMDSEntity_Last);
706   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
707   if( IsQuadratic ) {
708     aVec[SMDSEntity_Node] = nbNodes;
709     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
710   }
711   else {
712     aVec[SMDSEntity_Node] = nbNodes;
713     aVec[SMDSEntity_Triangle] = nbFaces;
714   }
715   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
716   aResMap.insert(std::make_pair(sm,aVec));
717
718   return true;
719 }