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