1 // Copyright (C) 2007-2023 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 //=============================================================================
24 // File : NETGENPlugin_NETGEN_3D.cxx
25 // Moved here from SMESH_NETGEN_3D.cxx
26 // Created : lundi 27 Janvier 2003
27 // Author : Nadir BOUHAMOU (CEA)
29 //=============================================================================
31 #include "NETGENPlugin_NETGEN_3D.hxx"
33 #include "NETGENPlugin_Hypothesis.hxx"
35 #include <SMDS_MeshElement.hxx>
36 #include <SMDS_MeshNode.hxx>
37 #include <SMESHDS_Mesh.hxx>
38 #include <SMESH_Comment.hxx>
39 #include <SMESH_ControlsDef.hxx>
40 #include <SMESH_Gen.hxx>
41 #include <SMESH_Mesh.hxx>
42 #include <SMESH_MeshEditor.hxx>
43 #include <SMESH_MesherHelper.hxx>
44 #include <SMESH_subMesh.hxx>
45 #include <StdMeshers_MaxElementVolume.hxx>
46 #include <StdMeshers_QuadToTriaAdaptor.hxx>
47 #include <StdMeshers_ViscousLayers.hxx>
48 #include <SMESH_subMesh.hxx>
51 #include <BRepGProp.hxx>
52 #include <BRep_Tool.hxx>
53 #include <GProp_GProps.hxx>
55 #include <TopExp_Explorer.hxx>
56 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <Standard_Failure.hxx>
60 #include <Standard_ErrorHandler.hxx>
62 #include <utilities.h>
77 #include <occgeom.hpp>
80 #include <ngexception.hpp>
83 #include <core/exception.hpp>
91 NETGENPLUGIN_DLL_HEADER
92 extern MeshingParameters mparam;
94 NETGENPLUGIN_DLL_HEADER
95 extern volatile multithreadt multithread;
97 using namespace nglib;
100 //=============================================================================
104 //=============================================================================
106 NETGENPlugin_NETGEN_3D::NETGENPlugin_NETGEN_3D(int hypId, SMESH_Gen* gen)
107 : SMESH_3D_Algo(hypId, gen)
110 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
111 _compatibleHypothesis.push_back("MaxElementVolume");
112 _compatibleHypothesis.push_back("NETGEN_Parameters");
113 _compatibleHypothesis.push_back("ViscousLayers");
115 _maxElementVolume = 0.;
117 _hypMaxElementVolume = NULL;
118 _hypParameters = NULL;
119 _viscousLayersHyp = NULL;
121 _requireShape = false; // can work without shape
124 //=============================================================================
128 //=============================================================================
130 NETGENPlugin_NETGEN_3D::~NETGENPlugin_NETGEN_3D()
134 //=============================================================================
138 //=============================================================================
140 bool NETGENPlugin_NETGEN_3D::CheckHypothesis (SMESH_Mesh& aMesh,
141 const TopoDS_Shape& aShape,
142 Hypothesis_Status& aStatus)
144 _hypMaxElementVolume = NULL;
145 _hypParameters = NULL;
146 _viscousLayersHyp = NULL;
147 _maxElementVolume = DBL_MAX;
149 // for correct work of GetProgress():
150 //netgen::multithread.percent = 0.;
151 //netgen::multithread.task = "Volume meshing";
152 _progressByTic = -1.;
154 list<const SMESHDS_Hypothesis*>::const_iterator itl;
155 //const SMESHDS_Hypothesis* theHyp;
157 const list<const SMESHDS_Hypothesis*>& hyps =
158 GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
159 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
160 if ( h == hyps.end())
162 aStatus = SMESH_Hypothesis::HYP_OK;
163 return true; // can work with no hypothesis
167 for ( ; h != hyps.end(); ++h )
169 if ( !_hypMaxElementVolume )
170 _hypMaxElementVolume = dynamic_cast< const StdMeshers_MaxElementVolume*> ( *h );
171 if ( !_viscousLayersHyp ) // several _viscousLayersHyp's allowed
172 _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
173 if ( ! _hypParameters )
174 _hypParameters = dynamic_cast< const NETGENPlugin_Hypothesis*> ( *h );
176 if ( *h != _hypMaxElementVolume &&
177 *h != _viscousLayersHyp &&
178 *h != _hypParameters &&
179 !dynamic_cast< const StdMeshers_ViscousLayers*>(*h)) // several VL hyps allowed
180 aStatus = HYP_INCOMPATIBLE;
182 if ( _hypMaxElementVolume && _hypParameters )
183 aStatus = HYP_INCOMPATIBLE;
184 else if ( aStatus == HYP_OK && _viscousLayersHyp )
185 error( _viscousLayersHyp->CheckHypothesis( aMesh, aShape, aStatus ));
187 if ( _hypMaxElementVolume )
188 _maxElementVolume = _hypMaxElementVolume->GetMaxVolume();
190 return aStatus == HYP_OK;
195 //=============================================================================
197 *Here we are going to use the NETGEN mesher
199 //=============================================================================
203 * @brief Compute the list of already meshed Surface elements and info
204 * on their orientation and if they are internal
206 * @param aMesh Global Mesh
207 * @param aShape Shape associated to the mesh
208 * @param proxyMesh pointer to mesh used fo find the elements
209 * @param internals information on internal sub shapes
210 * @param helper helper associated to the mesh
211 * @param listElements map of surface element associated with
212 * their orientation and internal status
213 * @return true if their was some error
215 bool NETGENPlugin_NETGEN_3D::getSurfaceElements(
217 const TopoDS_Shape& aShape,
218 SMESH_ProxyMesh::Ptr proxyMesh,
219 NETGENPlugin_Internals &internals,
220 SMESH_MesherHelper &helper,
221 std::map<const SMDS_MeshElement*, tuple<bool, bool>, TIDCompare>& listElements
224 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
225 TopAbs_ShapeEnum mainType = aMesh.GetShapeToMesh().ShapeType();
226 bool checkReverse = ( mainType == TopAbs_COMPOUND || mainType == TopAbs_COMPSOLID );
228 for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
230 const TopoDS_Shape& aShapeFace = exFa.Current();
231 int faceID = meshDS->ShapeToIndex( aShapeFace );
232 bool isInternalFace = internals.isInternalShape( faceID );
234 if ( checkReverse && !isInternalFace &&
235 helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
236 // IsReversedSubMesh() can work wrong on strongly curved faces,
237 // so we use it as less as possible
238 isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
240 const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
241 if ( !aSubMeshDSFace ) continue;
243 SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
244 if ( _quadraticMesh &&
245 dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
247 // add medium nodes of proxy triangles to helper (#16843)
248 while ( iteratorElem->more() )
249 helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
251 iteratorElem = aSubMeshDSFace->GetElements();
253 while(iteratorElem->more()){
254 const SMDS_MeshElement* elem = iteratorElem->next();
257 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
259 if ( elem->NbCornerNodes() != 3 ){
260 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
262 listElements[elem] = tuple(isRev, isInternalFace);
270 * @brief Part of Compute: adding already meshed elements
271 * into netgen structure
273 * @param aMesh Global mesh
274 * @param aShape Shape associated with the mesh
275 * @param nodeVec Mapping between nodes mesh id and netgen structure id
276 * @param ngLib Wrapper on netgen lib
277 * @param helper helper assocaited to the mesh
278 * @param Netgen_NbOfNodes Number of nodes in netge structure
279 * @return true if there was some error
282 bool NETGENPlugin_NETGEN_3D::computeFillNgMesh(
284 const TopoDS_Shape& aShape,
285 vector< const SMDS_MeshNode* > &nodeVec,
286 NETGENPlugin_NetgenLibWrapper &ngLib,
287 SMESH_MesherHelper &helper,
288 int &Netgen_NbOfNodes)
290 netgen::multithread.terminate = 0;
291 netgen::multithread.task = "Volume meshing";
292 _progressByTic = -1.;
294 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
296 _quadraticMesh = helper.IsQuadraticSubMesh(aShape);
297 helper.SetElementsOnShape( true );
299 Netgen_NbOfNodes = 0;
300 double Netgen_point[3];
301 int Netgen_triangle[3];
303 Ng_Mesh * Netgen_mesh = (Ng_Mesh*)ngLib._ngMesh;
306 const int invalid_ID = -1;
308 SMESH::Controls::Area areaControl;
309 SMESH::Controls::TSequenceOfXYZ nodesCoords;
311 // maps nodes to ng ID
312 // map must be sorted by ID to ensure that we will have the same number of
313 // 3D element if we recompute
314 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
315 typedef TNodeToIDMap::value_type TN2ID;
316 TNodeToIDMap nodeToNetgenID;
318 // find internal shapes
319 NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
321 // ---------------------------------
322 // Feed the Netgen with surface mesh
323 // ---------------------------------
325 bool isInternalFace=false;
327 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
328 if ( _viscousLayersHyp )
330 netgen::multithread.percent = 3;
331 proxyMesh = _viscousLayersHyp->Compute( aMesh, aShape );
335 if ( aMesh.NbQuadrangles() > 0 )
337 netgen::multithread.percent = 6;
338 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
339 Adaptor->Compute(aMesh,aShape,proxyMesh.get());
340 proxyMesh.reset( Adaptor );
343 // map must be sorted by ID to ensure that we will have the same number of
344 // 3D element if we recompute
345 std::map<const SMDS_MeshElement*, tuple<bool, bool>, TIDCompare> listElements;
346 bool ret = getSurfaceElements(aMesh, aShape, proxyMesh, internals, helper, listElements);
350 for ( auto const& [elem, info] : listElements ) // loop on elements on a geom face
352 isRev = get<0>(info);
353 isInternalFace = get<1>(info);
354 // Add nodes of triangles and triangles them-selves to netgen mesh
356 // add three nodes of triangle
357 bool hasDegen = false;
358 for ( int iN = 0; iN < 3; ++iN )
360 const SMDS_MeshNode* node = elem->GetNode( iN );
361 const int shapeID = node->getshapeId();
362 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
363 helper.IsDegenShape( shapeID ))
365 // ignore all nodes on degeneraged edge and use node on its vertex instead
366 TopoDS_Shape vertex = TopoDS_Iterator( meshDS->IndexToShape( shapeID )).Value();
367 node = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), meshDS );
370 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
371 if ( ngID == invalid_ID )
373 ngID = ++Netgen_NbOfNodes;
374 Netgen_point [ 0 ] = node->X();
375 Netgen_point [ 1 ] = node->Y();
376 Netgen_point [ 2 ] = node->Z();
377 Ng_AddPoint(Netgen_mesh, Netgen_point);
379 Netgen_triangle[ isRev ? 2-iN : iN ] = ngID;
382 if ( hasDegen && (Netgen_triangle[0] == Netgen_triangle[1] ||
383 Netgen_triangle[0] == Netgen_triangle[2] ||
384 Netgen_triangle[2] == Netgen_triangle[1] ))
387 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
389 if ( isInternalFace && !proxyMesh->IsTemporary( elem ))
391 swap( Netgen_triangle[1], Netgen_triangle[2] );
392 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
394 } // loop on elements on a face
396 // insert old nodes into nodeVec
397 nodeVec.resize( nodeToNetgenID.size() + 1, 0 );
398 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
399 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
400 nodeVec[ n_id->second ] = n_id->first;
401 nodeToNetgenID.clear();
403 if ( internals.hasInternalVertexInSolid() )
405 netgen::OCCGeometry occgeo;
406 NETGENPlugin_Mesher::AddIntVerticesInSolids( occgeo,
407 (netgen::Mesh&) *Netgen_mesh,
412 Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
417 * @brief Part of Compute: Setting the netgen parameters from the Hypothesis
419 * @param aMesh Global mesh
420 * @param ngLib Wrapper on netgen lib
421 * @param occgeo Mapping between nodes mesh id and netgen structure id
422 * @param helper helper assocaited to the mesh
423 * @param endWith end step of netgen
424 * @return true if there was some error
426 bool NETGENPlugin_NETGEN_3D::computePrepareParam(
428 NETGENPlugin_NetgenLibWrapper &ngLib,
429 netgen::OCCGeometry &occgeo,
430 SMESH_MesherHelper &helper,
434 netgen::multithread.terminate = 0;
436 netgen::Mesh* ngMesh = ngLib._ngMesh;
438 NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
441 if ( _hypParameters )
443 aMesher.SetParameters( _hypParameters );
445 if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
446 !_hypParameters->GetMeshSizeFile().empty() )
448 if ( ! &ngMesh->LocalHFunction() )
450 netgen::Point3d pmin, pmax;
451 ngMesh->GetBox( pmin, pmax, 0 );
452 ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
454 aMesher.SetLocalSize( occgeo, *ngMesh );
457 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
458 } catch (netgen::NgException & ex) {
459 return error( COMPERR_BAD_PARMETERS, ex.What() );
462 if ( !_hypParameters->GetOptimize() )
463 endWith = netgen::MESHCONST_MESHVOLUME;
465 else if ( _hypMaxElementVolume )
467 netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
468 // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
470 else if ( aMesh.HasShapeToMesh() )
472 aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
473 netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
477 netgen::Point3d pmin, pmax;
478 ngMesh->GetBox (pmin, pmax);
479 netgen::mparam.maxh = Dist(pmin, pmax)/2;
482 if ( !_hypParameters && aMesh.HasShapeToMesh() )
484 netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
490 * @brief Part of Compute: call to the netgen mesher
492 * @param occgeo netgen geometry structure
493 * @param nodeVec Mapping between nodes mesh id and netgen structure id
494 * @param ngMesh netgen mesh structure
495 * @param ngLib Wrapper on netgen lib
496 * @param startWith starting step of netgen
497 * @param endWith end step of netgen
498 * @return true if there was some error
500 bool NETGENPlugin_NETGEN_3D::computeRunMesher(
501 netgen::OCCGeometry &occgeo,
502 vector< const SMDS_MeshNode* > &nodeVec,
503 netgen::Mesh* ngMesh,
504 NETGENPlugin_NetgenLibWrapper &ngLib,
505 int &startWith, int &endWith)
513 ngLib.CalcLocalH(ngMesh);
514 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
516 if(netgen::multithread.terminate)
519 error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
522 catch (Standard_Failure& ex)
524 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
525 str << " at " << netgen::multithread.task
526 << ": " << ex.DynamicType()->Name();
527 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
528 str << ": " << ex.GetMessageString();
531 catch (netgen::NgException& exc)
533 SMESH_Comment str("NgException");
534 if ( strlen( netgen::multithread.task ) > 0 )
535 str << " at " << netgen::multithread.task;
536 str << ": " << exc.What();
541 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
542 if ( strlen( netgen::multithread.task ) > 0 )
543 str << " at " << netgen::multithread.task;
549 SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
550 if ( ce && ce->HasBadElems() ){
559 * @brief Part of Compute: Adding new element created by mesher to SMESH_Mesh
561 * @param nodeVec Mapping between nodes mesh id and netgen structure id
562 * @param ngLib Wrapper on netgen lib
563 * @param helper tool associated to the mesh to add element
564 * @param Netgen_NbOfNodes Number of nodes in netgen structure
565 * @return true if there was some error
567 bool NETGENPlugin_NETGEN_3D::computeFillMesh(
568 vector< const SMDS_MeshNode* > &nodeVec,
569 NETGENPlugin_NetgenLibWrapper &ngLib,
570 SMESH_MesherHelper &helper,
571 int &Netgen_NbOfNodes
574 Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
576 int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
577 int Netgen_NbOfTetra = Ng_GetNE(Netgen_mesh);
579 bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
582 double Netgen_point[3];
583 int Netgen_tetrahedron[4];
585 // create and insert new nodes into nodeVec
586 nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
587 int nodeIndex = Netgen_NbOfNodes + 1;
588 for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
590 Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
591 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
594 // create tetrahedrons
595 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
597 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
600 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
601 nodeVec.at( Netgen_tetrahedron[1] ),
602 nodeVec.at( Netgen_tetrahedron[2] ),
603 nodeVec.at( Netgen_tetrahedron[3] ));
615 * @brief Compute mesh associate to shape
617 * @param aMesh The mesh
618 * @param aShape The shape
619 * @return true fi there are some error
621 bool NETGENPlugin_NETGEN_3D::Compute(
623 const TopoDS_Shape& aShape)
625 // vector of nodes in which node index == netgen ID
626 vector< const SMDS_MeshNode* > nodeVec;
627 NETGENPlugin_NetgenLibWrapper ngLib;
628 SMESH_MesherHelper helper(aMesh);
629 int startWith = netgen::MESHCONST_MESHVOLUME;
630 int endWith = netgen::MESHCONST_OPTVOLUME;
631 int Netgen_NbOfNodes;
633 computeFillNgMesh(aMesh, aShape, nodeVec, ngLib, helper, Netgen_NbOfNodes);
635 netgen::OCCGeometry occgeo;
636 computePrepareParam(aMesh, ngLib, occgeo, helper, endWith);
637 computeRunMesher(occgeo, nodeVec, ngLib._ngMesh, ngLib, startWith, endWith);
639 computeFillMesh(nodeVec, ngLib, helper, Netgen_NbOfNodes);
645 //================================================================================
647 * \brief set parameters and generate the volume mesh
649 //================================================================================
651 bool NETGENPlugin_NETGEN_3D::compute(SMESH_Mesh& aMesh,
652 SMESH_MesherHelper& helper,
653 vector< const SMDS_MeshNode* >& nodeVec,
654 NETGENPlugin_NetgenLibWrapper& ngLib)
656 netgen::multithread.terminate = 0;
658 netgen::Mesh* ngMesh = ngLib._ngMesh;
659 Ng_Mesh* Netgen_mesh = ngLib.ngMesh();
660 int Netgen_NbOfNodes = Ng_GetNP( Netgen_mesh );
662 int startWith = netgen::MESHCONST_MESHVOLUME;
663 int endWith = netgen::MESHCONST_OPTVOLUME;
666 NETGENPlugin_Mesher aMesher( &aMesh, helper.GetSubShape(), /*isVolume=*/true );
667 netgen::OCCGeometry occgeo;
669 if ( _hypParameters )
671 aMesher.SetParameters( _hypParameters );
673 if ( !_hypParameters->GetLocalSizesAndEntries().empty() ||
674 !_hypParameters->GetMeshSizeFile().empty() )
676 if ( ! &ngMesh->LocalHFunction() )
678 netgen::Point3d pmin, pmax;
679 ngMesh->GetBox( pmin, pmax, 0 );
680 ngMesh->SetLocalH( pmin, pmax, _hypParameters->GetGrowthRate() );
682 aMesher.SetLocalSize( occgeo, *ngMesh );
685 ngMesh->LoadLocalMeshSize( netgen::mparam.meshsizefilename );
686 } catch (netgen::NgException & ex) {
687 return error( COMPERR_BAD_PARMETERS, ex.What() );
690 if ( !_hypParameters->GetOptimize() )
691 endWith = netgen::MESHCONST_MESHVOLUME;
693 else if ( _hypMaxElementVolume )
695 netgen::mparam.maxh = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
696 // limitVolumeSize( ngMesh, mparam.maxh ); // result is unpredictable
698 else if ( aMesh.HasShapeToMesh() )
700 aMesher.PrepareOCCgeometry( occgeo, helper.GetSubShape(), aMesh );
701 netgen::mparam.maxh = occgeo.GetBoundingBox().Diam()/2;
705 netgen::Point3d pmin, pmax;
706 ngMesh->GetBox (pmin, pmax);
707 netgen::mparam.maxh = Dist(pmin, pmax)/2;
710 if ( !_hypParameters && aMesh.HasShapeToMesh() )
712 netgen::mparam.minh = aMesher.GetDefaultMinSize( helper.GetSubShape(), netgen::mparam.maxh );
719 ngLib.CalcLocalH(ngMesh);
720 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
722 if(netgen::multithread.terminate)
725 error(SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task);
727 catch (Standard_Failure& ex)
729 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
730 str << " at " << netgen::multithread.task
731 << ": " << ex.DynamicType()->Name();
732 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
733 str << ": " << ex.GetMessageString();
736 catch (netgen::NgException& exc)
738 SMESH_Comment str("NgException");
739 if ( strlen( netgen::multithread.task ) > 0 )
740 str << " at " << netgen::multithread.task;
741 str << ": " << exc.What();
746 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
747 if ( strlen( netgen::multithread.task ) > 0 )
748 str << " at " << netgen::multithread.task;
752 int Netgen_NbOfNodesNew = Ng_GetNP(Netgen_mesh);
753 int Netgen_NbOfTetra = Ng_GetNE(Netgen_mesh);
755 // -------------------------------------------------------------------
756 // Feed back the SMESHDS with the generated Nodes and Volume Elements
757 // -------------------------------------------------------------------
761 SMESH_ComputeErrorPtr ce = NETGENPlugin_Mesher::ReadErrors(nodeVec);
762 if ( ce && ce->HasBadElems() )
766 bool isOK = ( /*status == NG_OK &&*/ Netgen_NbOfTetra > 0 );// get whatever built
769 double Netgen_point[3];
770 int Netgen_tetrahedron[4];
772 // create and insert new nodes into nodeVec
773 nodeVec.resize( Netgen_NbOfNodesNew + 1, 0 );
774 int nodeIndex = Netgen_NbOfNodes + 1;
775 for ( ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
777 Ng_GetPoint( Netgen_mesh, nodeIndex, Netgen_point );
778 nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0], Netgen_point[1], Netgen_point[2]);
781 // create tetrahedrons
782 for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
784 Ng_GetVolumeElement(Netgen_mesh, elemIndex, Netgen_tetrahedron);
787 helper.AddVolume (nodeVec.at( Netgen_tetrahedron[0] ),
788 nodeVec.at( Netgen_tetrahedron[1] ),
789 nodeVec.at( Netgen_tetrahedron[2] ),
790 nodeVec.at( Netgen_tetrahedron[3] ));
801 //================================================================================
803 * \brief Compute tetrahedral mesh from 2D mesh without geometry
805 //================================================================================
807 bool NETGENPlugin_NETGEN_3D::Compute(SMESH_Mesh& aMesh,
808 SMESH_MesherHelper* aHelper)
810 const int invalid_ID = -1;
812 netgen::multithread.terminate = 0;
813 _progressByTic = -1.;
815 SMESH_MesherHelper::MType MeshType = aHelper->IsQuadraticMesh();
816 if ( MeshType == SMESH_MesherHelper::COMP )
817 return error( COMPERR_BAD_INPUT_MESH,
818 SMESH_Comment("Mesh with linear and quadratic elements given"));
820 aHelper->SetIsQuadratic( MeshType == SMESH_MesherHelper::QUADRATIC );
822 // ---------------------------------
823 // Feed the Netgen with surface mesh
824 // ---------------------------------
826 int Netgen_NbOfNodes = 0;
827 double Netgen_point[3];
828 int Netgen_triangle[3];
830 NETGENPlugin_NetgenLibWrapper ngLib;
831 Ng_Mesh * Netgen_mesh = ngLib.ngMesh();
833 SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
834 if ( aMesh.NbQuadrangles() > 0 )
836 StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor;
837 Adaptor->Compute(aMesh);
838 proxyMesh.reset( Adaptor );
840 if ( aHelper->IsQuadraticMesh() )
842 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
844 aHelper->AddTLinks( static_cast< const SMDS_MeshFace* >( fIt->next() ));
848 // maps nodes to ng ID
849 typedef map< const SMDS_MeshNode*, int, TIDCompare > TNodeToIDMap;
850 typedef TNodeToIDMap::value_type TN2ID;
851 TNodeToIDMap nodeToNetgenID;
853 SMDS_ElemIteratorPtr fIt = proxyMesh->GetFaces();
857 const SMDS_MeshElement* elem = fIt->next();
859 return error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
860 if ( elem->NbCornerNodes() != 3 )
861 return error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
863 // add three nodes of triangle
864 for ( int iN = 0; iN < 3; ++iN )
866 const SMDS_MeshNode* node = elem->GetNode( iN );
867 int& ngID = nodeToNetgenID.insert(TN2ID( node, invalid_ID )).first->second;
868 if ( ngID == invalid_ID )
870 ngID = ++Netgen_NbOfNodes;
871 Netgen_point [ 0 ] = node->X();
872 Netgen_point [ 1 ] = node->Y();
873 Netgen_point [ 2 ] = node->Z();
874 Ng_AddPoint(Netgen_mesh, Netgen_point);
876 Netgen_triangle[ iN ] = ngID;
878 Ng_AddSurfaceElement(Netgen_mesh, NG_TRIG, Netgen_triangle);
880 proxyMesh.reset(); // delete tmp faces
882 // vector of nodes in which node index == netgen ID
883 vector< const SMDS_MeshNode* > nodeVec ( nodeToNetgenID.size() + 1 );
884 // insert old nodes into nodeVec
885 TNodeToIDMap::iterator n_id = nodeToNetgenID.begin();
886 for ( ; n_id != nodeToNetgenID.end(); ++n_id )
887 nodeVec.at( n_id->second ) = n_id->first;
888 nodeToNetgenID.clear();
890 // -------------------------
891 // Generate the volume mesh
892 // -------------------------
894 return ( ngLib._isComputeOk = compute( aMesh, *aHelper, nodeVec, ngLib ));
897 void NETGENPlugin_NETGEN_3D::CancelCompute()
899 SMESH_Algo::CancelCompute();
900 netgen::multithread.terminate = 1;
903 //================================================================================
905 * \brief Return Compute progress
907 //================================================================================
909 double NETGENPlugin_NETGEN_3D::GetProgress() const
912 const char* volMeshing = "Volume meshing";
913 const char* dlnMeshing = "Delaunay meshing";
914 const double meshingRatio = 0.15;
915 const_cast<NETGENPlugin_NETGEN_3D*>( this )->_progressTic++;
917 if ( _progressByTic < 0. &&
918 ( strncmp( netgen::multithread.task, dlnMeshing, 3 ) == 0 ||
919 strncmp( netgen::multithread.task, volMeshing, 3 ) == 0 ))
921 res = 0.001 + meshingRatio * netgen::multithread.percent / 100.;
923 else // different otimizations
925 if ( _progressByTic < 0. )
926 ((NETGENPlugin_NETGEN_3D*)this)->_progressByTic = meshingRatio / _progressTic;
927 res = _progressByTic * _progressTic;
929 return Min ( res, 0.98 );
932 //=============================================================================
936 //=============================================================================
938 bool NETGENPlugin_NETGEN_3D::Evaluate(SMESH_Mesh& aMesh,
939 const TopoDS_Shape& aShape,
940 MapShapeNbElems& aResMap)
942 smIdType nbtri = 0, nbqua = 0;
943 double fullArea = 0.0;
944 for (TopExp_Explorer expF(aShape, TopAbs_FACE); expF.More(); expF.Next()) {
945 TopoDS_Face F = TopoDS::Face( expF.Current() );
946 SMESH_subMesh *sm = aMesh.GetSubMesh(F);
947 MapShapeNbElemsItr anIt = aResMap.find(sm);
948 if( anIt==aResMap.end() ) {
949 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
950 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Submesh can not be evaluated",this));
953 std::vector<smIdType> aVec = (*anIt).second;
954 nbtri += std::max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
955 nbqua += std::max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
957 BRepGProp::SurfaceProperties(F,G);
958 double anArea = G.Mass();
962 // collect info from edges
963 smIdType nb0d_e = 0, nb1d_e = 0;
964 bool IsQuadratic = false;
966 TopTools_MapOfShape tmpMap;
967 for (TopExp_Explorer expF(aShape, TopAbs_EDGE); expF.More(); expF.Next()) {
968 TopoDS_Edge E = TopoDS::Edge(expF.Current());
969 if( tmpMap.Contains(E) )
972 SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(expF.Current());
973 MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
974 if( anIt==aResMap.end() ) {
975 SMESH_ComputeErrorPtr& smError = aSubMesh->GetComputeError();
976 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
977 "Submesh can not be evaluated",this));
980 std::vector<smIdType> aVec = (*anIt).second;
981 nb0d_e += aVec[SMDSEntity_Node];
982 nb1d_e += std::max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
984 IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
990 double ELen_face = sqrt(2.* ( fullArea/double(nbtri+nbqua*2) ) / sqrt(3.0) );
991 double ELen_vol = pow( 72, 1/6. ) * pow( _maxElementVolume, 1/3. );
992 double ELen = Min(ELen_vol,ELen_face*2);
995 BRepGProp::VolumeProperties(aShape,G);
996 double aVolume = G.Mass();
997 double tetrVol = 0.1179*ELen*ELen*ELen;
998 double CoeffQuality = 0.9;
999 smIdType nbVols = (smIdType)( aVolume/tetrVol/CoeffQuality );
1000 smIdType nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
1001 smIdType nb1d_in = (nbVols*6 - nb1d_e - nb1d_f ) / 5;
1002 std::vector<smIdType> aVec(SMDSEntity_Last);
1003 for(smIdType i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
1005 aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
1006 aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
1007 aVec[SMDSEntity_Quad_Pyramid] = nbqua;
1010 aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
1011 aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
1012 aVec[SMDSEntity_Pyramid] = nbqua;
1014 SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
1015 aResMap.insert(std::make_pair(sm,aVec));