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