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