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