1 // Copyright (C) 2007-2020 CEA/DEN, EDF R&D
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
21 // File : HexoticPlugin_Hexotic.cxx
22 // Author : Lioka RAZAFINDRAZAKA (CEA)
25 #include "HexoticPlugin_Hexotic.hxx"
26 #include "HexoticPlugin_Hypothesis.hxx"
27 #include "MG_Hexotic_API.hxx"
29 #include "utilities.h"
42 #include <SMESHDS_GroupBase.hxx>
43 #include <SMESHDS_Mesh.hxx>
44 #include <SMESH_ComputeError.hxx>
45 #include <SMESH_File.hxx>
46 #include <SMESH_Gen.hxx>
47 #include <SMESH_HypoFilter.hxx>
48 #include <SMESH_MesherHelper.hxx>
49 #include <SMESH_subMesh.hxx>
50 #include <SMESH_MeshEditor.hxx>
51 #include <SMESH_ControlPnt.hxx>
56 #include <Standard_ProgramError.hxx>
58 #include <BRepBndLib.hxx>
59 #include <BRepClass3d_SolidClassifier.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_Box.hxx>
62 #include <OSD_File.hxx>
63 #include <Precision.hxx>
64 #include <TopExp_Explorer.hxx>
65 #include <TopTools_MapOfShape.hxx>
67 #include <TopoDS_Vertex.hxx>
70 #include <Basics_Utils.hxx>
71 #include <GEOMImpl_Types.hxx>
72 #include <GEOM_wrap.hxx>
74 #define GMFVERSION GmfDouble
75 #define GMFDIMENSION 3
77 using SMESHUtils::ControlPnt;
79 static void removeFile( const TCollection_AsciiString& fileName )
82 OSD_File( fileName ).Remove();
84 catch ( Standard_ProgramError ) {
85 MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
89 //=============================================================================
93 //=============================================================================
95 HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, SMESH_Gen* gen)
96 : SMESH_3D_Algo(hypId, gen)
99 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
100 _onlyUnaryInput = false;
101 _requireShape = false;
104 _hexoticFilesKept=false;
105 _compatibleHypothesis.push_back( HexoticPlugin_Hypothesis::GetHypType() );
106 #ifdef WITH_BLSURFPLUGIN
109 _computeCanceled = false;
113 //=============================================================================
117 //=============================================================================
119 HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
124 #ifdef WITH_BLSURFPLUGIN
125 bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh& aMesh,
126 const TopoDS_Shape& aShape )
130 std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
131 const SMESHDS_Hypothesis* theHyp;
133 // If a BLSURF hypothesis is applied, get it
134 SMESH_HypoFilter blsurfFilter;
135 blsurfFilter.Init( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType(true) ));
136 blsurfFilter.Or ( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType(false)));
137 std::list<const SMESHDS_Hypothesis *> appliedHyps;
138 aMesh.GetHypotheses( aShape, blsurfFilter, appliedHyps, false );
140 if ( appliedHyps.size() > 0 ) {
141 itl = appliedHyps.begin();
142 theHyp = (*itl); // use only the first hypothesis
143 std::string hypName = theHyp->GetName();
144 if (hypName == BLSURFPlugin_Hypothesis::GetHypType(true) ||
145 hypName == BLSURFPlugin_Hypothesis::GetHypType(false) )
147 _blsurfHypo = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
156 //=============================================================================
160 //=============================================================================
162 bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh& aMesh,
163 const TopoDS_Shape& aShape,
164 SMESH_Hypothesis::Hypothesis_Status& aStatus )
168 std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
169 const SMESHDS_Hypothesis* theHyp;
171 const std::list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
172 int nbHyp = hyps.size();
174 // retrieve BLSURF hypothesis if no hexotic hypothesis has been set
175 #ifdef WITH_BLSURFPLUGIN
176 CheckBLSURFHypothesis(aMesh, aShape);
178 aStatus = SMESH_Hypothesis::HYP_OK;
179 return true; // can work with no hypothesis
183 theHyp = (*itl); // use only the first hypothesis
185 std::string hypName = theHyp->GetName();
186 if (hypName == HexoticPlugin_Hypothesis::GetHypType() ) {
187 _hypothesis = static_cast<const HexoticPlugin_Hypothesis*> (theHyp);
189 aStatus = SMESH_Hypothesis::HYP_OK;
192 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
194 #ifdef WITH_BLSURFPLUGIN
195 CheckBLSURFHypothesis(aMesh, aShape);
198 return aStatus == SMESH_Hypothesis::HYP_OK;
201 //=======================================================================
202 //function : findShape
204 //=======================================================================
206 static TopoDS_Shape findShape(SMDS_MeshNode** t_Node,
208 const TopoDS_Shape* t_Shape,
213 int iShape, nbNode = 8;
215 for ( int i=0; i<3; i++ ) {
217 for ( int j=0; j<nbNode; j++ ) {
218 if ( i == 0) pntCoor[i] += t_Node[j]->X();
219 if ( i == 1) pntCoor[i] += t_Node[j]->Y();
220 if ( i == 2) pntCoor[i] += t_Node[j]->Z();
222 pntCoor[i] /= nbNode;
224 gp_Pnt aPnt(pntCoor[0], pntCoor[1], pntCoor[2]);
226 if ( aShape.IsNull() ) aShape = t_Shape[0];
227 BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
228 if ( !(SC.State() == TopAbs_IN) ) {
230 for (iShape = 0; iShape < nShape && aShape.IsNull(); iShape++) {
231 if ( !( pntCoor[0] < t_Box[iShape][0] || t_Box[iShape][1] < pntCoor[0] ||
232 pntCoor[1] < t_Box[iShape][2] || t_Box[iShape][3] < pntCoor[1] ||
233 pntCoor[2] < t_Box[iShape][4] || t_Box[iShape][5] < pntCoor[2]) ) {
234 BRepClass3d_SolidClassifier SC (t_Shape[iShape], aPnt, Precision::Confusion());
235 if (SC.State() == TopAbs_IN)
236 aShape = t_Shape[iShape];
243 //=======================================================================
244 //function : getNbShape
246 //=======================================================================
248 static int getNbShape(MG_Hexotic_API* hexaOutput, int iMesh, GmfKwdCod what, int defaultValue=0)
250 int number = hexaOutput->GmfStatKwd( iMesh, what );
253 number = ( number + defaultValue + std::abs(number - defaultValue) ) / 2;
257 number = defaultValue;
262 //=======================================================================
263 //function : countShape
265 //=======================================================================
267 static int countShape( SMESH_Mesh* mesh, TopAbs_ShapeEnum shape )
269 if ( !mesh->HasShapeToMesh() )
271 TopExp_Explorer expShape ( mesh->GetShapeToMesh(), shape );
272 TopTools_MapOfShape mapShape;
274 for ( ; expShape.More(); expShape.Next() ) {
275 if (mapShape.Add(expShape.Current())) {
282 //=======================================================================
283 //function : getShape
285 //=======================================================================
287 template < class Mesh, class Shape, class Tab >
288 void getShape(Mesh* mesh, Shape shape, Tab *t_Shape)
290 TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
291 TopTools_MapOfShape mapShape;
292 for ( int i=0; expShape.More(); expShape.Next() ) {
293 if (mapShape.Add(expShape.Current())) {
294 t_Shape[i] = expShape.Current();
301 //=======================================================================
302 //function : printWarning
304 //=======================================================================
306 static void printWarning(const int nbExpected, std::string aString, const int nbFound) {
307 std::cout << std::endl;
308 std::cout << "WARNING : " << nbExpected << " " << aString << " expected, MG-Hexa has found " << nbFound << std::endl;
309 std::cout << "=======" << std::endl;
310 std::cout << std::endl;
314 //=======================================================================
315 //function : removeHexoticFiles
317 //=======================================================================
319 static void removeHexoticFiles(TCollection_AsciiString file_In, TCollection_AsciiString file_Out)
321 removeFile( file_In );
322 removeFile( file_Out );
325 //=======================================================================
326 //function : splitQuads
327 //purpose : splits all quadrangles into triangles
328 //=======================================================================
330 static void splitQuads(SMESH_Mesh& aMesh)
332 SMESH_MeshEditor spliter( &aMesh );
334 TIDSortedElemSet elems;
335 SMDS_ElemIteratorPtr eIt = aMesh.GetMeshDS()->elementsIterator();
337 elems.insert( elems.end(), eIt->next() );
339 spliter.QuadToTri ( elems, /*the13Diag=*/true);
342 //=======================================================================
343 //function : writeInput
344 //purpose : pass a mesh to input of MG-Hexa
345 //=======================================================================
347 static void writeInput(MG_Hexotic_API* theHexaInput,
349 const SMESHDS_Mesh* theMeshDS)
351 int meshID = theHexaInput->GmfOpenMesh( theFile, GmfWrite, GMFVERSION, GMFDIMENSION);
354 int iN = 0, nbNodes = theMeshDS->NbNodes();
355 theHexaInput->GmfSetKwd( meshID, GmfVertices, nbNodes );
356 std::map< const SMDS_MeshNode*, int, TIDCompare > node2IdMap;
357 SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
359 while ( nodeIt->more() )
361 n.Set( nodeIt->next() );
362 theHexaInput->GmfSetLin( meshID, GmfVertices, n.X(), n.Y(), n.Z(), n._node->getshapeId() );
363 node2IdMap.insert( node2IdMap.end(), std::make_pair( n._node, ++iN ));
367 SMDS_ElemIteratorPtr elemIt = theMeshDS->elementsIterator( SMDSAbs_Edge );
368 if ( elemIt->more() )
370 int nbEdges = theMeshDS->GetMeshInfo().NbElements( SMDSAbs_Edge );
371 theHexaInput->GmfSetKwd(meshID, GmfEdges, nbEdges );
372 for ( int gmfID = 1; elemIt->more(); ++gmfID )
374 const SMDS_MeshElement* edge = elemIt->next();
375 theHexaInput->GmfSetLin(meshID, GmfEdges,
376 node2IdMap[ edge->GetNode( 0 )],
377 node2IdMap[ edge->GetNode( 1 )],
378 edge->getshapeId() );
383 elemIt = theMeshDS->elementGeomIterator( SMDSGeom_TRIANGLE );
384 if ( elemIt->more() )
386 int nbTria = theMeshDS->GetMeshInfo().NbElements( SMDSGeom_TRIANGLE );
387 theHexaInput->GmfSetKwd(meshID, GmfTriangles, nbTria );
388 for ( int gmfID = 1; elemIt->more(); ++gmfID )
390 const SMDS_MeshElement* tria = elemIt->next();
391 theHexaInput->GmfSetLin(meshID, GmfTriangles,
392 node2IdMap[ tria->GetNode( 0 )],
393 node2IdMap[ tria->GetNode( 1 )],
394 node2IdMap[ tria->GetNode( 2 )],
395 tria->getshapeId() );
398 theHexaInput->GmfCloseMesh( meshID );
401 //=======================================================================
402 //function : readResult
403 //purpose : Read GMF file in case of a mesh with geometry
404 //=======================================================================
406 static bool readResult(MG_Hexotic_API* theHexaOutput,
408 HexoticPlugin_Hexotic*theAlgo,
409 SMESH_MesherHelper* theHelper,
410 const int nbShape = 0,
411 const TopoDS_Shape* tabShape = 0,
414 SMESH_Mesh* theMesh = theHelper->GetMesh();
415 SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
417 // ---------------------------------
418 // Read generated elements and nodes
419 // ---------------------------------
422 TopoDS_Vertex aVertex;
424 int shapeID, hexoticShapeID;
425 const int IdShapeRef = 2;
426 std::vector< int > tabID;
427 double epsilon = Precision::Confusion();
428 std::map <std::string,int> mapField;
429 std::vector< SMDS_MeshNode*> HexoticNode;
430 std::vector< TopoDS_Shape > tabCorner;
432 const int nbDomains = countShape( theMesh, TopAbs_SHELL );
433 const int holeID = -1;
437 tabID.resize( nbDomains, 0 );
438 if ( nbDomains == 1 )
439 tabID[0] = theMeshDS->ShapeToIndex( tabShape[0] );
443 tabID.resize( 1, 1 );
446 SMDS_ElemIteratorPtr eIt = theMeshDS->elementsIterator();
448 theMeshDS->RemoveFreeElement( eIt->next(), /*sm=*/0 );
449 SMDS_NodeIteratorPtr nIt = theMeshDS->nodesIterator();
450 while ( nIt->more() )
451 theMeshDS->RemoveFreeNode( nIt->next(), /*sm=*/0 );
453 theHelper->SetElementsOnShape( false );
456 int meshID = theHexaOutput->GmfOpenMesh( theFile, GmfRead, &ver, &dim );
458 int nbVertices = getNbShape(theHexaOutput, meshID, GmfVertices );
459 int nbCorners = getNbShape(theHexaOutput, meshID, GmfCorners, countShape( theMesh, TopAbs_VERTEX ));
460 if ( nbVertices == 0 )
463 tabCorner.resize( nbCorners );
464 HexoticNode.resize( nbVertices + 1 );
467 getShape( theMeshDS, TopAbs_VERTEX, tabCorner.data() );
469 int nbNodes = theHexaOutput->GmfStatKwd( meshID, GmfVertices );
472 theHexaOutput->GmfGotoKwd( meshID, GmfVertices );
474 for ( int aHexoticID = 1; aHexoticID <= nbNodes; ++aHexoticID )
476 if ( theAlgo->computeCanceled() )
478 theHexaOutput->GmfGetLin( meshID, GmfVertices, &x, &y, &z, &shapeID );
479 HexoticNode[ aHexoticID ] = theHelper->AddNode( x,y,z );
484 SMDS_MeshNode* node[8];
485 SMDS_MeshElement * aHexoticElement;
487 nbCorners = theHexaOutput->GmfStatKwd( meshID, GmfCorners );
488 if ( nbCorners > 0 && nbDomains > 0 )
490 theHexaOutput->GmfGotoKwd( meshID, GmfCorners );
491 for ( int iElem = 0; iElem < nbCorners; iElem++ )
493 if ( theAlgo->computeCanceled() )
495 theHexaOutput->GmfGetLin( meshID, GmfCorners, &nodeID[0] );
496 node[0] = HexoticNode[ nodeID[0] ];
497 gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
498 for ( int i = 0; i < nbCorners; i++ )
500 aVertex = TopoDS::Vertex( tabCorner[i] );
501 gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
502 if ( aPnt.Distance( HexoticPnt ) < epsilon )
504 theMeshDS->SetNodeOnVertex( node[0], aVertex );
511 int nbEdges = theHexaOutput->GmfStatKwd( meshID, GmfEdges );
514 theHexaOutput->GmfGotoKwd( meshID, GmfEdges );
515 for ( int iElem = 0; iElem < nbEdges; iElem++ )
517 if ( theAlgo->computeCanceled() )
519 theHexaOutput->GmfGetLin( meshID, GmfEdges, &nodeID[0], &nodeID[1], &shapeID );
520 for ( int i = 0; i < 2; ++i )
522 node[i] = HexoticNode[ nodeID[i]];
523 if ( shapeID > 0 && node[i]->getshapeId() < 1 )
524 theMeshDS->SetNodeOnEdge( node[i], shapeID );
526 aHexoticElement = theHelper->AddEdge( node[0], node[1] );
527 if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
528 theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
532 int nbQuad = theHexaOutput->GmfStatKwd( meshID, GmfQuadrilaterals );
535 theHexaOutput->GmfGotoKwd( meshID, GmfQuadrilaterals );
536 for ( int iElem = 0; iElem < nbQuad; iElem++ )
538 if ( theAlgo->computeCanceled() )
540 theHexaOutput->GmfGetLin( meshID, GmfQuadrilaterals,
541 &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3], &shapeID );
542 for ( int i = 0; i < 4; ++i )
544 node[i] = HexoticNode[ nodeID[i]];
545 if ( shapeID > 0 && node[i]->getshapeId() < 1 )
546 theMeshDS->SetNodeOnFace( node[i], shapeID );
548 aHexoticElement = theHelper->AddFace( node[0], node[1], node[2], node[3] );
549 if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
550 theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
554 int nbHexa = theHexaOutput->GmfStatKwd( meshID, GmfHexahedra );
557 theHexaOutput->GmfGotoKwd( meshID, GmfHexahedra );
558 for ( int iElem = 0; iElem < nbHexa; iElem++ )
560 if ( theAlgo->computeCanceled() )
562 theHexaOutput->GmfGetLin( meshID, GmfHexahedra,
563 &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3],
564 &nodeID[4], &nodeID[5], &nodeID[6], &nodeID[7],
566 for ( int i = 0; i < 8; ++i )
568 node[i] = HexoticNode[ nodeID[i]];
570 if ( nbDomains > 1 ) {
571 hexoticShapeID = shapeID - IdShapeRef;
572 if ( tabID[ hexoticShapeID ] == 0 ) {
573 aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
574 shapeID = aShape.IsNull() ? holeID : theMeshDS->ShapeToIndex( aShape );
575 tabID[ hexoticShapeID ] = shapeID;
578 shapeID = tabID[ hexoticShapeID ];
580 if ( iElem == ( nbHexa - 1) ) {
581 int shapeAssociated = 0;
582 for ( int i=0; i<nbDomains; i++ ) {
584 shapeAssociated += 1;
586 if ( shapeAssociated != nbShape )
587 printWarning(nbShape, "domains", shapeAssociated);
594 if ( shapeID != holeID )
596 for ( int i = 0; i < 8; ++i )
598 if ( node[i]->NbInverseElements( SMDSAbs_Face ) == 0 )
599 theMeshDS->SetNodeInVolume( node[i], shapeID );
601 aHexoticElement = theHelper->AddVolume( node[0], node[3], node[2], node[1],
602 node[4], node[7], node[6], node[5]);
603 if ( aHexoticElement->getshapeId() < 1 )
604 theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
608 std::cout << std::endl;
610 // remove nodes in holes
613 SMESHDS_SubMesh* subMesh = 0;
614 for ( int i = 1; i <= nbNodes; ++i )
615 if ( HexoticNode[i]->NbInverseElements() == 0 )
617 theMeshDS->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
621 // avoid "Error: No mesh on sub-shape"
622 if ( theMesh->NbVolumes() > 0 )
624 SMESH_subMesh* smMain = theMesh->GetSubMesh( theMesh->GetShapeToMesh() );
625 SMESH_subMeshIteratorPtr smIt = smMain->getDependsOnIterator( /*includeSelf=*/true );
626 while ( smIt->more() )
628 SMESH_subMesh* sm = smIt->next();
629 if ( !sm->IsMeshComputed() )
630 sm->SetIsAlwaysComputed( true );
637 //=============================================================================
639 * Pass parameters to MG-Hexa
641 //=============================================================================
643 void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp)
646 _hexesMinLevel = hyp->GetHexesMinLevel();
647 _hexesMaxLevel = hyp->GetHexesMaxLevel();
648 _hexesMinSize = hyp->GetMinSize();
649 _hexesMaxSize = hyp->GetMaxSize();
650 _approxAngle = hyp->GetGeomApproxAngle();
651 _hexoticIgnoreRidges = hyp->GetHexoticIgnoreRidges();
652 _hexoticInvalidElements = hyp->GetHexoticInvalidElements();
653 _hexoticSharpAngleThreshold = hyp->GetHexoticSharpAngleThreshold();
654 _hexoticNbProc = hyp->GetHexoticNbProc();
655 _hexoticWorkingDirectory = hyp->GetHexoticWorkingDirectory();
656 _hexoticVerbosity = hyp->GetHexoticVerbosity();
657 _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
658 _hexoticSdMode = hyp->GetHexoticSdMode();
659 _textOptions = hyp->GetAdvancedOption();
660 _sizeMaps = hyp->GetSizeMaps();
661 _nbLayers = hyp->GetNbLayers();
662 _firstLayerSize = hyp->GetFirstLayerSize();
663 _direction = hyp->GetDirection();
664 _growth = hyp->GetGrowth();
665 _facesWithLayers = hyp->GetFacesWithLayers();
666 _imprintedFaces = hyp->GetImprintedFaces();
667 _keepFiles = hyp->GetKeepFiles();
668 _removeLogOnSuccess = hyp->GetRemoveLogOnSuccess();
669 _logInStandardOutput = hyp->GetStandardOutputLog();
672 std::cout << std::endl;
673 std::cout << "WARNING : The MG-Hexa default parameters are taken into account" << std::endl;
674 std::cout << "=======" << std::endl;
675 _hexesMinLevel = hyp->GetDefaultHexesMinLevel();
676 _hexesMaxLevel = hyp->GetDefaultHexesMaxLevel();
677 _hexesMinSize = hyp->GetDefaultMinSize();
678 _hexesMaxSize = hyp->GetDefaultMaxSize();
679 _approxAngle = hyp->GetDefaultGeomApproxAngle();
680 _hexoticIgnoreRidges = hyp->GetDefaultHexoticIgnoreRidges();
681 _hexoticInvalidElements = hyp->GetDefaultHexoticInvalidElements();
682 _hexoticSharpAngleThreshold = hyp->GetDefaultHexoticSharpAngleThreshold();
683 _hexoticNbProc = hyp->GetDefaultHexoticNbProc();
684 _hexoticWorkingDirectory = hyp->GetDefaultHexoticWorkingDirectory();
685 _hexoticVerbosity = hyp->GetDefaultHexoticVerbosity();
686 _hexoticMaxMemory = hyp->GetDefaultHexoticMaxMemory();
687 _hexoticSdMode = hyp->GetDefaultHexoticSdMode();
688 _textOptions = hyp->GetDefaultTextOptions();
689 _sizeMaps = hyp->GetDefaultHexoticSizeMaps();
690 _nbLayers = hyp->GetDefaultNbLayers();
691 _firstLayerSize = hyp->GetDefaultFirstLayerSize();
692 _direction = hyp->GetDefaultDirection();
693 _growth = hyp->GetDefaultGrowth();
694 _facesWithLayers = hyp->GetDefaultFacesWithLayers();
695 _imprintedFaces = hyp->GetDefaultImprintedFaces();
696 _keepFiles = hyp->GetDefaultKeepFiles();
697 _removeLogOnSuccess = hyp->GetDefaultRemoveLogOnSuccess();
698 _logInStandardOutput = hyp->GetDefaultStandardOutputLog();
702 //=======================================================================
703 //function : getSuffix
704 //purpose : Returns a suffix that will be unique for the current process
705 //=======================================================================
707 static TCollection_AsciiString getSuffix()
709 TCollection_AsciiString aSuffix = "";
712 aSuffix += getenv("USER");
714 std::string uname = std::string(getenv("USERNAME"));
715 replace(uname.begin(), uname.end(), ' ', '_');
716 aSuffix += uname.c_str();
719 aSuffix += Kernel_Utils::GetHostname().c_str();
724 aSuffix += _getpid();
730 //================================================================================
732 * \brief Returns a command to run MG-Hexa mesher
734 //================================================================================
737 HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
738 const TCollection_AsciiString& Hexotic_Out,
739 const TCollection_AsciiString& Hexotic_SizeMap_Prefix,
740 const bool forExecutable) const
742 std::cout << std::endl;
743 std::cout << "MG-Hexa execution..." << std::endl;
744 std::cout << _name << " parameters :" << std::endl;
745 std::cout << " " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
746 std::cout << " " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
747 std::cout << " " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
748 std::cout << " " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
749 std::cout << " " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
750 std::cout << " " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
751 std::cout << " " << "MG-Hexa can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
752 std::cout << " " << "MG-Hexa authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
753 std::cout << " " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
754 std::cout << " " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
755 std::cout << " " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
756 std::cout << " " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
757 std::cout << " " << _name << " Text options = \"" << _textOptions << "\"" << std::endl;
758 std::cout << " " << _name << " Number of layers = " << _nbLayers << std::endl;
759 std::cout << " " << _name << " Size of the first layer = " << _firstLayerSize << std::endl;
760 std::cout << " " << _name << " Direction of the layers = " << ( _direction ? "Inward" : "Outward" ) << std::endl;
761 std::cout << " " << _name << " Growth = " << _growth << std::endl;
762 if (!_facesWithLayers.empty()) {
763 std::cout << " " << _name << " Faces with layers = ";
764 for (size_t i = 0; i < _facesWithLayers.size(); i++)
766 std::cout << _facesWithLayers.at(i);
767 if ((i + 1) != _facesWithLayers.size())
770 std::cout << std::endl;
772 if (!_imprintedFaces.empty()) {
773 std::cout << " " << _name << " Imprinted faces = ";
774 for (size_t i = 0; i < _imprintedFaces.size(); i++)
776 std::cout << _imprintedFaces.at(i);
777 if ((i + 1) != _imprintedFaces.size())
780 std::cout << std::endl;
783 TCollection_AsciiString run_Hexotic("mg-hexa.exe");
785 TCollection_AsciiString minl = " --min_level ", maxl = " --max_level ", angle = " --ridge_angle ";
786 TCollection_AsciiString mins = " --min_size ", maxs = " --max_size ";
787 TCollection_AsciiString in = " --in ", out = " --out ";
788 TCollection_AsciiString sizeMap = " --read_sizemap ";
789 TCollection_AsciiString ignoreRidges = " --compute_ridges no ", invalideElements = " --allow_invalid_elements yes ";
790 TCollection_AsciiString subdom = " --components ";
792 TCollection_AsciiString proc = " --max_number_of_threads ";
794 TCollection_AsciiString verb = " --verbose ";
795 TCollection_AsciiString maxmem = " --max_memory ";
797 TCollection_AsciiString comNbLayers = " --number_of_boundary_layers ";
798 TCollection_AsciiString comFirstLayerSize = " --height_of_the_first_layer ";
799 TCollection_AsciiString comDirection = " --boundary_layers_subdomain_direction ";
800 TCollection_AsciiString comGrowth = " --boundary_layers_geometric_progression ";
801 TCollection_AsciiString comFacesWithLayers = " --boundary_layers_surface_ids ";
802 TCollection_AsciiString comImptintedFaces = " --imprinted_surface_ids ";
804 TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory,
805 textOptions, nbLayers, firstLayerSize, direction, growth, facesWithLayers, imprintedFaces;
806 minLevel = _hexesMinLevel;
807 maxLevel = _hexesMaxLevel;
808 minSize = _hexesMinSize;
809 maxSize = _hexesMaxSize;
810 sharpAngle = _hexoticSharpAngleThreshold;
811 // Mode translation for mg-tetra 1.1
812 switch ( _hexoticSdMode )
815 mode = "outside_skin_only";
818 mode = "outside_components";
824 mode = "all --manifold_geometry no";
827 nbproc = _hexoticNbProc;
828 verbosity = _hexoticVerbosity;
829 maxMemory = _hexoticMaxMemory;
830 textOptions = (" " + _textOptions + " ").c_str();
831 nbLayers = _nbLayers;
832 firstLayerSize = _firstLayerSize;
833 direction = _direction ? "1" : "-1";
835 for (size_t i = 0; i < _facesWithLayers.size(); i++)
837 facesWithLayers += _facesWithLayers[i];
838 if ((i + 1) != _facesWithLayers.size())
839 facesWithLayers += ",";
841 for (size_t i = 0; i < _imprintedFaces.size(); i++)
843 imprintedFaces += _imprintedFaces[i];
844 if ((i + 1) != _imprintedFaces.size())
845 imprintedFaces += ",";
848 if (_hexoticIgnoreRidges)
849 run_Hexotic += ignoreRidges;
851 if (_hexoticInvalidElements)
852 run_Hexotic += invalideElements;
854 if (_hexesMinSize > 0)
855 run_Hexotic += mins + minSize;
857 if (_hexesMaxSize > 0)
858 run_Hexotic += maxs + maxSize;
860 if (_hexesMinLevel > 0)
861 run_Hexotic += minl + minLevel;
863 if (_hexesMaxLevel > 0)
864 run_Hexotic += maxl + maxLevel;
866 if (_hexoticSharpAngleThreshold > 0)
867 run_Hexotic += angle + sharpAngle;
869 if (_sizeMaps.begin() != _sizeMaps.end() && forExecutable )
870 run_Hexotic += sizeMap + Hexotic_SizeMap_Prefix;
873 _firstLayerSize > 0 &&
875 !_facesWithLayers.empty())
877 run_Hexotic += comNbLayers + nbLayers;
878 run_Hexotic += comFirstLayerSize + firstLayerSize;
879 run_Hexotic += comDirection + direction;
880 run_Hexotic += comGrowth + growth;
881 run_Hexotic += comFacesWithLayers + facesWithLayers;
882 if (!_imprintedFaces.empty())
883 run_Hexotic += comImptintedFaces + imprintedFaces;
886 run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
887 run_Hexotic += subdom + mode;
889 run_Hexotic += proc + nbproc;
891 run_Hexotic += verb + verbosity;
892 run_Hexotic += maxmem + maxMemory;
894 if (!_textOptions.empty())
895 run_Hexotic += textOptions;
897 return run_Hexotic.ToCString();
900 // TODO : this is a duplication of some code found in BLSURFPlugin_BLSURF find a proper
902 TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
904 GEOM::GEOM_Object_var aGeomObj;
905 TopoDS_Shape S = TopoDS_Shape();
906 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::getStudyServant()->FindObjectID( entry.c_str() );
907 if (!aSObj->_is_nil()) {
908 CORBA::Object_var obj = aSObj->GetObject();
909 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
912 if ( !aGeomObj->_is_nil() )
913 S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
917 //================================================================================
919 * \brief Produces a .mesh file with the size maps informations to give to Hexotic
921 //================================================================================
923 std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( MG_Hexotic_API* mgInput,
924 std::string sizeMapPrefix )
926 HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it;
928 std::vector<ControlPnt> points;
929 // Iterate on the size maps
930 for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
932 // Step 1 : Get the GEOM object entry and the size
933 // from the _sizeMaps infos
934 std::string anEntry = it->first;
935 double aLocalSize = it->second;
936 TopoDS_Shape aShape = entryToShape( anEntry );
938 // Step 2 : Create the points
939 createControlPoints( aShape, aLocalSize, points );
942 // Write the .mesh size map file
944 std::string myVerticesFile = sizeMapPrefix + ".mesh";
945 std::string mySolFile = sizeMapPrefix + ".sol";
949 mgInput->GmfOpenMesh( myVerticesFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );
951 mgInput->GmfOpenMesh( mySolFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );
953 int pointsNumber = points.size();
956 mgInput->GmfSetKwd( verticesFileID, GmfVertices, pointsNumber );
957 // SolAtVertices Keyword
958 int TypTab[] = {GmfSca};
959 mgInput->GmfSetKwd(solFileID, GmfSolAtVertices, pointsNumber, 1, TypTab);
961 // Read the control points information from the vector and write it into the files
963 std::vector<ControlPnt>::const_iterator points_it;
964 for (points_it = points.begin(); points_it != points.end(); points_it++ )
966 mgInput->GmfSetLin( verticesFileID, GmfVertices, points_it->X(), points_it->Y(), points_it->Z(), 0 );
967 ValTab[0] = points_it->Size();
968 mgInput->GmfSetLin( solFileID, GmfSolAtVertices, ValTab);
972 mgInput->GmfCloseMesh( verticesFileID );
973 mgInput->GmfCloseMesh( solFileID );
975 std::vector<std::string> fileNames(2);
976 fileNames[0] = myVerticesFile;
977 fileNames[1] = mySolFile;
982 //=============================================================================
984 * Here we are going to use the MG-Hexa mesher
986 //=============================================================================
988 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh& aMesh,
989 const TopoDS_Shape& aShape)
991 _computeCanceled = false;
993 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
994 TCollection_AsciiString hexahedraMessage;
996 _nbShape = countShape( &aMesh, TopAbs_SOLID ); // we count the number of shapes
999 // create bounding box for each shape of the compound
1002 TopoDS_Shape *tabShape;
1005 tabShape = new TopoDS_Shape[_nbShape];
1006 tabBox = new double*[_nbShape];
1007 for (int i=0; i<_nbShape; i++)
1008 tabBox[i] = new double[6];
1009 double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1011 TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1012 for (; expBox.More(); expBox.Next()) {
1013 tabShape[iShape] = expBox.Current();
1014 Bnd_Box BoundingBox;
1015 BRepBndLib::Add(expBox.Current(), BoundingBox);
1016 BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1017 tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1018 tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1019 tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1023 SetParameters(_hypothesis);
1025 TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();
1026 TCollection_AsciiString aQuote("");
1029 if ( aTmpDir.Value(aTmpDir.Length()) != '\\' ) aTmpDir += '\\';
1031 if ( aTmpDir.Value(aTmpDir.Length()) != '/' ) aTmpDir += '/';
1033 TCollection_AsciiString Hexotic_In(""), Hexotic_Out, Hexotic_SizeMap_Prefix;
1034 TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1035 TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log"; // log
1037 std::map <int,int> aSmdsToHexoticIdMap;
1038 std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1040 MG_Hexotic_API mgHexa( _computeCanceled, _progress );
1042 Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1043 #ifdef WITH_BLSURFPLUGIN
1044 bool defaultInputFile = true;
1045 if (_blsurfHypo && _blsurfHypo->GetElementType() == BLSURFPlugin_Hypothesis::Triangles ) {
1046 Hexotic_In = _blsurfHypo->GetGMFFile().c_str();
1047 if ( !Hexotic_In.IsEmpty() &&
1048 SMESH_File( _blsurfHypo->GetGMFFile() ).exists() )
1050 MESSAGE("Use output file from blsurf as input file from hexotic: " << Hexotic_In);
1051 mgHexa.SetUseExecutable();
1052 defaultInputFile = false;
1055 if (defaultInputFile) {
1057 Hexotic_In = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1058 removeHexoticFiles(Hexotic_In, Hexotic_Out);
1059 splitQuads(aMesh); // quadrangles are no longer acceptable as input
1060 if ( mgHexa.IsExecutable() )
1062 std::cout << std::endl;
1063 std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1065 writeInput( &mgHexa, Hexotic_In.ToCString(), meshDS );
1066 #ifdef WITH_BLSURFPLUGIN
1069 removeFile( Hexotic_Out );
1073 Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
1074 std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
1076 std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable() );
1077 run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString(); // dump into file
1078 mgHexa.SetLogFile( aLogFileName.ToCString() );
1079 std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1081 std::cout << std::endl;
1082 std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1084 if ( mgHexa.IsExecutable() )
1087 modeFile_In += Hexotic_In;
1088 system( modeFile_In.ToCString() );
1091 aSmdsToHexoticIdMap.clear();
1092 aHexoticIdToNodeMap.clear();
1094 MESSAGE("HexoticPlugin_Hexotic::Compute");
1098 Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
1105 if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
1108 modeFile_Out += Hexotic_Out;
1109 system( modeFile_Out.ToCString() );
1112 SMESH_MesherHelper aHelper( aMesh );
1114 Ok = readResult( &mgHexa, Hexotic_Out.ToCString(),
1116 &aHelper, _nbShape, tabShape, tabBox );
1118 std::string log = mgHexa.GetLog();
1119 hexahedraMessage = "failed";
1122 hexahedraMessage = "success";
1123 if ( _removeLogOnSuccess )
1124 removeFile( aLogFileName );
1126 else if ( !log.empty() )
1128 if( _computeCanceled )
1129 error( "interruption initiated by user" );
1132 // get problem description from the log file
1133 char msgLic[] = " Dlim ";
1134 const char* fileBeg = &log[0], *fileEnd = fileBeg + log.size();
1135 if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1136 error("Licence problems.");
1139 else if ( !errStr.empty() )
1141 // the log file is empty
1142 removeFile( aLogFileName );
1143 INFOS( "MG-Hexa Error, " << errStr);
1144 error(COMPERR_ALGO_FAILED, errStr);
1147 if ( !Ok && mgHexa.IsExecutable() )
1148 std::cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
1152 if (! Ok && _computeCanceled )
1153 removeFile( aLogFileName );
1154 removeFile(Hexotic_Out);
1155 removeFile(Hexotic_In);
1156 for ( size_t i = 0; i < sizeMapFiles.size(); i++ )
1157 removeFile( sizeMapFiles[i].c_str() );
1159 std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1160 std::cout << std::endl;
1163 for (int i=0; i<_nbShape; i++)
1164 delete [] tabBox[i];
1173 //=============================================================================
1175 * \brief Computes mesh without geometry
1176 * \param aMesh - the mesh
1177 * \param aHelper - helper that must be used for adding elements to \aaMesh
1178 * \retval bool - is a success
1180 * The method is called if ( !aMesh->HasShapeToMesh() )
1182 //=============================================================================
1184 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
1186 _computeCanceled = false;
1189 TCollection_AsciiString hexahedraMessage;
1190 TCollection_AsciiString aQuote("");
1194 SetParameters(_hypothesis);
1196 TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();//getTmpDir();
1197 TCollection_AsciiString Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix;
1198 TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1199 TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log"; // log
1201 std::map <int,int> aSmdsToHexoticIdMap;
1202 std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1204 Hexotic_In = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1205 Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1206 Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
1208 MG_Hexotic_API mgHexa( _computeCanceled, _progress );
1210 std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
1212 std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable());
1213 run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString(); // dump into file
1214 mgHexa.SetLogFile( aLogFileName.ToCString() );
1215 std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1217 removeHexoticFiles(Hexotic_In, Hexotic_Out);
1219 splitQuads(aMesh); // quadrangles are no longer acceptable as input
1221 std::cout << std::endl;
1222 std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1223 writeInput( &mgHexa, Hexotic_In.ToCString(), aHelper->GetMeshDS() );
1224 if ( mgHexa.IsExecutable() )
1227 modeFile_In += Hexotic_In;
1228 system( modeFile_In.ToCString() );
1231 aSmdsToHexoticIdMap.clear();
1232 aHexoticIdToNodeMap.clear();
1234 MESSAGE("HexoticPlugin_Hexotic::Compute");
1236 std::cout << std::endl;
1237 std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1240 Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
1246 if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
1248 modeFile_Out += Hexotic_Out;
1249 system( modeFile_Out.ToCString() );
1252 Ok = Ok && readResult( &mgHexa, Hexotic_Out.ToCString(), this, aHelper );
1254 std::string log = mgHexa.GetLog();
1257 hexahedraMessage = "success";
1261 hexahedraMessage = "failed";
1262 if ( mgHexa.IsExecutable() )
1263 std::cout << "Problem with MG-Hexa output file " << Hexotic_Out << std::endl;
1265 if ( log.find( " license " ) != std::string::npos ||
1266 log.find( " Dlim " ) != std::string::npos )
1267 error("License problems.");
1269 if ( !errStr.empty() )
1272 std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1273 std::cout << std::endl;
1275 if(_computeCanceled)
1276 return error(SMESH_Comment("interruption initiated by user"));
1277 removeFile(Hexotic_Out);
1278 removeFile(Hexotic_In);
1280 removeFile(aLogFileName);
1281 for( size_t i=0; i<sizeMapFiles.size(); i++)
1283 removeFile( TCollection_AsciiString(sizeMapFiles[i].c_str()) );
1288 //=============================================================================
1292 //=============================================================================
1294 bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh& aMesh,
1295 const TopoDS_Shape& aShape,
1296 MapShapeNbElems& aResMap)
1298 std::vector<int> aResVec(SMDSEntity_Last);
1299 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1300 SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
1301 aResMap.insert(std::make_pair(sm,aResVec));
1303 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1304 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Evaluation is not implemented",this));
1309 void HexoticPlugin_Hexotic::CancelCompute()
1311 _computeCanceled = true;
1314 TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str(); //getTmpDir();
1315 TCollection_AsciiString Hexotic_In = aTmpDir + "Hexotic_In.mesh";
1316 TCollection_AsciiString cmd = TCollection_AsciiString("ps ux | grep ") + Hexotic_In;
1317 cmd += TCollection_AsciiString(" | grep -v grep | awk '{print $2}' | xargs kill -9 > /dev/null 2>&1");
1318 system( cmd.ToCString() );