]> SALOME platform Git repositories - plugins/netgenplugin.git/blob - src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cxx
Salome HOME
Renaming functions and files + minor corrections in runner_main to detect what to do
[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_DriverStep.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   //TODO: Handle variable mesh_name
328   std::string mesh_name = "Maillage_1";
329
330   //Writing Shape
331   exportShape(shape_file.string(), aShape);
332   //Writing hypo
333   netgen_params aParams;
334   FillParameters(_hypParameters, aParams);
335
336   exportNetgenParams(param_file.string(), aParams);
337
338   // Exporting element orientation
339   exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
340
341   aMesh.Unlock();
342   // Calling run_mesher
343   // TODO: check if we need to handle the .exe for windows
344   std::string cmd;
345   fs::path run_mesher_exe =
346     fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
347     fs::path("bin")/
348     fs::path("salome")/
349     fs::path("NETGENPlugin_Runner");
350   cmd = run_mesher_exe.string() +
351                   " NETGEN2D " + mesh_file.string() + " "
352                                + shape_file.string() + " "
353                                + param_file.string() + " "
354                                + element_orientation_file.string() + " "
355                                + new_element_file.string() + " "
356                                + std::to_string(0) + " "
357                                + output_mesh_file.string() +
358                                " >> " + log_file.string();
359
360   std::cout << "Running command: " << std::endl;
361   std::cout << cmd << std::endl;
362
363   // Writing command in log
364   std::ofstream flog(log_file.string());
365   flog << cmd << endl;
366   flog.close();
367
368   // TODO: Replace system by something else to handle redirection for windows
369   int ret = system(cmd.c_str());
370
371   // TODO: better error handling (display log ?)
372   if(ret != 0){
373     // Run crahed
374     //throw Exception("Meshing failed");
375     std::cerr << "Issue with command: " << std::endl;
376     std::cerr << cmd << std::endl;
377     return false;
378   }
379
380     aMesh.Lock();
381   std::ifstream df(new_element_file.string(), ios::binary);
382
383   int Netgen_NbOfNodes;
384   int Netgen_NbOfNodesNew;
385   int Netgen_NbOfTria;
386   double Netgen_point[3];
387   int    Netgen_triangle[3];
388   int nodeID;
389
390   SMESH_MesherHelper helper(aMesh);
391   // This function is necessary so that SetElementOnShape works
392   int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
393   helper.SetElementsOnShape( true );
394
395   // Number of nodes in intial mesh
396   df.read((char*) &Netgen_NbOfNodes, sizeof(int));
397   // Number of nodes added by netgen
398   df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
399
400   // Filling nodevec (correspondence netgen numbering mesh numbering)
401   vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
402   for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
403   {
404     //Id of the point
405     df.read((char*) &nodeID, sizeof(int));
406     nodeVec.at(nodeIndex) = nullptr;
407     SMDS_NodeIteratorPtr iteratorNode = aMesh.GetMeshDS()->nodesIterator();
408     while(iteratorNode->more()){
409       const SMDS_MeshNode* node = iteratorNode->next();
410       if(node->GetID() == nodeID){
411         nodeVec.at(nodeIndex) = node;
412         break;
413       }
414     }
415     if(nodeVec.at(nodeIndex) == nullptr){
416       std::cout << "Error could not identify id";
417       return false;
418     }
419   }
420
421   // Add new points and update nodeVec
422   for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
423   {
424     df.read((char *) &Netgen_point, sizeof(double)*3);
425
426     nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
427                                            Netgen_point[1],
428                                            Netgen_point[2]);
429   }
430
431   // Add tetrahedrons
432   df.read((char*) &Netgen_NbOfTria, sizeof(int));
433   for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTria; ++elemIndex )
434   {
435     df.read((char*) &Netgen_triangle, sizeof(int)*3);
436     helper.AddFace (nodeVec.at( Netgen_triangle[0] ),
437                     nodeVec.at( Netgen_triangle[1] ),
438                     nodeVec.at( Netgen_triangle[2] ));
439   }
440   df.close();
441
442   aMesh.Unlock();
443
444   return true;
445 }
446 //=============================================================================
447 /*!
448  *Here we are going to use the NETGEN mesher
449  */
450 //=============================================================================
451
452 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh&         aMesh,
453                                           const TopoDS_Shape& aShape)
454 {
455
456   if(aMesh.IsParallel())
457     return RemoteCompute(aMesh, aShape);
458
459   netgen::multithread.terminate = 0;
460   netgen::multithread.task = "Surface meshing";
461
462   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
463   SMESH_MesherHelper helper(aMesh);
464   helper.SetElementsOnShape( true );
465
466   NETGENPlugin_NetgenLibWrapper ngLib;
467   ngLib._isComputeOk = false;
468
469   netgen::Mesh   ngMeshNoLocSize;
470   netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh,  & ngMeshNoLocSize };
471   netgen::OCCGeometry occgeoComm;
472
473   // min / max sizes are set as follows:
474   // if ( _hypParameters )
475   //    min and max are defined by the user
476   // else if ( _hypLengthFromEdges )
477   //    min = aMesher.GetDefaultMinSize()
478   //    max = average segment len of a FACE
479   // else if ( _hypMaxElementArea )
480   //    min = aMesher.GetDefaultMinSize()
481   //    max = f( _hypMaxElementArea )
482   // else
483   //    min = aMesher.GetDefaultMinSize()
484   //    max = max segment len of a FACE
485   NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
486   aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
487   const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
488   if ( _hypMaxElementArea )
489   {
490     netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
491   }
492   if ( _hypQuadranglePreference )
493     netgen::mparam.quad = true;
494
495   // local size is common for all FACEs in aShape?
496   const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
497   const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
498   aMesh.Unlock();
499
500
501   if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
502   {
503     //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
504     aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
505
506     // local size set at MESHCONST_ANALYSE step depends on
507     // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
508     if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
509     {
510       if ( !_hypParameters )
511         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
512       netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
513     }
514     // set local size depending on curvature and NOT closeness of EDGEs
515 #ifdef NETGEN_V6
516     const double factor = 2; //netgen::occparam.resthcloseedgefac;
517 #else
518     const double factor = netgen::occparam.resthcloseedgefac;
519     netgen::occparam.resthcloseedgeenable = false;
520     netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
521 #endif
522     occgeoComm.face_maxh = netgen::mparam.maxh;
523 #ifdef NETGEN_V6
524     netgen::OCCParameters occparam;
525     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
526 #else
527     aMesh.Lock();
528     netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
529     aMesh.Unlock();
530 #endif
531     occgeoComm.emap.Clear();
532     occgeoComm.vmap.Clear();
533
534     // set local size according to size of existing segments
535     TopTools_IndexedMapOfShape edgeMap;
536     TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
537     for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
538     {
539       const TopoDS_Shape& edge = edgeMap( iE );
540       if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
541         continue;
542       SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
543       if ( !smDS ) continue;
544       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
545       while ( segIt->more() )
546       {
547         const SMDS_MeshElement* seg = segIt->next();
548         SMESH_TNodeXYZ n1 = seg->GetNode(0);
549         SMESH_TNodeXYZ n2 = seg->GetNode(1);
550         gp_XYZ p = 0.5 * ( n1 + n2 );
551         netgen::Point3d pi(p.X(), p.Y(), p.Z());
552         ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
553       }
554     }
555
556     // set local size defined on shapes
557     aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
558     aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
559     try {
560       ngMeshes[0]->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
561     } catch (NgException & ex) {
562       return error( COMPERR_BAD_PARMETERS, ex.What() );
563     }
564   }
565   netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
566   // ==================
567   // Loop on all FACEs
568   // ==================
569
570   vector< const SMDS_MeshNode* > nodeVec;
571
572   TopExp_Explorer fExp( aShape, TopAbs_FACE );
573   for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
574   {
575     TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
576     int    faceID = meshDS->ShapeToIndex( F );
577     SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
578
579     _quadraticMesh = helper.IsQuadraticSubMesh( F );
580     const bool ignoreMediumNodes = _quadraticMesh;
581
582     // build viscous layers if required
583     if ( F.Orientation() != TopAbs_FORWARD &&
584          F.Orientation() != TopAbs_REVERSED )
585       F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
586     SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
587     if ( !proxyMesh )
588       continue;
589
590     // ------------------------
591     // get all EDGEs of a FACE
592     // ------------------------
593     TSideVector wires =
594       StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, &helper, proxyMesh );
595     if ( faceErr && !faceErr->IsOK() )
596       continue;
597     size_t nbWires = wires.size();
598     if ( nbWires == 0 )
599     {
600       faceErr.reset
601         ( new SMESH_ComputeError
602           ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
603       continue;
604     }
605     if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
606     {
607       faceErr.reset
608         ( new SMESH_ComputeError
609           ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
610       continue;
611     }
612
613     // ----------------------
614     // compute maxh of a FACE
615     // ----------------------
616
617     if ( !_hypParameters )
618     {
619       double edgeLength = 0;
620       if (_hypLengthFromEdges )
621       {
622         // compute edgeLength as an average segment length
623         smIdType nbSegments = 0;
624         for ( size_t iW = 0; iW < nbWires; ++iW )
625         {
626           edgeLength += wires[ iW ]->Length();
627           nbSegments += wires[ iW ]->NbSegments();
628         }
629         if ( nbSegments )
630           edgeLength /= double( nbSegments );
631         netgen::mparam.maxh = edgeLength;
632       }
633       else if ( isDefaultHyp )
634       {
635         // set edgeLength by a longest segment
636         double maxSeg2 = 0;
637         for ( size_t iW = 0; iW < nbWires; ++iW )
638         {
639           const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
640           if ( points.empty() )
641             return error( COMPERR_BAD_INPUT_MESH );
642           gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
643           for ( size_t i = 1; i < points.size(); ++i )
644           {
645             gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
646             maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
647             pPrev = p;
648           }
649         }
650         edgeLength = sqrt( maxSeg2 ) * 1.05;
651         netgen::mparam.maxh = edgeLength;
652       }
653       if ( netgen::mparam.maxh < DBL_MIN )
654         netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
655
656       if ( !isCommonLocalSize )
657       {
658         netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
659       }
660     }
661
662     // prepare occgeom
663     netgen::OCCGeometry occgeom;
664     occgeom.shape = F;
665     occgeom.fmap.Add( F );
666     occgeom.CalcBoundingBox();
667     occgeom.facemeshstatus.SetSize(1);
668     occgeom.facemeshstatus = 0;
669     occgeom.face_maxh_modified.SetSize(1);
670     occgeom.face_maxh_modified = 0;
671     occgeom.face_maxh.SetSize(1);
672     occgeom.face_maxh = netgen::mparam.maxh;
673
674     // -------------------------
675     // Fill netgen mesh
676     // -------------------------
677
678     // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
679     // w/o MESHCONST_ANALYSE at the second loop
680     int err = 0;
681     enum { LOC_SIZE, NO_LOC_SIZE };
682     int iLoop = isCommonLocalSize ? 0 : 1;
683     for ( ; iLoop < 2; iLoop++ )
684     {
685       //bool isMESHCONST_ANALYSE = false;
686       InitComputeError();
687
688       netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
689       ngMesh->DeleteMesh();
690
691       if ( iLoop == NO_LOC_SIZE )
692       {
693         ngMesh->SetGlobalH ( netgen::mparam.maxh );
694         ngMesh->SetMinimalH( netgen::mparam.minh );
695         Box<3> bb = occgeom.GetBoundingBox();
696         bb.Increase (bb.Diam()/10);
697         ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
698         aMesher.SetLocalSize( occgeom, *ngMesh );
699         aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
700         try {
701           ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
702         } catch (NgException & ex) {
703           return error( COMPERR_BAD_PARMETERS, ex.What() );
704         }
705       }
706
707       nodeVec.clear();
708       faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
709                                            /*overrideMinH=*/!_hypParameters);
710       if ( faceErr && !faceErr->IsOK() )
711         break;
712
713       //if ( !isCommonLocalSize )
714       //limitSize( ngMesh, netgen::mparam.maxh * 0.8);
715
716       // -------------------------
717       // Generate surface mesh
718       // -------------------------
719
720       const int startWith = MESHCONST_MESHSURFACE;
721       const int endWith   = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
722
723       SMESH_Comment str;
724       try {
725         OCC_CATCH_SIGNALS;
726         err = ngLib.GenerateMesh(occgeom, startWith, endWith, ngMesh);
727         if ( netgen::multithread.terminate )
728           return false;
729         if ( err )
730           str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
731       }
732       catch (Standard_Failure& ex)
733       {
734         err = 1;
735         str << "Exception in  netgen::OCCGenerateMesh()"
736             << " at " << netgen::multithread.task
737             << ": " << ex.DynamicType()->Name();
738         if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
739           str << ": " << ex.GetMessageString();
740       }
741       catch (...) {
742         err = 1;
743         str << "Exception in  netgen::OCCGenerateMesh()"
744             << " at " << netgen::multithread.task;
745       }
746       if ( err )
747       {
748         if ( aMesher.FixFaceMesh( occgeom, *ngMesh, 1 ))
749           break;
750         if ( iLoop == LOC_SIZE )
751         {
752           netgen::mparam.minh = netgen::mparam.maxh;
753           netgen::mparam.maxh = 0;
754           for ( size_t iW = 0; iW < wires.size(); ++iW )
755           {
756             StdMeshers_FaceSidePtr wire = wires[ iW ];
757             const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
758             for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
759             {
760               SMESH_TNodeXYZ   p( uvPtVec[ iP ].node );
761               netgen::Point3d np( p.X(),p.Y(),p.Z());
762               double segLen = p.Distance( uvPtVec[ iP-1 ].node );
763               double   size = ngMesh->GetH( np );
764               netgen::mparam.minh = Min( netgen::mparam.minh, size );
765              netgen:: mparam.maxh = Max( netgen::mparam.maxh, segLen );
766             }
767           }
768           //cerr << "min " << mparam.minh << " max " << mparam.maxh << endl;
769           netgen::mparam.minh *= 0.9;
770           netgen::mparam.maxh *= 1.1;
771           continue;
772         }
773         else
774         {
775           faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
776         }
777       }
778
779       // ----------------------------------------------------
780       // Fill the SMESHDS with the generated nodes and faces
781       // ----------------------------------------------------
782
783       int nbNodes = ngMesh->GetNP();
784       int nbFaces = ngMesh->GetNSE();
785
786       int nbInputNodes = (int) nodeVec.size()-1;
787       nodeVec.resize( nbNodes+1, 0 );
788
789       // add nodes
790       for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
791       {
792         const MeshPoint& ngPoint = ngMesh->Point( ngID );
793         SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
794         nodeVec[ ngID ] = node;
795       }
796
797       // create faces
798       int i,j;
799       vector<const SMDS_MeshNode*> nodes;
800       for ( i = 1; i <= nbFaces ; ++i )
801       {
802         const Element2d& elem = ngMesh->SurfaceElement(i);
803         nodes.resize( elem.GetNP() );
804         for (j=1; j <= elem.GetNP(); ++j)
805         {
806           int pind = elem.PNum(j);
807           if ( pind < 1 )
808             break;
809           nodes[ j-1 ] = nodeVec[ pind ];
810           if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
811           {
812             const PointGeomInfo& pgi = elem.GeomInfoPi(j);
813             meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
814           }
815         }
816         if ( j > elem.GetNP() )
817         {
818           if ( elem.GetType() == TRIG )
819             helper.AddFace(nodes[0],nodes[1],nodes[2]);
820           else
821             helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
822         }
823       }
824
825       break;
826     } // two attempts
827   } // loop on FACEs
828
829   return true;
830 }
831
832 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
833 {
834   SMESH_Algo::CancelCompute();
835   netgen::multithread.terminate = 1;
836 }
837
838 //================================================================================
839 /*!
840  * \brief Return progress of Compute() [0.,1]
841  */
842 //================================================================================
843
844 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
845 {
846   return -1;
847   // const char* task1 = "Surface meshing";
848   // //const char* task2 = "Optimizing surface";
849   // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
850   // if ( _progressByTic < 0. &&
851   //      strncmp( netgen::multithread.task, task1, 3 ) == 0 )
852   // {
853   //   progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
854   // }
855   // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
856   // {
857   //   if ( _progressByTic < 0 )
858   //   {
859   //     NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
860   //     me->_progressByTic = 0.25 / (_progressTic+1);
861   //   }
862   //   const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
863   //   progress = Max( progress, _progressByTic * _progressTic );
864   // }
865   // //cout << netgen::multithread.task << " " << _progressTic << endl;
866   // return Min( progress, 0.99 );
867 }
868
869 //=============================================================================
870 /*!
871  *
872  */
873 //=============================================================================
874
875 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
876                                            const TopoDS_Shape& aShape,
877                                            MapShapeNbElems& aResMap)
878 {
879   TopoDS_Face F = TopoDS::Face(aShape);
880   if(F.IsNull())
881     return false;
882
883   // collect info from edges
884   smIdType nb0d = 0, nb1d = 0;
885   bool IsQuadratic = false;
886   bool IsFirst = true;
887   double fullLen = 0.0;
888   TopTools_MapOfShape tmpMap;
889   for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
890     TopoDS_Edge E = TopoDS::Edge(exp.Current());
891     if( tmpMap.Contains(E) )
892       continue;
893     tmpMap.Add(E);
894     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
895     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
896     if( anIt==aResMap.end() ) {
897       SMESH_subMesh *sm = aMesh.GetSubMesh(F);
898       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
899       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
900       return false;
901     }
902     std::vector<smIdType> aVec = (*anIt).second;
903     nb0d += aVec[SMDSEntity_Node];
904     nb1d += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
905     double aLen = SMESH_Algo::EdgeLength(E);
906     fullLen += aLen;
907     if(IsFirst) {
908       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
909       IsFirst = false;
910     }
911   }
912   tmpMap.Clear();
913
914   // compute edge length
915   double ELen = 0;
916   if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
917     if ( nb1d > 0 )
918       ELen = fullLen / double( nb1d );
919   }
920   if ( _hypMaxElementArea ) {
921     double maxArea = _hypMaxElementArea->GetMaxArea();
922     ELen = sqrt(2. * maxArea/sqrt(3.0));
923   }
924   GProp_GProps G;
925   BRepGProp::SurfaceProperties(F,G);
926   double anArea = G.Mass();
927
928   const int hugeNb = numeric_limits<int>::max()/10;
929   if ( anArea / hugeNb > ELen*ELen )
930   {
931     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
932     SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
933     smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
934     return false;
935   }
936   smIdType nbFaces = (smIdType) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
937   smIdType nbNodes = (smIdType) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
938   std::vector<smIdType> aVec(SMDSEntity_Last);
939   for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
940   if( IsQuadratic ) {
941     aVec[SMDSEntity_Node] = nbNodes;
942     aVec[SMDSEntity_Quad_Triangle] = nbFaces;
943   }
944   else {
945     aVec[SMDSEntity_Node] = nbNodes;
946     aVec[SMDSEntity_Triangle] = nbFaces;
947   }
948   SMESH_subMesh *sm = aMesh.GetSubMesh(F);
949   aResMap.insert(std::make_pair(sm,aVec));
950
951   return true;
952 }