1 // Copyright (C) 2007-2022 CEA/DEN, EDF R&D, OPEN CASCADE
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : NETGENPlugin_NETGEN_2D_ONLY.cxx
21 // Author : Edward AGAPOV (OCC)
24 #include "NETGENPlugin_NETGEN_2D_ONLY.hxx"
26 #include "NETGENPlugin_Mesher.hxx"
27 #include "NETGENPlugin_Hypothesis_2D.hxx"
28 #include "NETGENPlugin_Provider.hxx"
29 #include "netgen_param.hxx"
31 #include <SMDS_MeshElement.hxx>
32 #include <SMDS_MeshNode.hxx>
33 #include <SMESHDS_Mesh.hxx>
34 #include <SMESH_Comment.hxx>
35 #include <SMESH_Gen.hxx>
36 #include <SMESH_Mesh.hxx>
37 #include <SMESH_MesherHelper.hxx>
38 #include <SMESH_subMesh.hxx>
39 #include <StdMeshers_FaceSide.hxx>
40 #include <StdMeshers_LengthFromEdges.hxx>
41 #include <StdMeshers_MaxElementArea.hxx>
42 #include <StdMeshers_QuadranglePreference.hxx>
43 #include <StdMeshers_ViscousLayers2D.hxx>
44 #include "DriverStep.hxx"
45 #include "DriverMesh.hxx"
48 #include <Precision.hxx>
49 #include <Standard_ErrorHandler.hxx>
50 #include <Standard_Failure.hxx>
52 #include <utilities.h>
59 #include <boost/filesystem.hpp>
60 namespace fs = boost::filesystem;
70 #include <occgeom.hpp>
71 #include <meshing.hpp>
72 //#include <meshtype.hpp>
74 NETGENPLUGIN_DLL_HEADER
75 extern MeshingParameters mparam;
77 extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
82 using namespace netgen;
83 using namespace nglib;
86 //=============================================================================
90 //=============================================================================
92 NETGENPlugin_NETGEN_2D_ONLY::NETGENPlugin_NETGEN_2D_ONLY(int hypId,
94 : SMESH_2D_Algo(hypId, gen)
96 _name = "NETGEN_2D_ONLY";
98 _shapeType = (1 << TopAbs_FACE);// 1 bit /shape type
99 _onlyUnaryInput = false; // treat all FACEs at once
101 _compatibleHypothesis.push_back("MaxElementArea");
102 _compatibleHypothesis.push_back("LengthFromEdges");
103 _compatibleHypothesis.push_back("QuadranglePreference");
104 _compatibleHypothesis.push_back("NETGEN_Parameters_2D");
105 _compatibleHypothesis.push_back("ViscousLayers2D");
107 _hypMaxElementArea = 0;
108 _hypLengthFromEdges = 0;
109 _hypQuadranglePreference = 0;
113 //=============================================================================
117 //=============================================================================
119 NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY()
121 //MESSAGE("NETGENPlugin_NETGEN_2D_ONLY::~NETGENPlugin_NETGEN_2D_ONLY");
124 //=============================================================================
128 //=============================================================================
130 bool NETGENPlugin_NETGEN_2D_ONLY::CheckHypothesis (SMESH_Mesh& aMesh,
131 const TopoDS_Shape& aShape,
132 Hypothesis_Status& aStatus)
134 _hypMaxElementArea = 0;
135 _hypLengthFromEdges = 0;
136 _hypQuadranglePreference = 0;
141 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
145 aStatus = HYP_OK; //SMESH_Hypothesis::HYP_MISSING;
146 return true; // (PAL13464) can work with no hypothesis, LengthFromEdges is default one
149 aStatus = HYP_MISSING;
152 list<const SMESHDS_Hypothesis*>::const_iterator ith;
153 for (ith = hyps.begin(); ith != hyps.end(); ++ith )
155 const SMESHDS_Hypothesis* hyp = (*ith);
157 string hypName = hyp->GetName();
159 if ( hypName == "MaxElementArea")
160 _hypMaxElementArea = static_cast<const StdMeshers_MaxElementArea*> (hyp);
161 else if ( hypName == "LengthFromEdges" )
162 _hypLengthFromEdges = static_cast<const StdMeshers_LengthFromEdges*> (hyp);
163 else if ( hypName == "QuadranglePreference" )
164 _hypQuadranglePreference = static_cast<const StdMeshers_QuadranglePreference*>(hyp);
165 else if ( hypName == "NETGEN_Parameters_2D" )
166 _hypParameters = static_cast<const NETGENPlugin_Hypothesis_2D*>(hyp);
167 else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
170 aStatus = HYP_INCOMPATIBLE;
175 int nbHyps = bool(_hypMaxElementArea) + bool(_hypLengthFromEdges) + bool(_hypParameters );
177 aStatus = HYP_CONCURRENT;
179 error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus ));
183 if ( aStatus == HYP_OK && _hypParameters && _hypQuadranglePreference )
185 aStatus = HYP_INCOMPAT_HYPS;
186 return error(SMESH_Comment("\"") << _hypQuadranglePreference->GetName()
187 << "\" and \"" << _hypParameters->GetName()
188 << "\" are incompatible hypotheses");
191 return ( aStatus == HYP_OK );
196 // void limitSize( netgen::Mesh* ngMesh,
197 // const double maxh )
200 // netgen::Point3d pmin, pmax;
201 // ngMesh->GetBox( pmin, pmax, 0 );
202 // const double dx = pmax.X() - pmin.X();
203 // const double dy = pmax.Y() - pmin.Y();
204 // const double dz = pmax.Z() - pmin.Z();
206 // const int nbX = Max( 2, int( dx / maxh * 3 ));
207 // const int nbY = Max( 2, int( dy / maxh * 3 ));
208 // const int nbZ = Max( 2, int( dz / maxh * 3 ));
210 // if ( ! & ngMesh->LocalHFunction() )
211 // ngMesh->SetLocalH( pmin, pmax, 0.1 );
213 // netgen::Point3d p;
214 // for ( int i = 0; i <= nbX; ++i )
216 // p.X() = pmin.X() + i * dx / nbX;
217 // for ( int j = 0; j <= nbY; ++j )
219 // p.Y() = pmin.Y() + j * dy / nbY;
220 // for ( int k = 0; k <= nbZ; ++k )
222 // p.Z() = pmin.Z() + k * dz / nbZ;
223 // ngMesh->RestrictLocalH( p, maxh );
231 // write in a binary file the orientation for each 2D element of the mesh
232 void NETGENPlugin_NETGEN_2D_ONLY::exportElementOrientation(SMESH_Mesh& aMesh,
233 const TopoDS_Shape& aShape,
234 netgen_params& aParams,
235 const std::string output_file)
237 std::map<vtkIdType, bool> elemOrientation;
239 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
240 for ( TopExp_Explorer exEd( aShape, TopAbs_EDGE ); exEd.More(); exEd.Next())
242 const TopoDS_Shape& aShapeEdge = exEd.Current();
243 const SMESHDS_SubMesh * aSubMeshDSEdge = proxyMesh->GetSubMesh( aShapeEdge );
244 if ( !aSubMeshDSEdge ) continue;
246 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSEdge->GetElements();
247 while ( iteratorElem->more() ) // loop on elements on a geom face
249 const SMDS_MeshElement* elem = iteratorElem->next();
250 elemOrientation[elem->GetID()] = aShapeEdge.Orientation() == TopAbs_INTERNAL;
254 std::ofstream df(output_file, ios::out|ios::binary);
255 int size=elemOrientation.size();
257 df.write((char*)&size, sizeof(int));
258 for(auto const& [id, orient]:elemOrientation){
259 df.write((char*)&id, sizeof(vtkIdType));
260 df.write((char*)&orient, sizeof(bool));
265 void NETGENPlugin_NETGEN_2D_ONLY::FillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
267 //TODO: factorize code with the one from NETGEN3D
268 // Move in netgen_param ?
269 aParams.maxh = hyp->GetMaxSize();
270 aParams.minh = hyp->GetMinSize();
271 aParams.segmentsperedge = hyp->GetNbSegPerEdge();
272 aParams.grading = hyp->GetGrowthRate();
273 aParams.curvaturesafety = hyp->GetNbSegPerRadius();
274 aParams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
275 aParams.quad = hyp->GetQuadAllowed() ? 1 : 0;
276 aParams.optimize = hyp->GetOptimize();
277 aParams.fineness = hyp->GetFineness();
278 aParams.uselocalh = hyp->GetSurfaceCurvature();
279 aParams.merge_solids = hyp->GetFuseEdges();
280 aParams.chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
281 aParams.optsteps2d = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
282 aParams.optsteps3d = aParams.optimize ? hyp->GetNbVolOptSteps() : 0;
283 aParams.elsizeweight = hyp->GetElemSizeWeight();
284 aParams.opterrpow = hyp->GetWorstElemMeasure();
285 aParams.delaunay = hyp->GetUseDelauney();
286 aParams.checkoverlap = hyp->GetCheckOverlapping();
287 aParams.checkchartboundary = hyp->GetCheckChartBoundary();
290 aParams.meshsizefilename = hyp->GetMeshSizeFile();
293 aParams.meshsizefilename = hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
296 aParams.closeedgefac = 2;
298 aParams.closeedgefac = 0;
300 aParams.has_LengthFromEdges_hyp = _hypLengthFromEdges;
302 //=============================================================================
304 *Here we are going to use the NETGEN mesher remotely
306 //=============================================================================
308 bool NETGENPlugin_NETGEN_2D_ONLY::RemoteCompute(SMESH_Mesh& aMesh,
309 const TopoDS_Shape& aShape)
312 SMESH_Hypothesis::Hypothesis_Status hypStatus;
313 CheckHypothesis(aMesh, aShape, hypStatus);
315 // Temporary folder for run
316 fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Face-%%%%-%%%%"));
317 fs::create_directories(tmp_folder);
318 // Using MESH2D generated after all triangles where created.
319 fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh1D.med");
320 fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
321 fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
322 fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
323 // TODO: Remove that file we do not use it
324 fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
325 fs::path shape_file=tmp_folder / fs::path("shape.step");
326 fs::path param_file=tmp_folder / fs::path("netgen2d_param.txt");
327 fs::path log_file=tmp_folder / fs::path("run_mesher.log");
328 //TODO: Handle variable mesh_name
329 std::string mesh_name = "Maillage_1";
332 export_shape(shape_file.string(), aShape);
334 netgen_params aParams;
335 FillParameters(_hypParameters, aParams);
337 export_netgen_params(param_file.string(), aParams);
339 // Exporting element orientation
340 exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
343 // Calling run_mesher
344 // TODO: check if we need to handle the .exe for windows
346 fs::path run_mesher_exe =
347 fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
350 fs::path("run_mesher");
351 cmd = run_mesher_exe.string() +
352 " NETGEN2D " + mesh_file.string() + " "
353 + shape_file.string() + " "
354 + param_file.string() + " "
355 + element_orientation_file.string() + " "
356 + new_element_file.string() + " "
357 + std::to_string(0) + " "
358 + output_mesh_file.string() +
359 " >> " + log_file.string();
361 std::cout << "Running command: " << std::endl;
362 std::cout << cmd << std::endl;
364 // Writing command in log
365 std::ofstream flog(log_file.string());
369 // TODO: Replace system by something else to handle redirection for windows
370 int ret = system(cmd.c_str());
372 // TODO: better error handling (display log ?)
375 //throw Exception("Meshing failed");
376 std::cerr << "Issue with command: " << std::endl;
377 std::cerr << cmd << std::endl;
382 std::ifstream df(new_element_file.string(), ios::binary);
384 int Netgen_NbOfNodes;
385 int Netgen_NbOfNodesNew;
387 double Netgen_point[3];
388 int Netgen_triangle[3];
391 SMESH_MesherHelper helper(aMesh);
392 // This function is necessary so that SetElementOnShape works
393 int _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
394 helper.SetElementsOnShape( true );
396 // Number of nodes in intial mesh
397 df.read((char*) &Netgen_NbOfNodes, sizeof(int));
398 // Number of nodes added by netgen
399 df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
401 // Filling nodevec (correspondence netgen numbering mesh numbering)
402 vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
403 for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
406 df.read((char*) &nodeID, sizeof(int));
407 nodeVec.at(nodeIndex) = nullptr;
408 SMDS_NodeIteratorPtr iteratorNode = aMesh.GetMeshDS()->nodesIterator();
409 while(iteratorNode->more()){
410 const SMDS_MeshNode* node = iteratorNode->next();
411 if(node->GetID() == nodeID){
412 nodeVec.at(nodeIndex) = node;
416 if(nodeVec.at(nodeIndex) == nullptr){
417 std::cout << "Error could not identify id";
422 // Add new points and update nodeVec
423 for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
425 df.read((char *) &Netgen_point, sizeof(double)*3);
427 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
433 df.read((char*) &Netgen_NbOfTria, sizeof(int));
434 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTria; ++elemIndex )
436 df.read((char*) &Netgen_triangle, sizeof(int)*3);
437 helper.AddFace (nodeVec.at( Netgen_triangle[0] ),
438 nodeVec.at( Netgen_triangle[1] ),
439 nodeVec.at( Netgen_triangle[2] ));
447 //=============================================================================
449 *Here we are going to use the NETGEN mesher
451 //=============================================================================
453 bool NETGENPlugin_NETGEN_2D_ONLY::Compute(SMESH_Mesh& aMesh,
454 const TopoDS_Shape& aShape)
457 if(aMesh.IsParallel())
458 return RemoteCompute(aMesh, aShape);
460 netgen::multithread.terminate = 0;
461 netgen::multithread.task = "Surface meshing";
463 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
464 SMESH_MesherHelper helper(aMesh);
465 helper.SetElementsOnShape( true );
467 NETGENPlugin_NetgenLibWrapper ngLib;
468 ngLib._isComputeOk = false;
470 netgen::Mesh ngMeshNoLocSize;
471 netgen::Mesh * ngMeshes[2] = { (netgen::Mesh*) ngLib._ngMesh, & ngMeshNoLocSize };
472 netgen::OCCGeometry occgeoComm;
474 // min / max sizes are set as follows:
475 // if ( _hypParameters )
476 // min and max are defined by the user
477 // else if ( _hypLengthFromEdges )
478 // min = aMesher.GetDefaultMinSize()
479 // max = average segment len of a FACE
480 // else if ( _hypMaxElementArea )
481 // min = aMesher.GetDefaultMinSize()
482 // max = f( _hypMaxElementArea )
484 // min = aMesher.GetDefaultMinSize()
485 // max = max segment len of a FACE
486 NETGENPlugin_Mesher aMesher( &aMesh, aShape, /*isVolume=*/false);
487 aMesher.SetParameters( _hypParameters ); // _hypParameters -> netgen::mparam
488 const bool toOptimize = _hypParameters ? _hypParameters->GetOptimize() : true;
489 if ( _hypMaxElementArea )
491 netgen::mparam.maxh = sqrt( 2. * _hypMaxElementArea->GetMaxArea() / sqrt(3.0) );
493 if ( _hypQuadranglePreference )
494 netgen::mparam.quad = true;
496 // local size is common for all FACEs in aShape?
497 const bool isCommonLocalSize = ( !_hypLengthFromEdges && !_hypMaxElementArea && netgen::mparam.uselocalh );
498 const bool isDefaultHyp = ( !_hypLengthFromEdges && !_hypMaxElementArea && !_hypParameters );
502 if ( isCommonLocalSize ) // compute common local size in ngMeshes[0]
504 //list< SMESH_subMesh* > meshedSM[4]; --> all sub-shapes are added to occgeoComm
505 aMesher.PrepareOCCgeometry( occgeoComm, aShape, aMesh );//, meshedSM );
507 // local size set at MESHCONST_ANALYSE step depends on
508 // minh, face_maxh, grading and curvaturesafety; find minh if not set by the user
509 if ( !_hypParameters || netgen::mparam.minh < DBL_MIN )
511 if ( !_hypParameters )
512 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam() / 3.;
513 netgen::mparam.minh = aMesher.GetDefaultMinSize( aShape, netgen::mparam.maxh );
515 // set local size depending on curvature and NOT closeness of EDGEs
517 const double factor = 2; //netgen::occparam.resthcloseedgefac;
519 const double factor = netgen::occparam.resthcloseedgefac;
520 netgen::occparam.resthcloseedgeenable = false;
521 netgen::occparam.resthcloseedgefac = 1.0 + netgen::mparam.grading;
523 occgeoComm.face_maxh = netgen::mparam.maxh;
525 netgen::OCCParameters occparam;
526 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0], netgen::mparam, occparam );
529 netgen::OCCSetLocalMeshSize( occgeoComm, *ngMeshes[0] );
532 occgeoComm.emap.Clear();
533 occgeoComm.vmap.Clear();
535 // set local size according to size of existing segments
536 TopTools_IndexedMapOfShape edgeMap;
537 TopExp::MapShapes( aMesh.GetShapeToMesh(), TopAbs_EDGE, edgeMap );
538 for ( int iE = 1; iE <= edgeMap.Extent(); ++iE )
540 const TopoDS_Shape& edge = edgeMap( iE );
541 if ( SMESH_Algo::isDegenerated( TopoDS::Edge( edge )))
543 SMESHDS_SubMesh* smDS = meshDS->MeshElements( edge );
544 if ( !smDS ) continue;
545 SMDS_ElemIteratorPtr segIt = smDS->GetElements();
546 while ( segIt->more() )
548 const SMDS_MeshElement* seg = segIt->next();
549 SMESH_TNodeXYZ n1 = seg->GetNode(0);
550 SMESH_TNodeXYZ n2 = seg->GetNode(1);
551 gp_XYZ p = 0.5 * ( n1 + n2 );
552 netgen::Point3d pi(p.X(), p.Y(), p.Z());
553 ngMeshes[0]->RestrictLocalH( pi, factor * ( n1 - n2 ).Modulus() );
557 // set local size defined on shapes
558 aMesher.SetLocalSize( occgeoComm, *ngMeshes[0] );
559 aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMeshes[0] );
561 ngMeshes[0]->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
562 } catch (NgException & ex) {
563 return error( COMPERR_BAD_PARMETERS, ex.What() );
566 netgen::mparam.uselocalh = toOptimize; // restore as it is used at surface optimization
567 // ==================
569 // ==================
571 vector< const SMDS_MeshNode* > nodeVec;
573 TopExp_Explorer fExp( aShape, TopAbs_FACE );
574 for ( int iF = 0; fExp.More(); fExp.Next(), ++iF )
576 TopoDS_Face F = TopoDS::Face( fExp.Current() /*.Oriented( TopAbs_FORWARD )*/);
577 int faceID = meshDS->ShapeToIndex( F );
578 SMESH_ComputeErrorPtr& faceErr = aMesh.GetSubMesh( F )->GetComputeError();
580 _quadraticMesh = helper.IsQuadraticSubMesh( F );
581 const bool ignoreMediumNodes = _quadraticMesh;
583 // build viscous layers if required
584 if ( F.Orientation() != TopAbs_FORWARD &&
585 F.Orientation() != TopAbs_REVERSED )
586 F.Orientation( TopAbs_FORWARD ); // avoid pb with TopAbs_INTERNAL
587 SMESH_ProxyMesh::Ptr proxyMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
591 // ------------------------
592 // get all EDGEs of a FACE
593 // ------------------------
595 StdMeshers_FaceSide::GetFaceWires( F, aMesh, ignoreMediumNodes, faceErr, &helper, proxyMesh );
596 if ( faceErr && !faceErr->IsOK() )
598 size_t nbWires = wires.size();
602 ( new SMESH_ComputeError
603 ( COMPERR_ALGO_FAILED, "Problem in StdMeshers_FaceSide::GetFaceWires()" ));
606 if ( wires[0]->NbSegments() < 3 ) // ex: a circle with 2 segments
609 ( new SMESH_ComputeError
610 ( COMPERR_BAD_INPUT_MESH, SMESH_Comment("Too few segments: ")<<wires[0]->NbSegments()) );
614 // ----------------------
615 // compute maxh of a FACE
616 // ----------------------
618 if ( !_hypParameters )
620 double edgeLength = 0;
621 if (_hypLengthFromEdges )
623 // compute edgeLength as an average segment length
624 smIdType nbSegments = 0;
625 for ( size_t iW = 0; iW < nbWires; ++iW )
627 edgeLength += wires[ iW ]->Length();
628 nbSegments += wires[ iW ]->NbSegments();
631 edgeLength /= double( nbSegments );
632 netgen::mparam.maxh = edgeLength;
634 else if ( isDefaultHyp )
636 // set edgeLength by a longest segment
638 for ( size_t iW = 0; iW < nbWires; ++iW )
640 const UVPtStructVec& points = wires[ iW ]->GetUVPtStruct();
641 if ( points.empty() )
642 return error( COMPERR_BAD_INPUT_MESH );
643 gp_Pnt pPrev = SMESH_TNodeXYZ( points[0].node );
644 for ( size_t i = 1; i < points.size(); ++i )
646 gp_Pnt p = SMESH_TNodeXYZ( points[i].node );
647 maxSeg2 = Max( maxSeg2, p.SquareDistance( pPrev ));
651 edgeLength = sqrt( maxSeg2 ) * 1.05;
652 netgen::mparam.maxh = edgeLength;
654 if ( netgen::mparam.maxh < DBL_MIN )
655 netgen::mparam.maxh = occgeoComm.GetBoundingBox().Diam();
657 if ( !isCommonLocalSize )
659 netgen::mparam.minh = aMesher.GetDefaultMinSize( F, netgen::mparam.maxh );
664 netgen::OCCGeometry occgeom;
666 occgeom.fmap.Add( F );
667 occgeom.CalcBoundingBox();
668 occgeom.facemeshstatus.SetSize(1);
669 occgeom.facemeshstatus = 0;
670 occgeom.face_maxh_modified.SetSize(1);
671 occgeom.face_maxh_modified = 0;
672 occgeom.face_maxh.SetSize(1);
673 occgeom.face_maxh = netgen::mparam.maxh;
675 // -------------------------
677 // -------------------------
679 // MESHCONST_ANALYSE step may lead to a failure, so we make an attempt
680 // w/o MESHCONST_ANALYSE at the second loop
682 enum { LOC_SIZE, NO_LOC_SIZE };
683 int iLoop = isCommonLocalSize ? 0 : 1;
684 for ( ; iLoop < 2; iLoop++ )
686 //bool isMESHCONST_ANALYSE = false;
689 netgen::Mesh * ngMesh = ngMeshes[ iLoop ];
690 ngMesh->DeleteMesh();
692 if ( iLoop == NO_LOC_SIZE )
694 ngMesh->SetGlobalH ( netgen::mparam.maxh );
695 ngMesh->SetMinimalH( netgen::mparam.minh );
696 Box<3> bb = occgeom.GetBoundingBox();
697 bb.Increase (bb.Diam()/10);
698 ngMesh->SetLocalH (bb.PMin(), bb.PMax(), netgen::mparam.grading);
699 aMesher.SetLocalSize( occgeom, *ngMesh );
700 aMesher.SetLocalSizeForChordalError( occgeoComm, *ngMesh );
702 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
703 } catch (NgException & ex) {
704 return error( COMPERR_BAD_PARMETERS, ex.What() );
709 faceErr = aMesher.AddSegmentsToMesh( *ngMesh, occgeom, wires, helper, nodeVec,
710 /*overrideMinH=*/!_hypParameters);
711 if ( faceErr && !faceErr->IsOK() )
714 //if ( !isCommonLocalSize )
715 //limitSize( ngMesh, netgen::mparam.maxh * 0.8);
717 // -------------------------
718 // Generate surface mesh
719 // -------------------------
721 const int startWith = MESHCONST_MESHSURFACE;
722 const int endWith = toOptimize ? MESHCONST_OPTSURFACE : MESHCONST_MESHSURFACE;
727 err = ngLib.GenerateMesh(occgeom, startWith, endWith, ngMesh);
728 if ( netgen::multithread.terminate )
731 str << "Error in netgen::OCCGenerateMesh() at " << netgen::multithread.task;
733 catch (Standard_Failure& ex)
736 str << "Exception in netgen::OCCGenerateMesh()"
737 << " at " << netgen::multithread.task
738 << ": " << ex.DynamicType()->Name();
739 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
740 str << ": " << ex.GetMessageString();
744 str << "Exception in netgen::OCCGenerateMesh()"
745 << " at " << netgen::multithread.task;
749 if ( aMesher.FixFaceMesh( occgeom, *ngMesh, 1 ))
751 if ( iLoop == LOC_SIZE )
753 netgen::mparam.minh = netgen::mparam.maxh;
754 netgen::mparam.maxh = 0;
755 for ( size_t iW = 0; iW < wires.size(); ++iW )
757 StdMeshers_FaceSidePtr wire = wires[ iW ];
758 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
759 for ( size_t iP = 1; iP < uvPtVec.size(); ++iP )
761 SMESH_TNodeXYZ p( uvPtVec[ iP ].node );
762 netgen::Point3d np( p.X(),p.Y(),p.Z());
763 double segLen = p.Distance( uvPtVec[ iP-1 ].node );
764 double size = ngMesh->GetH( np );
765 netgen::mparam.minh = Min( netgen::mparam.minh, size );
766 netgen:: mparam.maxh = Max( netgen::mparam.maxh, segLen );
769 //cerr << "min " << mparam.minh << " max " << mparam.maxh << endl;
770 netgen::mparam.minh *= 0.9;
771 netgen::mparam.maxh *= 1.1;
776 faceErr.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, str ));
780 // ----------------------------------------------------
781 // Fill the SMESHDS with the generated nodes and faces
782 // ----------------------------------------------------
784 int nbNodes = ngMesh->GetNP();
785 int nbFaces = ngMesh->GetNSE();
787 int nbInputNodes = (int) nodeVec.size()-1;
788 nodeVec.resize( nbNodes+1, 0 );
791 for ( int ngID = nbInputNodes + 1; ngID <= nbNodes; ++ngID )
793 const MeshPoint& ngPoint = ngMesh->Point( ngID );
794 SMDS_MeshNode * node = meshDS->AddNode(ngPoint(0), ngPoint(1), ngPoint(2));
795 nodeVec[ ngID ] = node;
800 vector<const SMDS_MeshNode*> nodes;
801 for ( i = 1; i <= nbFaces ; ++i )
803 const Element2d& elem = ngMesh->SurfaceElement(i);
804 nodes.resize( elem.GetNP() );
805 for (j=1; j <= elem.GetNP(); ++j)
807 int pind = elem.PNum(j);
810 nodes[ j-1 ] = nodeVec[ pind ];
811 if ( nodes[ j-1 ]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE )
813 const PointGeomInfo& pgi = elem.GeomInfoPi(j);
814 meshDS->SetNodeOnFace( nodes[ j-1 ], faceID, pgi.u, pgi.v);
817 if ( j > elem.GetNP() )
819 if ( elem.GetType() == TRIG )
820 helper.AddFace(nodes[0],nodes[1],nodes[2]);
822 helper.AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
833 void NETGENPlugin_NETGEN_2D_ONLY::CancelCompute()
835 SMESH_Algo::CancelCompute();
836 netgen::multithread.terminate = 1;
839 //================================================================================
841 * \brief Return progress of Compute() [0.,1]
843 //================================================================================
845 double NETGENPlugin_NETGEN_2D_ONLY::GetProgress() const
848 // const char* task1 = "Surface meshing";
849 // //const char* task2 = "Optimizing surface";
850 // double& progress = const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progress;
851 // if ( _progressByTic < 0. &&
852 // strncmp( netgen::multithread.task, task1, 3 ) == 0 )
854 // progress = Min( 0.25, SMESH_Algo::GetProgressByTic() ); // [0, 0.25]
856 // else //if ( strncmp( netgen::multithread.task, task2, 3 ) == 0)
858 // if ( _progressByTic < 0 )
860 // NETGENPlugin_NETGEN_2D_ONLY* me = (NETGENPlugin_NETGEN_2D_ONLY*) this;
861 // me->_progressByTic = 0.25 / (_progressTic+1);
863 // const_cast<NETGENPlugin_NETGEN_2D_ONLY*>( this )->_progressTic++;
864 // progress = Max( progress, _progressByTic * _progressTic );
866 // //cout << netgen::multithread.task << " " << _progressTic << endl;
867 // return Min( progress, 0.99 );
870 //=============================================================================
874 //=============================================================================
876 bool NETGENPlugin_NETGEN_2D_ONLY::Evaluate(SMESH_Mesh& aMesh,
877 const TopoDS_Shape& aShape,
878 MapShapeNbElems& aResMap)
880 TopoDS_Face F = TopoDS::Face(aShape);
884 // collect info from edges
885 smIdType nb0d = 0, nb1d = 0;
886 bool IsQuadratic = false;
888 double fullLen = 0.0;
889 TopTools_MapOfShape tmpMap;
890 for (TopExp_Explorer exp(F, TopAbs_EDGE); exp.More(); exp.Next()) {
891 TopoDS_Edge E = TopoDS::Edge(exp.Current());
892 if( tmpMap.Contains(E) )
895 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
896 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
897 if( anIt==aResMap.end() ) {
898 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
899 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
900 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
903 std::vector<smIdType> aVec = (*anIt).second;
904 nb0d += aVec[SMDSEntity_Node];
905 nb1d += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
906 double aLen = SMESH_Algo::EdgeLength(E);
909 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
915 // compute edge length
917 if (( _hypLengthFromEdges ) || ( !_hypLengthFromEdges && !_hypMaxElementArea )) {
919 ELen = fullLen / double( nb1d );
921 if ( _hypMaxElementArea ) {
922 double maxArea = _hypMaxElementArea->GetMaxArea();
923 ELen = sqrt(2. * maxArea/sqrt(3.0));
926 BRepGProp::SurfaceProperties(F,G);
927 double anArea = G.Mass();
929 const int hugeNb = numeric_limits<int>::max()/10;
930 if ( anArea / hugeNb > ELen*ELen )
932 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
933 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
934 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated.\nToo small element length",this));
937 smIdType nbFaces = (smIdType) ( anArea / ( ELen*ELen*sqrt(3.) / 4 ) );
938 smIdType nbNodes = (smIdType) ( ( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
939 std::vector<smIdType> aVec(SMDSEntity_Last);
940 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
942 aVec[SMDSEntity_Node] = nbNodes;
943 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
946 aVec[SMDSEntity_Node] = nbNodes;
947 aVec[SMDSEntity_Triangle] = nbFaces;
949 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
950 aResMap.insert(std::make_pair(sm,aVec));