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