]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
Removing hard coded meshname from Mesh import
[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_DriverParam.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 #include "SMESH_DriverShape.hxx"
44 #include "SMESH_DriverMesh.hxx"
45
46
47 #include <Precision.hxx>
48 #include <Standard_ErrorHandler.hxx>
49 #include <Standard_Failure.hxx>
50
51 #include <utilities.h>
52
53 #include <list>
54 #include <vector>
55 #include <limits>
56
57 #include <cstdlib>
58 #include <boost/filesystem.hpp>
59 namespace fs = boost::filesystem;
60 /*
61   Netgen include files
62 */
63 namespace nglib {
64 #include <nglib.h>
65 }
66 #ifndef OCCGEOMETRY
67 #define OCCGEOMETRY
68 #endif
69 #include <occgeom.hpp>
70 #include <meshing.hpp>
71 //#include <meshtype.hpp>
72 namespace netgen {
73   NETGENPLUGIN_DLL_HEADER
74   extern MeshingParameters mparam;
75 #ifdef NETGEN_V5
76   extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
77 #endif
78 }
79
80 using namespace std;
81 using namespace netgen;
82 using namespace nglib;
83
84
85 //=============================================================================
86 /*!
87  *
88  */
89 //=============================================================================
90
91 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int        hypId,
92                                                          SMESH_Gen* gen)
93   : SMESH_2D_Algo(hypId, gen)
94 {
95   _name = "NETGEN_2D_ONLY";
96
97   _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
98   _onlyUnaryInput = false; // treat all FACEs at once
99
100   _compatibleHypothesis.push_back("MaxElementArea");
101   _compatibleHypothesis.push_back("LengthFromEdges");
102   _compatibleHypothesis.push_back("QuadranglePreference");
103   _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
104   _compatibleHypothesis.push_back("ViscousLayers2D");
105
106   _hypMaxElementArea       = 0;
107   _hypLengthFromEdges      = 0;
108   _hypQuadranglePreference = 0;
109   _hypParameters           = 0;
110 }
111
112 //=============================================================================
113 /*!
114  *
115  */
116 //=============================================================================
117
118 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
119 {
120   //MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
121 }
122
123 //=============================================================================
124 /*!
125  *
126  */
127 //=============================================================================
128
129 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh&         aMesh,
130                                                    const TopoDS_Shape& aShape,
131                                                    Hypothesis_Status&  aStatus)
132 {
133   _hypMaxElementArea = 0;
134   _hypLengthFromEdges = 0;
135   _hypQuadranglePreference = 0;
136   _hypParameters = 0;
137   _progressByTic = -1;
138
139
140   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
141
142   if (hyps.empty())
143   {
144     aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
145     return true;  // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
146   }
147
148   aStatus = HYP_MISSING;
149
150   bool hasVL = false;
151   list<const SMESHDS_Hypothesis*>::const_iterator ith;
152   for (ith = hyps.begin(); ith != hyps.end(); ++ith )
153   {
154     const SMESHDS_Hypothesis* hyp = (*ith);
155
156     string hypName = hyp->GetName();
157
158     if      ( hypName == "MaxElementArea")
159       _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
160     else if ( hypName == "LengthFromEdges" )
161       _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
162     else if ( hypName == "QuadranglePreference" )
163       _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
164     else if ( hypName == "NETGEN_Parameters_2D" )
165       _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
166     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
167       hasVL = true;
168     else {
169       aStatus = HYP_INCOMPATIBLE;
170       return false;
171     }
172   }
173
174   int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
175   if ( nbHyps > 1 )
176     aStatus = HYP_CONCURRENT;
177   else if ( hasVL )
178     error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus ));
179   else
180     aStatus = HYP_OK;
181
182   if ( aStatus == HYP_OK && _hypParameters && _hypQuadranglePreference )
183   {
184     aStatus = HYP_INCOMPAT_HYPS;
185     return error(SMESH_Comment("\"") << _hypQuadranglePreference->GetName()
186                  << "\" and \"" << _hypParameters->GetName()
187                  << "\" are incompatible hypotheses");
188   }
189
190   return ( aStatus == HYP_OK );
191 }
192
193 // namespace
194 // {
195 //   void limitSize( netgen::Mesh* ngMesh,
196 //                   const double  maxh )
197 //   {
198 //     // get bnd box
199 //     netgen::Point3d pmin, pmax;
200 //     ngMesh->GetBox( pmin, pmax, 0 );
201 //     const double dx = pmax.X() - pmin.X();
202 //     const double dy = pmax.Y() - pmin.Y();
203 //     const double dz = pmax.Z() - pmin.Z();
204
205 //     const int nbX = Max( 2, int( dx / maxh * 3 ));
206 //     const int nbY = Max( 2, int( dy / maxh * 3 ));
207 //     const int nbZ = Max( 2, int( dz / maxh * 3 ));
208
209 //     if ( ! & ngMesh->LocalHFunction() )
210 //       ngMesh->SetLocalH( pmin, pmax, 0.1 );
211
212 //     netgen::Point3d p;
213 //     for ( int i = 0; i <= nbX; ++i )
214 //     {
215 //       p.X() = pmin.X() +  i * dx / nbX;
216 //       for ( int j = 0; j <= nbY; ++j )
217 //       {
218 //         p.Y() = pmin.Y() +  j * dy / nbY;
219 //         for ( int k = 0; k <= nbZ; ++k )
220 //         {
221 //           p.Z() = pmin.Z() +  k * dz / nbZ;
222 //           ngMesh->RestrictLocalH( p, maxh );
223 //         }
224 //       }
225 //     }
226 //   }
227 // }
228
229
230 // write in a binary file the orientation for each 2D element of the mesh
231 void NETGENPlugin_NETGEN_2D_ONLY::exportElementOrientation(SMESH_Mesh& aMesh,
232                                                            const TopoDS_Shape& aShape,
233                                                            netgen_params& aParams,
234                                                            const std::string output_file)
235 {
236   std::map<vtkIdType, bool> elemOrientation;
237
238   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
239   for ( TopExp_Explorer exEd( aShape, TopAbs_EDGE ); exEd.More(); exEd.Next())
240   {
241     const TopoDS_Shape& aShapeEdge = exEd.Current();
242     const SMESHDS_SubMesh * aSubMeshDSEdge = proxyMesh->GetSubMesh( aShapeEdge );
243     if ( !aSubMeshDSEdge ) continue;
244
245     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSEdge->GetElements();
246     while ( iteratorElem->more() ) // loop on elements on a geom face
247     {
248       const SMDS_MeshElement* elem = iteratorElem->next();
249       elemOrientation[elem->GetID()] = aShapeEdge.Orientation() == TopAbs_INTERNAL;
250     }
251   }
252
253   std::ofstream df(output_file, ios::out|ios::binary);
254   int size=elemOrientation.size();
255
256   df.write((char*)&size, sizeof(int));
257   for(auto const& [id, orient]:elemOrientation){
258     df.write((char*)&id, sizeof(vtkIdType));
259     df.write((char*)&orient, sizeof(bool));
260   }
261   df.close();
262 }
263
264 void NETGENPlugin_NETGEN_2D_ONLY::FillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
265 {
266   //TODO: factorize code with the one from NETGEN3D
267   // Move in netgen_param ?
268   aParams.maxh               = hyp->GetMaxSize();
269   aParams.minh               = hyp->GetMinSize();
270   aParams.segmentsperedge    = hyp->GetNbSegPerEdge();
271   aParams.grading            = hyp->GetGrowthRate();
272   aParams.curvaturesafety    = hyp->GetNbSegPerRadius();
273   aParams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
274   aParams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
275   aParams.optimize           = hyp->GetOptimize();
276   aParams.fineness           = hyp->GetFineness();
277   aParams.uselocalh          = hyp->GetSurfaceCurvature();
278   aParams.merge_solids       = hyp->GetFuseEdges();
279   aParams.chordalError       = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
280   aParams.optsteps2d         = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
281   aParams.optsteps3d         = aParams.optimize ? hyp->GetNbVolOptSteps()  : 0;
282   aParams.elsizeweight       = hyp->GetElemSizeWeight();
283   aParams.opterrpow          = hyp->GetWorstElemMeasure();
284   aParams.delaunay           = hyp->GetUseDelauney();
285   aParams.checkoverlap       = hyp->GetCheckOverlapping();
286   aParams.checkchartboundary = hyp->GetCheckChartBoundary();
287 #ifdef NETGEN_V6
288   // std::string
289   aParams.meshsizefilename = hyp->GetMeshSizeFile();
290 #else
291   // const char*
292   aParams.meshsizefilename = hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
293 #endif
294 #ifdef NETGEN_V6
295   aParams.closeedgefac = 2;
296 #else
297   aParams.closeedgefac = 0;
298 #endif
299   aParams.has_LengthFromEdges_hyp = _hypLengthFromEdges;
300 }
301 //=============================================================================
302 /*!
303  *Here we are going to use the NETGEN mesher remotely
304  */
305 //=============================================================================
306
307 bool NETGENPlugin_NETGEN_2D_ONLY::RemoteCompute(SMESH_Mesh&         aMesh,
308                                                 const TopoDS_Shape& aShape)
309 {
310     aMesh.Lock();
311   SMESH_Hypothesis::Hypothesis_Status hypStatus;
312   CheckHypothesis(aMesh, aShape, hypStatus);
313
314   // Temporary folder for run
315   fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Face-%%%%-%%%%"));
316   fs::create_directories(tmp_folder);
317   // Using MESH2D generated after all triangles where created.
318   fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh1D.med");
319   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
320   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
321   fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
322   // TODO: Remove that file we do not use it
323   fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
324   fs::path shape_file=tmp_folder / fs::path("shape.step");
325   fs::path param_file=tmp_folder / fs::path("netgen2d_param.txt");
326   fs::path log_file=tmp_folder / fs::path("run.log");
327
328   //Writing Shape
329   exportShape(shape_file.string(), aShape);
330   //Writing hypo
331   netgen_params aParams;
332   FillParameters(_hypParameters, aParams);
333
334   exportNetgenParams(param_file.string(), aParams);
335
336   // Exporting element orientation
337   exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
338
339   aMesh.Unlock();
340   // Calling run_mesher
341   // TODO: check if we need to handle the .exe for windows
342   std::string cmd;
343   fs::path run_mesher_exe =
344     fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
345     fs::path("bin")/
346     fs::path("salome")/
347     fs::path("NETGENPlugin_Runner");
348   cmd = run_mesher_exe.string() +
349                   " NETGEN2D " + mesh_file.string() + " "
350                                + shape_file.string() + " "
351                                + param_file.string() + " "
352                                + element_orientation_file.string() + " "
353                                + new_element_file.string() + " "
354                                + std::to_string(0) + " "
355                                + output_mesh_file.string() +
356                                " >> " + log_file.string();
357
358   std::cout << "Running command: " << std::endl;
359   std::cout << cmd << std::endl;
360
361   // Writing command in log
362   std::ofstream flog(log_file.string());
363   flog << cmd << endl;
364   flog.close();
365
366   // TODO: Replace system by something else to handle redirection for windows
367   int ret = system(cmd.c_str());
368
369   // TODO: better error handling (display log ?)
370   if(ret != 0){
371     // Run crahed
372     //throw Exception("Meshing failed");
373     std::cerr << "Issue with command: " << std::endl;
374     std::cerr << cmd << std::endl;
375     return false;
376   }
377
378     aMesh.Lock();
379   std::ifstream df(new_element_file.string(), ios::binary);
380
381   int Netgen_NbOfNodes;
382   int Netgen_NbOfNodesNew;
383   int Netgen_NbOfTria;
384   double Netgen_point[3];
385   int    Netgen_triangle[3];
386   int nodeID;
387
388   SMESH_MesherHelper helper(aMesh);
389   // This function is necessary so that SetElementOnShape works
390   int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
391   helper.SetElementsOnShape( true );
392
393   // Number of nodes in intial mesh
394   df.read((char*) &Netgen_NbOfNodes, sizeof(int));
395   // Number of nodes added by netgen
396   df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
397
398   // Filling nodevec (correspondence netgen numbering mesh numbering)
399   vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
400   for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
401   {
402     //Id of the point
403     df.read((char*) &nodeID, sizeof(int));
404     nodeVec.at(nodeIndex) = nullptr;
405     SMDS_NodeIteratorPtr iteratorNode = aMesh.GetMeshDS()->nodesIterator();
406     while(iteratorNode->more()){
407       const SMDS_MeshNode* node = iteratorNode->next();
408       if(node->GetID() == nodeID){
409         nodeVec.at(nodeIndex) = node;
410         break;
411       }
412     }
413     if(nodeVec.at(nodeIndex) == nullptr){
414       std::cout << "Error could not identify id";
415       return false;
416     }
417   }
418
419   // Add new points and update nodeVec
420   for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
421   {
422     df.read((char *) &Netgen_point, sizeof(double)*3);
423
424     nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
425                                            Netgen_point[1],
426                                            Netgen_point[2]);
427   }
428
429   // Add tetrahedrons
430   df.read((char*) &Netgen_NbOfTria, sizeof(int));
431   for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTria; ++elemIndex )
432   {
433     df.read((char*) &Netgen_triangle, sizeof(int)*3);
434     helper.AddFace (nodeVec.at( Netgen_triangle[0] ),
435                     nodeVec.at( Netgen_triangle[1] ),
436                     nodeVec.at( Netgen_triangle[2] ));
437   }
438   df.close();
439
440   aMesh.Unlock();
441
442   return true;
443 }
444 //=============================================================================
445 /*!
446  *Here we are going to use the NETGEN mesher
447  */
448 //=============================================================================
449
450 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
451                                           const TopoDS_Shape& aShape)
452 {
453
454   if(aMesh.IsParallel())
455     return RemoteCompute(aMesh, aShape);
456
457   netgen::multithread.terminate = 0;
458   netgen::multithread.task = "Surface meshing";
459
460   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
461   SMESH_MesherHelper helper(aMesh);
462   helper.SetElementsOnShape( true );
463
464   NETGENPlugin_NetgenLibWrapper ngLib;
465   ngLib._isComputeOk = false;
466
467   netgen::Mesh   ngMeshNoLocSize;
468   netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh,  & ngMeshNoLocSize };
469   netgen::OCCGeometry occgeoComm;
470
471   // min / max sizes are set as follows:
472   // if ( _hypParameters )
473   //    min and max are defined by the user
474   // else if ( _hypLengthFromEdges )
475   //    min = aMesher.GetDefaultMinSize()
476   //    max = average segment len of a FACE
477   // else if ( _hypMaxElementArea )
478   //    min = aMesher.GetDefaultMinSize()
479   //    max = f( _hypMaxElementArea )
480   // else
481   //    min = aMesher.GetDefaultMinSize()
482   //    max = max segment len of a FACE
483   NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
484   aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
485   const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
486   if ( _hypMaxElementArea )
487   {
488     netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
489   }
490   if ( _hypQuadranglePreference )
491     netgen::mparam.quad = true;
492
493   // local size is common for all FACEs in aShape?
494   const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
495   const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
496   aMesh.Unlock();
497
498
499   if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
500   {
501     //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
502     aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
503
504     // local size set at MESHCONST_ANALYSE step depends on
505     // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
506     if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
507     {
508       if ( !_hypParameters )
509         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
510       netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
511     }
512     // set local size depending on curvature and NOT closeness of EDGEs
513 #ifdef NETGEN_V6
514     const double factor = 2; //netgen::occparam.resthcloseedgefac;
515 #else
516     const double factor = netgen::occparam.resthcloseedgefac;
517     netgen::occparam.resthcloseedgeenable = false;
518     netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
519 #endif
520     occgeoComm.face_maxh = netgen::mparam.maxh;
521 #ifdef NETGEN_V6
522     netgen::OCCParameters occparam;
523     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
524 #else
525     aMesh.Lock();
526     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
527     aMesh.Unlock();
528 #endif
529     occgeoComm.emap.Clear();
530     occgeoComm.vmap.Clear();
531
532     // set local size according to size of existing segments
533     TopTools_IndexedMapOfShape edgeMap;
534     TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
535     for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
536     {
537       const TopoDS_Shape& edge = edgeMap( iE );
538       if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
539         continue;
540       SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
541       if ( !smDS ) continue;
542       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
543       while ( segIt->more() )
544       {
545         const SMDS_MeshElement* seg = segIt->next();
546         SMESH_TNodeXYZ n1 = seg->GetNode(0);
547         SMESH_TNodeXYZ n2 = seg->GetNode(1);
548         gp_XYZ p = 0.5 * ( n1 + n2 );
549         netgen::Point3d pi(p.X(), p.Y(), p.Z());
550         ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
551       }
552     }
553
554     // set local size defined on shapes
555     aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
556     aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
557     try {
558       ngMeshes[0]->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
559     } catch (NgException & ex) {
560       return error( COMPERR_BAD_PARMETERS, ex.What() );
561     }
562   }
563   netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
564   // ==================
565   // Loop on all FACEs
566   // ==================
567
568   vector< const SMDS_MeshNode* > nodeVec;
569
570   TopExp_Explorer fExp( aShape, TopAbs_FACE );
571   for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
572   {
573     TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
574     int    faceID = meshDS->ShapeToIndex( F );
575     SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
576
577     _quadraticMesh = helper.IsQuadraticSubMesh( F );
578     const bool ignoreMediumNodes = _quadraticMesh;
579
580     // build viscous layers if required
581     if ( F.Orientation() != TopAbs_FORWARD &&
582          F.Orientation() != TopAbs_REVERSED )
583       F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
584     SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
585     if ( !proxyMesh )
586       continue;
587
588     // ------------------------
589     // get all EDGEs of a FACE
590     // ------------------------
591     TSideVector wires =
592       StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, &helper, proxyMesh );
593     if ( faceErr && !faceErr->IsOK() )
594       continue;
595     size_t nbWires = wires.size();
596     if ( nbWires == 0 )
597     {
598       faceErr.reset
599         ( new SMESH_ComputeError
600           ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
601       continue;
602     }
603     if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
604     {
605       faceErr.reset
606         ( new SMESH_ComputeError
607           ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
608       continue;
609     }
610
611     // ----------------------
612     // compute maxh of a FACE
613     // ----------------------
614
615     if ( !_hypParameters )
616     {
617       double edgeLength = 0;
618       if (_hypLengthFromEdges )
619       {
620         // compute edgeLength as an average segment length
621         smIdType nbSegments = 0;
622         for ( size_t iW = 0; iW < nbWires; ++iW )
623         {
624           edgeLength += wires[ iW ]->Length();
625           nbSegments += wires[ iW ]->NbSegments();
626         }
627         if ( nbSegments )
628           edgeLength /= double( nbSegments );
629         netgen::mparam.maxh = edgeLength;
630       }
631       else if ( isDefaultHyp )
632       {
633         // set edgeLength by a longest segment
634         double maxSeg2 = 0;
635         for ( size_t iW = 0; iW < nbWires; ++iW )
636         {
637           const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
638           if ( points.empty() )
639             return error( COMPERR_BAD_INPUT_MESH );
640           gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
641           for ( size_t i = 1; i < points.size(); ++i )
642           {
643             gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
644             maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
645             pPrev = p;
646           }
647         }
648         edgeLength = sqrt( maxSeg2 ) * 1.05;
649         netgen::mparam.maxh = edgeLength;
650       }
651       if ( netgen::mparam.maxh < DBL_MIN )
652         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
653
654       if ( !isCommonLocalSize )
655       {
656         netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
657       }
658     }
659
660     // prepare occgeom
661     netgen::OCCGeometry occgeom;
662     occgeom.shape = F;
663     occgeom.fmap.Add( F );
664     occgeom.CalcBoundingBox();
665     occgeom.facemeshstatus.SetSize(1);
666     occgeom.facemeshstatus = 0;
667     occgeom.face_maxh_modified.SetSize(1);
668     occgeom.face_maxh_modified = 0;
669     occgeom.face_maxh.SetSize(1);
670     occgeom.face_maxh = netgen::mparam.maxh;
671
672     // -------------------------
673     // Fill netgen mesh
674     // -------------------------
675
676     // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
677     // w/o MESHCONST_ANALYSE at the second loop
678     int err = 0;
679     enum { LOC_SIZE, NO_LOC_SIZE };
680     int iLoop = isCommonLocalSize ? 0 : 1;
681     for ( ; iLoop < 2; iLoop++ )
682     {
683       //bool isMESHCONST_ANALYSE = false;
684       InitComputeError();
685
686       netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
687       ngMesh->DeleteMesh();
688
689       if ( iLoop == NO_LOC_SIZE )
690       {
691         ngMesh->SetGlobalH ( netgen::mparam.maxh );
692         ngMesh->SetMinimalH( netgen::mparam.minh );
693         Box<3> bb = occgeom.GetBoundingBox();
694         bb.Increase (bb.Diam()/10);
695         ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
696         aMesher.SetLocalSize( occgeom, *ngMesh );
697         aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
698         try {
699           ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
700         } catch (NgException & ex) {
701           return error( COMPERR_BAD_PARMETERS, ex.What() );
702         }
703       }
704
705       nodeVec.clear();
706       faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
707                                            /*overrideMinH=*/!_hypParameters);
708       if ( faceErr && !faceErr->IsOK() )
709         break;
710
711       //if ( !isCommonLocalSize )
712       //limitSize( ngMesh, netgen::mparam.maxh * 0.8);
713
714       // -------------------------
715       // Generate surface mesh
716       // -------------------------
717
718       const int startWith = MESHCONST_MESHSURFACE;
719       const int endWith   = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
720
721       SMESH_Comment str;
722       try {
723         OCC_CATCH_SIGNALS;
724         err = ngLib.GenerateMesh(occgeom, startWith, endWith, ngMesh);
725         if ( netgen::multithread.terminate )
726           return false;
727         if ( err )
728           str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
729       }
730       catch (Standard_Failure& ex)
731       {
732         err = 1;
733         str << "Exception in  netgen::OCCGenerateMesh()"
734             << " at " << netgen::multithread.task
735             << ": " << ex.DynamicType()->Name();
736         if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
737           str << ": " << ex.GetMessageString();
738       }
739       catch (...) {
740         err = 1;
741         str << "Exception in  netgen::OCCGenerateMesh()"
742             << " at " << netgen::multithread.task;
743       }
744       if ( err )
745       {
746         if ( aMesher.FixFaceMesh( occgeom, *ngMesh, 1 ))
747           break;
748         if ( iLoop == LOC_SIZE )
749         {
750           netgen::mparam.minh = netgen::mparam.maxh;
751           netgen::mparam.maxh = 0;
752           for ( size_t iW = 0; iW < wires.size(); ++iW )
753           {
754             StdMeshers_FaceSidePtr wire = wires[ iW ];
755             const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
756             for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
757             {
758               SMESH_TNodeXYZ   p( uvPtVec[ iP ].node );
759               netgen::Point3d np( p.X(),p.Y(),p.Z());
760               double segLen = p.Distance( uvPtVec[ iP-1 ].node );
761               double   size = ngMesh->GetH( np );
762               netgen::mparam.minh = Min( netgen::mparam.minh, size );
763              netgen:: mparam.maxh = Max( netgen::mparam.maxh, segLen );
764             }
765           }
766           //cerr << "min " << mparam.minh << " max " << mparam.maxh << endl;
767           netgen::mparam.minh *= 0.9;
768           netgen::mparam.maxh *= 1.1;
769           continue;
770         }
771         else
772         {
773           faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
774         }
775       }
776
777       // ----------------------------------------------------
778       // Fill the SMESHDS with the generated nodes and faces
779       // ----------------------------------------------------
780
781       int nbNodes = ngMesh->GetNP();
782       int nbFaces = ngMesh->GetNSE();
783
784       int nbInputNodes = (int) nodeVec.size()-1;
785       nodeVec.resize( nbNodes+1, 0 );
786
787       // add nodes
788       for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
789       {
790         const MeshPoint& ngPoint = ngMesh->Point( ngID );
791         SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
792         nodeVec[ ngID ] = node;
793       }
794
795       // create faces
796       int i,j;
797       vector<const SMDS_MeshNode*> nodes;
798       for ( i = 1; i <= nbFaces ; ++i )
799       {
800         const Element2d& elem = ngMesh->SurfaceElement(i);
801         nodes.resize( elem.GetNP() );
802         for (j=1; j <= elem.GetNP(); ++j)
803         {
804           int pind = elem.PNum(j);
805           if ( pind < 1 )
806             break;
807           nodes[ j-1 ] = nodeVec[ pind ];
808           if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
809           {
810             const PointGeomInfo& pgi = elem.GeomInfoPi(j);
811             meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
812           }
813         }
814         if ( j > elem.GetNP() )
815         {
816           if ( elem.GetType() == TRIG )
817             helper.AddFace(nodes[0],nodes[1],nodes[2]);
818           else
819             helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
820         }
821       }
822
823       break;
824     } // two attempts
825   } // loop on FACEs
826
827   return true;
828 }
829
830 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
831 {
832   SMESH_Algo::CancelCompute();
833   netgen::multithread.terminate = 1;
834 }
835
836 //================================================================================
837 /*!
838  * \brief Return progress of Compute() [0.,1]
839  */
840 //================================================================================
841
842 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
843 {
844   return -1;
845   // const char* task1 = "Surface meshing";
846   // //const char* task2 = "Optimizing surface";
847   // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
848   // if ( _progressByTic < 0. &&
849   //      strncmp( netgen::multithread.task, task1, 3 ) == 0 )
850   // {
851   //   progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
852   // }
853   // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
854   // {
855   //   if ( _progressByTic < 0 )
856   //   {
857   //     NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
858   //     me->_progressByTic = 0.25 / (_progressTic+1);
859   //   }
860   //   const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
861   //   progress = Max( progress, _progressByTic * _progressTic );
862   // }
863   // //cout << netgen::multithread.task << " " << _progressTic << endl;
864   // return Min( progress, 0.99 );
865 }
866
867 //=============================================================================
868 /*!
869  *
870  */
871 //=============================================================================
872
873 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
874                                            const TopoDS_Shape& aShape,
875                                            MapShapeNbElems& aResMap)
876 {
877   TopoDS_Face F = TopoDS::Face(aShape);
878   if(F.IsNull())
879     return false;
880
881   // collect info from edges
882   smIdType nb0d = 0, nb1d = 0;
883   bool IsQuadratic = false;
884   bool IsFirst = true;
885   double fullLen = 0.0;
886   TopTools_MapOfShape tmpMap;
887   for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
888     TopoDS_Edge E = TopoDS::Edge(exp.Current());
889     if( tmpMap.Contains(E) )
890       continue;
891     tmpMap.Add(E);
892     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
893     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
894     if( anIt==aResMap.end() ) {
895       SMESH_subMesh *sm = aMesh.GetSubMesh(F);
896       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
897       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
898       return false;
899     }
900     std::vector<smIdType> aVec = (*anIt).second;
901     nb0d += aVec[SMDSEntity_Node];
902     nb1d += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
903     double aLen = SMESH_Algo::EdgeLength(E);
904     fullLen += aLen;
905     if(IsFirst) {
906       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
907       IsFirst = false;
908     }
909   }
910   tmpMap.Clear();
911
912   // compute edge length
913   double ELen = 0;
914   if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
915     if ( nb1d > 0 )
916       ELen = fullLen / double( nb1d );
917   }
918   if ( _hypMaxElementArea ) {
919     double maxArea = _hypMaxElementArea->GetMaxArea();
920     ELen = sqrt(2. * maxArea/sqrt(3.0));
921   }
922   GProp_GProps G;
923   BRepGProp::SurfaceProperties(F,G);
924   double anArea = G.Mass();
925
926   const int hugeNb = numeric_limits<int>::max()/10;
927   if ( anArea / hugeNb > ELen*ELen )
928   {
929     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
930     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
931     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
932     return false;
933   }
934   smIdType nbFaces = (smIdType) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
935   smIdType nbNodes = (smIdType) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
936   std::vector<smIdType> aVec(SMDSEntity_Last);
937   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
938   if( IsQuadratic ) {
939     aVec[SMDSEntity_Node] = nbNodes;
940     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
941   }
942   else {
943     aVec[SMDSEntity_Node] = nbNodes;
944     aVec[SMDSEntity_Triangle] = nbFaces;
945   }
946   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
947   aResMap.insert(std::make_pair(sm,aVec));
948
949   return true;
950 }