1 // Copyright (C) 2007-2013 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.
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"
28 #include "utilities.h"
31 #include <sys/sysinfo.h>
43 #include <SMESHDS_Mesh.hxx>
44 #include <SMESHDS_GroupBase.hxx>
45 #include <SMESH_ComputeError.hxx>
46 #include <SMESH_File.hxx>
47 #include <SMESH_Gen.hxx>
48 #include <SMESH_HypoFilter.hxx>
49 #include <SMESH_MesherHelper.hxx>
50 #include <SMESH_subMesh.hxx>
56 #include <Standard_ProgramError.hxx>
58 #include <BRep_Tool.hxx>
59 #include <BRepBndLib.hxx>
60 #include <BRepClass3d_SolidClassifier.hxx>
61 #include <BRepBuilderAPI_MakeVertex.hxx>
62 #include <BRepExtrema_DistShapeShape.hxx>
63 #include <OSD_File.hxx>
64 #include <Precision.hxx>
65 #include <TopExp_Explorer.hxx>
66 #include <TopTools_MapOfShape.hxx>
70 #include <GCPnts_UniformAbscissa.hxx>
71 #include <IntCurvesFace_Intersector.hxx>
72 #include <BRepMesh_IncrementalMesh.hxx>
73 #include <Poly_Triangulation.hxx>
75 #include <GeomAdaptor_Curve.hxx>
77 #include <Basics_Utils.hxx>
78 #include "GEOMImpl_Types.hxx"
79 #include "GEOM_wrap.hxx"
81 static void removeFile( const TCollection_AsciiString& fileName )
84 OSD_File( fileName ).Remove();
86 catch ( Standard_ProgramError ) {
87 MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
91 //=============================================================================
95 //=============================================================================
97 HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, int studyId, SMESH_Gen* gen)
98 : SMESH_3D_Algo(hypId, studyId, gen)
100 MESSAGE("HexoticPlugin_Hexotic::HexoticPlugin_Hexotic");
101 _name = "Hexotic_3D";
102 _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
103 // _onlyUnaryInput = false;
104 _requireShape = false;
107 _hexoticFilesKept=false;
108 _compatibleHypothesis.push_back("Hexotic_Parameters");
109 #ifdef WITH_BLSURFPLUGIN
112 _compute_canceled = false;
114 // Copy of what is done in BLSURFPLugin TODO : share the code
115 smeshGen_i = SMESH_Gen_i::GetSMESHGen();
116 CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
117 SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
120 myStudy = aStudyMgr->GetStudyByID(_studyId);
122 MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
125 //=============================================================================
129 //=============================================================================
131 HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
133 MESSAGE("HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic");
137 #ifdef WITH_BLSURFPLUGIN
138 bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh& aMesh,
139 const TopoDS_Shape& aShape )
141 // MESSAGE("HexoticPlugin_Hexotic::CheckBLSURFHypothesis");
144 std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
145 const SMESHDS_Hypothesis* theHyp;
147 // If a BLSURF hypothesis is applied, get it
148 SMESH_HypoFilter blsurfFilter;
149 blsurfFilter.Init( blsurfFilter.HasName( "BLSURF_Parameters" ));
150 std::list<const SMESHDS_Hypothesis *> appliedHyps;
151 aMesh.GetHypotheses( aShape, blsurfFilter, appliedHyps, false );
153 if ( appliedHyps.size() > 0 ) {
154 itl = appliedHyps.begin();
155 theHyp = (*itl); // use only the first hypothesis
156 std::string hypName = theHyp->GetName();
157 if (hypName == "BLSURF_Parameters") {
158 _blsurfHypo = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
167 //=============================================================================
171 //=============================================================================
173 bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh& aMesh,
174 const TopoDS_Shape& aShape,
175 SMESH_Hypothesis::Hypothesis_Status& aStatus )
177 // MESSAGE("HexoticPlugin_Hexotic::CheckHypothesis");
180 std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
181 const SMESHDS_Hypothesis* theHyp;
183 const std::list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
184 int nbHyp = hyps.size();
186 aStatus = SMESH_Hypothesis::HYP_OK;
187 return true; // can work with no hypothesis
191 theHyp = (*itl); // use only the first hypothesis
193 std::string hypName = theHyp->GetName();
194 if (hypName == "Hexotic_Parameters") {
195 _hypothesis = static_cast<const HexoticPlugin_Hypothesis*> (theHyp);
197 aStatus = SMESH_Hypothesis::HYP_OK;
200 aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
202 #ifdef WITH_BLSURFPLUGIN
203 CheckBLSURFHypothesis(aMesh, aShape);
206 return aStatus == SMESH_Hypothesis::HYP_OK;
209 //=======================================================================
210 //function : findShape
212 //=======================================================================
214 static TopoDS_Shape findShape(SMDS_MeshNode** t_Node,
216 const TopoDS_Shape* t_Shape,
221 int iShape, nbNode = 8;
223 for ( int i=0; i<3; i++ ) {
225 for ( int j=0; j<nbNode; j++ ) {
226 if ( i == 0) pntCoor[i] += t_Node[j]->X();
227 if ( i == 1) pntCoor[i] += t_Node[j]->Y();
228 if ( i == 2) pntCoor[i] += t_Node[j]->Z();
230 pntCoor[i] /= nbNode;
232 gp_Pnt aPnt(pntCoor[0], pntCoor[1], pntCoor[2]);
234 if ( aShape.IsNull() ) aShape = t_Shape[0];
235 BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
236 if ( !(SC.State() == TopAbs_IN) ) {
238 for (iShape = 0; iShape < nShape && aShape.IsNull(); iShape++) {
239 if ( !( pntCoor[0] < t_Box[iShape][0] || t_Box[iShape][1] < pntCoor[0] ||
240 pntCoor[1] < t_Box[iShape][2] || t_Box[iShape][3] < pntCoor[1] ||
241 pntCoor[2] < t_Box[iShape][4] || t_Box[iShape][5] < pntCoor[2]) ) {
242 BRepClass3d_SolidClassifier SC (t_Shape[iShape], aPnt, Precision::Confusion());
243 if (SC.State() == TopAbs_IN)
244 aShape = t_Shape[iShape];
251 //=======================================================================
252 //function : findEdge
254 //=======================================================================
256 static int findEdge(const SMDS_MeshNode* aNode,
257 const SMESHDS_Mesh* aMesh,
259 const TopoDS_Shape* t_Edge) {
261 TopoDS_Shape aPntShape, foundEdge;
262 TopoDS_Vertex aVertex;
263 gp_Pnt aPnt( aNode->X(), aNode->Y(), aNode->Z() );
266 double nearest = RealLast(), *t_Dist;
267 double epsilon = Precision::Confusion();
269 t_Dist = new double[ nEdge ];
270 aPntShape = BRepBuilderAPI_MakeVertex( aPnt ).Shape();
271 aVertex = TopoDS::Vertex( aPntShape );
273 for ( ind=0; ind < nEdge; ind++ ) {
274 BRepExtrema_DistShapeShape aDistance ( aVertex, t_Edge[ind] );
275 t_Dist[ind] = aDistance.Value();
276 if ( t_Dist[ind] < nearest ) {
277 nearest = t_Dist[ind];
278 foundEdge = t_Edge[ind];
280 if ( nearest < epsilon )
286 return aMesh->ShapeToIndex( foundEdge );
289 //=======================================================================
290 //function : getNbShape
292 //=======================================================================
294 static int getNbShape(std::string aFile, std::string aString, int defaultValue=0) {
295 int number = defaultValue;
297 std::ifstream file(aFile.c_str());
298 while ( !file.eof() ) {
299 getline( file, aLine);
300 if ( aLine == aString ) {
301 getline( file, aLine);
302 std::istringstream stringFlux( aLine );
303 stringFlux >> number;
304 number = ( number + defaultValue + std::abs(number - defaultValue) ) / 2;
312 //=======================================================================
313 //function : countShape
315 //=======================================================================
317 template < class Mesh, class Shape >
318 static int countShape( Mesh* mesh, Shape shape ) {
319 TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
320 TopTools_MapOfShape mapShape;
322 for ( ; expShape.More(); expShape.Next() ) {
323 if (mapShape.Add(expShape.Current())) {
330 //=======================================================================
331 //function : getShape
333 //=======================================================================
335 template < class Mesh, class Shape, class Tab >
336 void getShape(Mesh* mesh, Shape shape, Tab *t_Shape) {
337 TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
338 TopTools_MapOfShape mapShape;
339 for ( int i=0; expShape.More(); expShape.Next() ) {
340 if (mapShape.Add(expShape.Current())) {
341 t_Shape[i] = expShape.Current();
348 //=======================================================================
349 //function : printWarning
351 //=======================================================================
353 static void printWarning(const int nbExpected, std::string aString, const int nbFound) {
355 cout << "WARNING : " << nbExpected << " " << aString << " expected, Hexotic has found " << nbFound << std::endl;
356 cout << "=======" << std::endl;
361 //=======================================================================
362 //function : removeHexoticFiles
364 //=======================================================================
366 static void removeHexoticFiles(TCollection_AsciiString file_In, TCollection_AsciiString file_Out) {
367 removeFile( file_In );
368 removeFile( file_Out );
371 //=======================================================================
372 //function : readResult
373 //purpose : Read GMF file in case of a mesh with geometry
374 //=======================================================================
376 static bool readResult(std::string theFile,
377 #ifdef WITH_SMESH_CANCEL_COMPUTE
378 HexoticPlugin_Hexotic* theAlgo,
380 SMESHDS_Mesh* theMesh,
382 const TopoDS_Shape* tabShape,
385 // ---------------------------------
386 // Optimisation of the plugin ...
387 // Retrieve the correspondance edge --> shape
388 // (which is very costly) only when user
389 // has defined at least one group of edges
390 // which should be rare for a 3d mesh !
391 // ---------------------------------
393 bool retrieve_edges = false;
394 const std::set<SMESHDS_GroupBase*>& aGroups = theMesh->GetGroups();
395 set<SMESHDS_GroupBase*>::const_iterator GrIt = aGroups.begin();
396 for (; GrIt != aGroups.end(); GrIt++)
398 SMESHDS_GroupBase* aGrp = *GrIt;
401 if ( aGrp->GetType() == SMDSAbs_Edge )
403 retrieve_edges = true;
408 // ---------------------------------
409 // Read generated elements and nodes
410 // ---------------------------------
413 TopoDS_Vertex aVertex;
415 int EndOfFile = 0, nbElem = 0, nField = 9, nbRef = 0;
416 int aHexoticNodeID = 0, shapeID, hexoticShapeID;
417 const int IdShapeRef = 2;
418 int *tabID, *tabRef, *nodeAssigne;
419 bool *tabDummy, hasDummy = false;
420 double epsilon = Precision::Confusion();
421 std::map <std::string,int> mapField;
422 SMDS_MeshNode** HexoticNode;
423 TopoDS_Shape *tabCorner, *tabEdge;
425 const int nbDomains = countShape( theMesh, TopAbs_SHELL );
426 const int holeID = -1;
428 // tabID = new int[nbShape];
429 tabID = new int[nbDomains];
430 tabRef = new int[nField];
431 tabDummy = new bool[nField];
433 for (int i=0; i<nbDomains; i++)
435 if ( nbDomains == 1 )
436 tabID[0] = theMesh->ShapeToIndex( tabShape[0] );
438 mapField["MeshVersionFormatted"] = 0; tabRef[0] = 0; tabDummy[0] = false;
439 mapField["Dimension"] = 1; tabRef[1] = 0; tabDummy[1] = false;
440 mapField["Vertices"] = 2; tabRef[2] = 3; tabDummy[2] = true;
441 mapField["Corners"] = 3; tabRef[3] = 1; tabDummy[3] = false;
442 mapField["Edges"] = 4; tabRef[4] = 2; tabDummy[4] = true;
443 mapField["Ridges"] = 5; tabRef[5] = 1; tabDummy[5] = false;
444 mapField["Quadrilaterals"] = 6; tabRef[6] = 4; tabDummy[6] = true;
445 mapField["Hexahedra"] = 7; tabRef[7] = 8; tabDummy[7] = true;
446 mapField["End"] = 8; tabRef[8] = 0; tabDummy[0] = false;
448 SMDS_NodeIteratorPtr itOnHexoticInputNode = theMesh->nodesIterator();
449 while ( itOnHexoticInputNode->more() )
450 theMesh->RemoveNode( itOnHexoticInputNode->next() );
452 int nbVertices = getNbShape(theFile, "Vertices");
453 int nbCorners = getNbShape(theFile, "Corners", countShape( theMesh, TopAbs_VERTEX ));
454 int nbShapeEdge = countShape( theMesh, TopAbs_EDGE );
456 tabCorner = new TopoDS_Shape[ nbCorners ];
457 tabEdge = new TopoDS_Shape[ nbShapeEdge ];
458 nodeAssigne = new int[ nbVertices + 1 ];
459 HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
461 getShape(theMesh, TopAbs_VERTEX, tabCorner);
462 getShape(theMesh, TopAbs_EDGE, tabEdge);
464 MESSAGE("Read " << theFile << " file");
465 std::ifstream fileRes(theFile.c_str());
468 while ( EndOfFile == 0 ) {
472 if (mapField.count(token)) {
473 nField = mapField[token];
474 nbRef = tabRef[nField];
475 hasDummy = tabDummy[nField];
483 if ( nField < (mapField.size() - 1) && nField >= 0 )
487 case 0: { // "MeshVersionFormatted"
488 MESSAGE(token << " " << nbElem);
491 case 1: { // "Dimension"
492 MESSAGE("Mesh dimension " << nbElem << "D");
495 case 2: { // "Vertices"
496 MESSAGE("Read " << nbElem << " " << token);
499 SMDS_MeshNode * aHexoticNode;
501 coord = new double[nbRef];
502 for ( int iElem = 0; iElem < nbElem; iElem++ ) {
503 #ifdef WITH_SMESH_CANCEL_COMPUTE
504 if(theAlgo->computeCanceled())
509 aHexoticID = iElem + 1;
510 for ( int iCoord = 0; iCoord < 3; iCoord++ )
511 fileRes >> coord[ iCoord ];
513 aHexoticNode = theMesh->AddNode(coord[0], coord[1], coord[2]);
514 HexoticNode[ aHexoticID ] = aHexoticNode;
515 nodeAssigne[ aHexoticID ] = 0;
523 case 6: // "Quadrilaterals"
524 case 7: { // "Hexahedra"
525 MESSAGE("Read " << nbElem << " " << token);
526 SMDS_MeshNode** node;
527 int nodeDim, *nodeID;
528 SMDS_MeshElement * aHexoticElement = 0;
530 node = new SMDS_MeshNode*[ nbRef ];
531 nodeID = new int[ nbRef ];
532 for ( int iElem = 0; iElem < nbElem; iElem++ ) {
533 #ifdef WITH_SMESH_CANCEL_COMPUTE
534 if(theAlgo->computeCanceled())
539 for ( int iRef = 0; iRef < nbRef; iRef++ ) {
540 fileRes >> aHexoticNodeID; // read nbRef aHexoticNodeID
541 node[ iRef ] = HexoticNode[ aHexoticNodeID ];
542 nodeID[ iRef ] = aHexoticNodeID;
547 case 3: { // "Corners"
549 gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
550 for ( int i=0; i<nbElem; i++ ) {
551 aVertex = TopoDS::Vertex( tabCorner[i] );
552 gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
553 if ( aPnt.Distance( HexoticPnt ) < epsilon )
560 aHexoticElement = theMesh->AddEdge( node[0], node[1] );
562 if ( nodeAssigne[ nodeID[0] ] == 0 || nodeAssigne[ nodeID[0] ] == 2 )
565 shapeID = findEdge( node[iNode], theMesh, nbShapeEdge, tabEdge );
570 case 5: { // "Ridges"
573 case 6: { // "Quadrilaterals"
575 aHexoticElement = theMesh->AddFace( node[0], node[1], node[2], node[3] );
579 case 7: { // "Hexahedra"
581 if ( nbDomains > 1 ) {
582 hexoticShapeID = dummy - IdShapeRef;
583 if ( tabID[ hexoticShapeID ] == 0 ) {
584 aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
585 shapeID = aShape.IsNull() ? holeID : theMesh->ShapeToIndex( aShape );
586 tabID[ hexoticShapeID ] = shapeID;
589 shapeID = tabID[ hexoticShapeID ];
590 if ( iElem == (nbElem - 1) ) {
591 int shapeAssociated = 0;
592 for ( int i=0; i<nbDomains; i++ ) {
594 shapeAssociated += 1;
596 if ( shapeAssociated != nbShape )
597 printWarning(nbShape, "domains", shapeAssociated);
603 if ( shapeID != holeID )
604 aHexoticElement = theMesh->AddVolume( node[0], node[3], node[2], node[1], node[4], node[7], node[6], node[5] );
609 if ( token != "Ridges" && ( shapeID > 0 || token == "Corners")) {
610 for ( int i=0; i<nbRef; i++ ) {
611 if ( nodeAssigne[ nodeID[i] ] == 0 ) {
612 if ( token == "Corners" ) theMesh->SetNodeOnVertex( node[0], aVertex );
613 else if ( token == "Edges" ) theMesh->SetNodeOnEdge( node[i], shapeID );
614 else if ( token == "Quadrilaterals" ) theMesh->SetNodeOnFace( node[i], shapeID );
615 else if ( token == "Hexahedra" ) theMesh->SetNodeInVolume( node[i], shapeID );
616 nodeAssigne[ nodeID[i] ] = nodeDim;
619 if ( token != "Corners" && aHexoticElement )
620 theMesh->SetMeshElementOnShape( aHexoticElement, shapeID );
629 MESSAGE("End of " << theFile << " file");
633 MESSAGE("Unknown Token: " << token);
639 // remove nodes in holes
642 SMESHDS_SubMesh* subMesh;
643 for ( int i = 1; i <= nbVertices; ++i )
644 if ( HexoticNode[i]->NbInverseElements() == 0 )
646 subMesh = HexoticNode[i]->getshapeId() > 0 ? theMesh->MeshElements(HexoticNode[i]->getshapeId() ) : 0;
647 theMesh->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
655 delete [] nodeAssigne;
656 delete [] HexoticNode;
661 //=======================================================================
662 //function : readResult
663 //purpose : Read GMF file in case of a mesh w/o geometry
664 //=======================================================================
666 static bool readResult(std::string theFile,
667 #ifdef WITH_SMESH_CANCEL_COMPUTE
668 HexoticPlugin_Hexotic* theAlgo,
670 SMESH_MesherHelper* theHelper)
672 SMESHDS_Mesh* theMesh = theHelper->GetMeshDS();
674 // ---------------------------------
675 // Read generated elements and nodes
676 // ---------------------------------
679 const int nbField = 9;
680 int nField, EndOfFile = 0, nbElem = 0, nbRef = 0;
681 int aHexoticNodeID = 0, shapeID;
682 int tabRef[nbField], *nodeAssigne;
683 bool tabDummy[nbField], hasDummy = false;
684 std::map <std::string,int> mapField;
685 SMDS_MeshNode** HexoticNode;
687 mapField["MeshVersionFormatted"] = 0; tabRef[0] = 0; tabDummy[0] = false;
688 mapField["Dimension"] = 1; tabRef[1] = 0; tabDummy[1] = false;
689 mapField["Vertices"] = 2; tabRef[2] = 3; tabDummy[2] = true;
690 mapField["Corners"] = 3; tabRef[3] = 1; tabDummy[3] = false;
691 mapField["Edges"] = 4; tabRef[4] = 2; tabDummy[4] = true;
692 mapField["Ridges"] = 5; tabRef[5] = 1; tabDummy[5] = false;
693 mapField["Quadrilaterals"] = 6; tabRef[6] = 4; tabDummy[6] = true;
694 mapField["Hexahedra"] = 7; tabRef[7] = 8; tabDummy[7] = true;
695 mapField["End"] = 8; tabRef[8] = 0; tabDummy[8] = false;
697 theHelper->GetMesh()->Clear();
699 int nbVertices = getNbShape(theFile, "Vertices");
700 HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
701 nodeAssigne = new int[ nbVertices + 1 ];
703 MESSAGE("Read " << theFile << " file");
704 std::ifstream fileRes(theFile.c_str());
712 if (mapField.count(token)) {
713 nField = mapField[token];
714 nbRef = tabRef[nField];
715 hasDummy = tabDummy[nField];
723 if ( nField < (mapField.size() - 1) && nField >= 0 )
727 case 0: { // "MeshVersionFormatted"
728 MESSAGE(token << " " << nbElem);
731 case 1: { // "Dimension"
732 MESSAGE("Mesh dimension " << nbElem << "D");
735 case 2: { // "Vertices"
736 MESSAGE("Read " << nbElem << " " << token);
739 SMDS_MeshNode * aHexoticNode;
741 for ( int iElem = 0; iElem < nbElem; iElem++ ) {
742 #ifdef WITH_SMESH_CANCEL_COMPUTE
743 if(theAlgo->computeCanceled())
748 aHexoticID = iElem + 1;
749 for ( int iCoord = 0; iCoord < 3; iCoord++ )
750 fileRes >> coord[ iCoord ];
752 aHexoticNode = theMesh->AddNode(coord[0], coord[1], coord[2]);
753 HexoticNode[ aHexoticID ] = aHexoticNode;
754 nodeAssigne[ aHexoticID ] = 0;
761 case 6: // "Quadrilaterals"
762 case 7: { // "Hexahedra"
763 MESSAGE("Read " << nbElem << " " << token);
764 std::vector< SMDS_MeshNode* > node( nbRef );
765 std::vector< int > nodeID( nbRef );
767 for ( int iElem = 0; iElem < nbElem; iElem++ )
769 #ifdef WITH_SMESH_CANCEL_COMPUTE
770 if(theAlgo->computeCanceled())
775 for ( int iRef = 0; iRef < nbRef; iRef++ )
777 fileRes >> aHexoticNodeID; // read nbRef aHexoticNodeID
778 node [ iRef ] = HexoticNode[ aHexoticNodeID ];
779 nodeID[ iRef ] = aHexoticNodeID;
786 theHelper->AddEdge( node[0], node[1] ); break;
787 case 6: // "Quadrilaterals"
788 theMesh->AddFace( node[0], node[1], node[2], node[3] ); break;
789 case 7: // "Hexahedra"
790 theHelper->AddVolume( node[0], node[3], node[2], node[1],
791 node[4], node[7], node[6], node[5] ); break;
795 for ( int iRef = 0; iRef < nbRef; iRef++ )
796 nodeAssigne[ nodeID[ iRef ]] = 1;
802 MESSAGE("End of " << theFile << " file");
806 MESSAGE("Unknown Token: " << token);
812 shapeID = theHelper->GetSubShapeID();
813 for ( int i = 0; i < nbVertices; ++i )
814 if ( !nodeAssigne[ i+1 ])
815 theMesh->SetNodeInVolume( HexoticNode[ i+1 ], shapeID );
817 delete [] HexoticNode;
818 delete [] nodeAssigne;
822 //=============================================================================
824 * Pass parameters to Hexotic
826 //=============================================================================
828 void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp) {
830 MESSAGE("HexoticPlugin_Hexotic::SetParameters");
832 _hexesMinLevel = hyp->GetHexesMinLevel();
833 _hexesMaxLevel = hyp->GetHexesMaxLevel();
834 _hexesMinSize = hyp->GetMinSize();
835 _hexesMaxSize = hyp->GetMaxSize();
836 _hexoticIgnoreRidges = hyp->GetHexoticIgnoreRidges();
837 _hexoticInvalidElements = hyp->GetHexoticInvalidElements();
838 _hexoticSharpAngleThreshold = hyp->GetHexoticSharpAngleThreshold();
839 _hexoticNbProc = hyp->GetHexoticNbProc();
840 _hexoticWorkingDirectory = hyp->GetHexoticWorkingDirectory();
841 _hexoticVerbosity = hyp->GetHexoticVerbosity();
842 _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
843 _hexoticSdMode = hyp->GetHexoticSdMode();
844 _sizeMaps = hyp->GetSizeMaps();
848 cout << "WARNING : The Hexotic default parameters are taken into account" << std::endl;
849 cout << "=======" << std::endl;
850 _hexesMinLevel = hyp->GetDefaultHexesMinLevel();
851 _hexesMaxLevel = hyp->GetDefaultHexesMaxLevel();
852 _hexesMinSize = hyp->GetDefaultMinSize();
853 _hexesMaxSize = hyp->GetDefaultMaxSize();
854 _hexoticIgnoreRidges = hyp->GetDefaultHexoticIgnoreRidges();
855 _hexoticInvalidElements = hyp->GetDefaultHexoticInvalidElements();
856 _hexoticSharpAngleThreshold = hyp->GetDefaultHexoticSharpAngleThreshold();
857 _hexoticNbProc = hyp->GetDefaultHexoticNbProc();
858 _hexoticWorkingDirectory = hyp->GetDefaultHexoticWorkingDirectory();
859 _hexoticVerbosity = hyp->GetDefaultHexoticVerbosity();
860 _hexoticMaxMemory = hyp->GetDefaultHexoticMaxMemory();
861 _hexoticSdMode = hyp->GetDefaultHexoticSdMode();
862 _sizeMaps = hyp->GetDefaultHexoticSizeMaps();
866 //=======================================================================
867 //function : getTmpDir
869 //=======================================================================
871 static TCollection_AsciiString getTmpDir()
873 TCollection_AsciiString aTmpDir;
875 char *Tmp_dir = getenv("SALOME_TMP_DIR");
877 if(Tmp_dir == NULL) {
878 Tmp_dir = getenv("TEMP");
880 Tmp_dir = getenv("TMP");
883 if(Tmp_dir != NULL) {
886 if(aTmpDir.Value(aTmpDir.Length()) != '\\') aTmpDir+='\\';
888 if(aTmpDir.Value(aTmpDir.Length()) != '/') aTmpDir+='/';
893 aTmpDir = TCollection_AsciiString("C:\\");
895 aTmpDir = TCollection_AsciiString("/tmp/");
901 //=======================================================================
902 //function : getSuffix
903 //purpose : Returns a suffix that will be unique for the current process
904 //=======================================================================
906 static TCollection_AsciiString getSuffix()
908 TCollection_AsciiString aSuffix = "";
910 aSuffix += getenv("USER");
912 aSuffix += Kernel_Utils::GetHostname().c_str();
919 //================================================================================
921 * \brief Returns a command to run Hexotic mesher
923 //================================================================================
925 std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
926 const TCollection_AsciiString& Hexotic_Out,
927 const TCollection_AsciiString& Hexotic_SizeMap_Prefix) const
930 cout << "Hexotic execution..." << std::endl;
931 cout << _name << " parameters :" << std::endl;
932 cout << " " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
933 cout << " " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
934 cout << " " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
935 cout << " " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
936 cout << " " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
937 cout << " " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
938 cout << " " << "Hexotic can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
939 cout << " " << "Hexotic authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
940 cout << " " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
941 cout << " " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
942 cout << " " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
943 cout << " " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
945 TCollection_AsciiString run_Hexotic( "mg-hexa.exe" );
947 TCollection_AsciiString minl = " --min_level ", maxl = " --max_level ", angle = " --ridge_angle ";
948 TCollection_AsciiString mins = " --min_size ", maxs = " --max_size ";
949 TCollection_AsciiString in = " --in ", out = " --out ";
950 TCollection_AsciiString sizeMap = " --read_sizemap ";
951 TCollection_AsciiString ignoreRidges = " --compute_ridges no ", invalideElements = " --allow_invalid_elements yes ";
952 TCollection_AsciiString subdom = " --components ";
953 TCollection_AsciiString proc = " --max_number_of_threads ";
954 TCollection_AsciiString verb = " --verbose ";
955 TCollection_AsciiString maxmem = " --max_memory ";
957 TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory;
958 minLevel = _hexesMinLevel;
959 maxLevel = _hexesMaxLevel;
960 minSize = _hexesMinSize;
961 maxSize = _hexesMaxSize;
962 sharpAngle = _hexoticSharpAngleThreshold;
963 // Mode translation for mg-tetra 1.1
964 switch ( _hexoticSdMode )
967 mode = "outside_skin_only";
970 mode = "outside_components";
976 mode = "all --manifold_geometry no";
979 nbproc = _hexoticNbProc;
980 verbosity = _hexoticVerbosity;
981 maxMemory = _hexoticMaxMemory;
983 if (_hexoticIgnoreRidges)
984 run_Hexotic += ignoreRidges;
986 if (_hexoticInvalidElements)
987 run_Hexotic += invalideElements;
989 if (_hexesMinSize > 0)
990 run_Hexotic += mins + minSize;
992 if (_hexesMaxSize > 0)
993 run_Hexotic += maxs + maxSize;
995 if (_hexesMinLevel > 0)
996 run_Hexotic += minl + minLevel;
998 if (_hexesMaxLevel > 0)
999 run_Hexotic += maxl + maxLevel;
1001 if (_hexoticSharpAngleThreshold > 0)
1002 run_Hexotic += angle + sharpAngle;
1004 if (_sizeMaps.begin() != _sizeMaps.end())
1005 run_Hexotic += sizeMap + Hexotic_SizeMap_Prefix;
1007 run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
1008 run_Hexotic += subdom + mode;
1009 run_Hexotic += proc + nbproc;
1010 run_Hexotic += verb + verbosity;
1011 run_Hexotic += maxmem + maxMemory;
1013 return run_Hexotic.ToCString();
1016 // TODO : this is a duplication of some code found in BLSURFPlugin_BLSURF find a proper
1018 TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
1020 MESSAGE("HexoticPlugin_Hexotic::entryToShape "<<entry );
1021 GEOM::GEOM_Object_var aGeomObj;
1022 TopoDS_Shape S = TopoDS_Shape();
1023 SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
1024 if (!aSObj->_is_nil()) {
1025 CORBA::Object_var obj = aSObj->GetObject();
1026 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
1027 aSObj->UnRegister();
1029 if ( !aGeomObj->_is_nil() )
1030 S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
1034 //================================================================================
1036 * \brief Produces a .mesh file with the size maps informations to give to Hexotic
1038 //================================================================================
1039 std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( std::string sizeMapPrefix )
1041 HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it ;
1043 // The GMF driver will be used to write the size map file
1044 DriverGMF_Write aWriter;
1045 aWriter.SetSizeMapPrefix( sizeMapPrefix );
1047 std::vector<Control_Pnt> points;
1048 // Iterate on the size maps
1049 for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
1051 // Step 1 : Get the GEOM object entry and the size
1052 // from the _sizeMaps infos
1053 std::string anEntry = it->first;
1054 double aLocalSize = it->second;
1055 TopoDS_Shape aShape = entryToShape( anEntry );
1057 // Step 2 : Create the points
1058 createControlPoints( aShape, aLocalSize, points );
1060 // Write the .mesh size map file
1061 aWriter.PerformSizeMap(points);
1062 return aWriter.GetSizeMapFiles();
1065 //================================================================================
1067 * \brief Fills a vector of points from which a size map input file can be written
1069 //================================================================================
1070 void HexoticPlugin_Hexotic::createControlPoints( const TopoDS_Shape& aShape,
1071 const double& theSize,
1072 std::vector<Control_Pnt>& thePoints )
1074 if ( aShape.ShapeType() == TopAbs_VERTEX )
1076 gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex(aShape) );
1077 Control_Pnt aControl_Pnt( aPnt, theSize );
1078 thePoints.push_back( aControl_Pnt );
1080 if ( aShape.ShapeType() == TopAbs_EDGE )
1082 createPointsSampleFromEdge( aShape, theSize, thePoints );
1084 else if ( aShape.ShapeType() == TopAbs_WIRE )
1087 for (Ex.Init(aShape,TopAbs_EDGE); Ex.More(); Ex.Next())
1089 createPointsSampleFromEdge( Ex.Current(), theSize, thePoints );
1092 else if ( aShape.ShapeType() == TopAbs_FACE )
1094 createPointsSampleFromFace( aShape, theSize, thePoints );
1096 else if ( aShape.ShapeType() == TopAbs_SOLID )
1098 createPointsSampleFromSolid( aShape, theSize, thePoints );
1100 else if ( aShape.ShapeType() == TopAbs_COMPOUND )
1102 TopoDS_Iterator it( aShape );
1103 for(; it.More(); it.Next())
1105 createControlPoints( it.Value(), theSize, thePoints );
1110 //================================================================================
1112 * \brief Fills a vector of points with point samples approximately
1113 * \brief spaced with a given size
1115 //================================================================================
1116 void HexoticPlugin_Hexotic::createPointsSampleFromEdge( const TopoDS_Shape& aShape,
1117 const double& theSize,
1118 std::vector<Control_Pnt>& thePoints )
1120 double step = theSize;
1122 Handle( Geom_Curve ) aCurve = BRep_Tool::Curve( TopoDS::Edge( aShape ), first, last );
1123 GeomAdaptor_Curve C ( aCurve );
1124 GCPnts_UniformAbscissa DiscretisationAlgo(C, step , first, last, Precision::Confusion());
1125 int nbPoints = DiscretisationAlgo.NbPoints();
1127 for ( int i = 1; i <= nbPoints; i++ )
1129 double param = DiscretisationAlgo.Parameter( i );
1131 aCurve->D0( param, aPnt );
1132 aPnt.SetSize(theSize);
1133 thePoints.push_back( aPnt );
1137 //================================================================================
1139 * \brief Fills a vector of points with point samples approximately
1140 * \brief spaced with a given size
1142 //================================================================================
1143 void HexoticPlugin_Hexotic::createPointsSampleFromFace( const TopoDS_Shape& aShape,
1144 const double& theSize,
1145 std::vector<Control_Pnt>& thePoints )
1147 BRepMesh_IncrementalMesh M(aShape, 0.01, Standard_True);
1148 TopLoc_Location aLocation;
1149 TopoDS_Face aFace = TopoDS::Face(aShape);
1151 // Triangulate the face
1152 Handle(Poly_Triangulation) aTri = BRep_Tool::Triangulation (aFace, aLocation);
1154 // Get the transformation associated to the face location
1155 gp_Trsf aTrsf = aLocation.Transformation();
1158 int nbTriangles = aTri->NbTriangles();
1159 Poly_Array1OfTriangle triangles(1,nbTriangles);
1160 triangles=aTri->Triangles();
1163 int nbNodes = aTri->NbNodes();
1164 TColgp_Array1OfPnt nodes(1,nbNodes);
1165 nodes = aTri->Nodes();
1167 // Iterate on triangles and subdivide them
1168 for(int i=1; i<=nbTriangles; i++)
1170 Poly_Triangle aTriangle = triangles.Value(i);
1171 gp_Pnt p1 = nodes.Value(aTriangle.Value(1));
1172 gp_Pnt p2 = nodes.Value(aTriangle.Value(2));
1173 gp_Pnt p3 = nodes.Value(aTriangle.Value(3));
1175 p1.Transform(aTrsf);
1176 p2.Transform(aTrsf);
1177 p3.Transform(aTrsf);
1179 subdivideTriangle(p1, p2, p3, theSize, thePoints);
1183 //================================================================================
1185 * \brief Fills a vector of points with point samples approximately
1186 * \brief spaced with a given size
1188 //================================================================================
1189 void HexoticPlugin_Hexotic::createPointsSampleFromSolid( const TopoDS_Shape& aShape,
1190 const double& theSize,
1191 std::vector<Control_Pnt>& thePoints )
1193 // Compute the bounding box
1194 double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1196 BRepBndLib::Add(aShape, B);
1197 B.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1199 // Create the points
1200 double step = theSize;
1202 for ( double x=Xmin; x-Xmax<Precision::Confusion(); x=x+step )
1204 for ( double y=Ymin; y-Ymax<Precision::Confusion(); y=y+step )
1206 // Step1 : generate the Zmin -> Zmax line
1207 gp_Pnt startPnt(x, y, Zmin);
1208 gp_Pnt endPnt(x, y, Zmax);
1209 gp_Vec aVec(startPnt, endPnt);
1210 gp_Lin aLine(startPnt, aVec);
1211 double endParam = Zmax - Zmin;
1213 // Step2 : for each face of aShape:
1214 std::set<double> intersections;
1215 std::set<double>::iterator it = intersections.begin();
1218 for (Ex.Init(aShape,TopAbs_FACE); Ex.More(); Ex.Next())
1220 // check if there is an intersection
1221 IntCurvesFace_Intersector anIntersector(TopoDS::Face(Ex.Current()), Precision::Confusion());
1222 anIntersector.Perform(aLine, 0, endParam);
1224 // get the intersection's parameter and store it
1225 int nbPoints = anIntersector.NbPnt();
1226 for(int i = 0 ; i < nbPoints ; i++ )
1228 it = intersections.insert( it, anIntersector.WParameter(i+1) );
1231 // Step3 : go through the line chunk by chunk
1232 if ( intersections.begin() != intersections.end() )
1234 std::set<double>::iterator intersectionsIterator=intersections.begin();
1235 double first = *intersectionsIterator;
1236 intersectionsIterator++;
1237 bool innerPoints = true;
1238 for ( ; intersectionsIterator!=intersections.end() ; intersectionsIterator++ )
1240 double second = *intersectionsIterator;
1243 // If the last chunk was outside of the shape or this is the first chunk
1244 // add the points in the range [first, second] to the points vector
1245 double localStep = (second -first) / ceil( (second - first) / step );
1246 for ( double z = Zmin + first; z < Zmin + second; z = z + localStep )
1248 thePoints.push_back(Control_Pnt( x, y, z, theSize ));
1250 thePoints.push_back(Control_Pnt( x, y, Zmin + second, theSize ));
1253 innerPoints = !innerPoints;
1260 //================================================================================
1262 * \brief Subdivides a triangle until it reaches a certain size (recursive function)
1264 //================================================================================
1265 void HexoticPlugin_Hexotic::subdivideTriangle( const gp_Pnt& p1,
1268 const double& theSize,
1269 std::vector<Control_Pnt>& thePoints)
1271 // Size threshold to stop subdividing
1272 // This value ensures that two control points are distant no more than 2*theSize
1275 // The greater distance D of the mass center M to each Edge is 1/3 * Median
1276 // and Median < sqrt(3/4) * a where a is the greater side (by using Apollonius' thorem).
1277 // So D < 1/3 * sqrt(3/4) * a and if a < sqrt(3) * S then D < S/2
1278 // and the distance between two mass centers of two neighbouring triangles
1279 // sharing an edge is < 2 * 1/2 * S = S
1280 // If the traingles share a Vertex and no Edge the distance of the mass centers
1281 // to the Vertices is 2*D < S so the mass centers are distant of less than 2*S
1283 double threshold = sqrt( 3 ) * theSize;
1285 if ( (p1.Distance(p2) > threshold ||
1286 p2.Distance(p3) > threshold ||
1287 p3.Distance(p1) > threshold))
1289 std::vector<gp_Pnt> midPoints = computePointsForSplitting(p1, p2, p3);
1291 subdivideTriangle( midPoints[0], midPoints[1], midPoints[2], theSize, thePoints );
1292 subdivideTriangle( midPoints[0], p2, midPoints[1], theSize, thePoints );
1293 subdivideTriangle( midPoints[2], midPoints[1], p3, theSize, thePoints );
1294 subdivideTriangle( p1, midPoints[0], midPoints[2], theSize, thePoints );
1298 double x = (p1.X() + p2.X() + p3.X()) / 3 ;
1299 double y = (p1.Y() + p2.Y() + p3.Y()) / 3 ;
1300 double z = (p1.Z() + p2.Z() + p3.Z()) / 3 ;
1302 Control_Pnt massCenter( x ,y ,z, theSize );
1303 thePoints.push_back( massCenter );
1307 //================================================================================
1309 * \brief Returns the appropriate points for splitting a triangle
1310 * \brief the tangency points of the incircle are used in order to have mostly
1311 * \brief well-shaped sub-triangles
1313 //================================================================================
1314 std::vector<gp_Pnt> HexoticPlugin_Hexotic::computePointsForSplitting( const gp_Pnt& p1,
1318 std::vector<gp_Pnt> midPoints;
1319 //Change coordinates
1320 gp_Trsf Trsf_1; // Identity transformation
1321 gp_Ax3 reference_system(gp::Origin(), gp::DZ(), gp::DX()); // OXY
1324 gp_Vec Vaux(p1, p2);
1327 gp_Dir Dz = Dx.Crossed(Daux);
1328 gp_Ax3 current_system(p1, Dz, Dx);
1330 Trsf_1.SetTransformation( reference_system, current_system );
1332 gp_Pnt A = p1.Transformed(Trsf_1);
1333 gp_Pnt B = p2.Transformed(Trsf_1);
1334 gp_Pnt C = p3.Transformed(Trsf_1);
1336 double a = B.Distance(C) ;
1337 double b = A.Distance(C) ;
1338 double c = B.Distance(A) ;
1340 // Incenter coordinates
1341 // see http://mathworld.wolfram.com/Incenter.html
1342 double Xi = ( b*B.X() + c*C.X() ) / ( a + b + c );
1343 double Yi = ( b*B.Y() ) / ( a + b + c );
1344 gp_Pnt Center(Xi, Yi, 0);
1346 // Calculate the tangency points of the incircle
1347 gp_Pnt T1 = tangencyPoint( A, B, Center);
1348 gp_Pnt T2 = tangencyPoint( B, C, Center);
1349 gp_Pnt T3 = tangencyPoint( C, A, Center);
1351 gp_Pnt p1_2 = T1.Transformed(Trsf_1.Inverted());
1352 gp_Pnt p2_3 = T2.Transformed(Trsf_1.Inverted());
1353 gp_Pnt p3_1 = T3.Transformed(Trsf_1.Inverted());
1355 midPoints.push_back(p1_2);
1356 midPoints.push_back(p2_3);
1357 midPoints.push_back(p3_1);
1362 //================================================================================
1364 * \brief Computes the tangency points of the circle of center Center with
1365 * \brief the straight line (p1 p2)
1367 //================================================================================
1368 gp_Pnt HexoticPlugin_Hexotic::tangencyPoint(const gp_Pnt& p1,
1370 const gp_Pnt& Center)
1375 // The tangency point is the intersection of the straight line (p1 p2)
1376 // and the straight line (Center T) which is orthogonal to (p1 p2)
1377 if ( fabs(p1.X() - p2.X()) <= Precision::Confusion() )
1379 Xt=p1.X(); // T is on (p1 p2)
1380 Yt=Center.Y(); // (Center T) is orthogonal to (p1 p2)
1382 else if ( fabs(p1.Y() - p2.Y()) <= Precision::Confusion() )
1384 Yt=p1.Y(); // T is on (p1 p2)
1385 Xt=Center.X(); // (Center T) is orthogonal to (p1 p2)
1389 // First straight line coefficients (equation y=a*x+b)
1390 double a = (p2.Y() - p1.Y()) / (p2.X() - p1.X()) ;
1391 double b = p1.Y() - a*p1.X(); // p1 is on this straight line
1393 // Second straight line coefficients (equation y=c*x+d)
1394 double c = -1 / a; // The 2 lines are orthogonal
1395 double d = Center.Y() - c*Center.X(); // Center is on this straight line
1397 Xt = (d - b) / (a - c);
1401 return gp_Pnt( Xt, Yt, 0 );
1404 //=============================================================================
1406 * Here we are going to use the Hexotic mesher
1408 //=============================================================================
1410 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh& aMesh,
1411 const TopoDS_Shape& aShape)
1413 #ifdef WITH_SMESH_CANCEL_COMPUTE
1414 _compute_canceled = false;
1417 SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1418 TCollection_AsciiString hexahedraMessage;
1420 if (_iShape == 0 && _nbShape == 0) {
1421 _nbShape = countShape( meshDS, TopAbs_SOLID ); // we count the number of shapes
1424 // to prevent from displaying error message after computing,
1425 // SetIsAlwaysComputed( true ) to empty sub-meshes
1426 vector< SMESH_subMesh* > subMeshesAlwaysComp;
1427 for ( int i = 0; i < _nbShape; ++i )
1428 if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( aShape ))
1430 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
1431 /*complexShapeFirst=*/false);
1432 while ( smIt->more() )
1435 if ( !sm->IsMeshComputed() )
1437 sm->SetIsAlwaysComputed( true );
1438 subMeshesAlwaysComp.push_back( sm );
1445 if (_iShape == _nbShape ) {
1447 // create bounding box for each shape of the compound
1450 TopoDS_Shape *tabShape;
1453 tabShape = new TopoDS_Shape[_nbShape];
1454 tabBox = new double*[_nbShape];
1455 for (int i=0; i<_nbShape; i++)
1456 tabBox[i] = new double[6];
1457 double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1459 TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1460 for (; expBox.More(); expBox.Next()) {
1461 tabShape[iShape] = expBox.Current();
1462 Bnd_Box BoundingBox;
1463 BRepBndLib::Add(expBox.Current(), BoundingBox);
1464 BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1465 tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1466 tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1467 tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1471 SetParameters(_hypothesis);
1473 // TCollection_AsciiString aTmpDir = getTmpDir();
1474 TCollection_AsciiString aTmpDir = TCollection_AsciiString(_hexoticWorkingDirectory.c_str());
1476 if ( aTmpDir.Value(aTmpDir.Length()) != '\\' ) aTmpDir += '\\';
1478 if ( aTmpDir.Value(aTmpDir.Length()) != '/' ) aTmpDir += '/';
1480 TCollection_AsciiString Hexotic_In(""), Hexotic_Out, Hexotic_SizeMap_Prefix;
1481 TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1482 TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log"; // log
1484 std::map <int,int> aSmdsToHexoticIdMap;
1485 std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1487 Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1488 #ifdef WITH_BLSURFPLUGIN
1489 bool defaultInputFile = true;
1490 if (_blsurfHypo && !_blsurfHypo->GetQuadAllowed()) {
1491 Hexotic_In = TCollection_AsciiString(_blsurfHypo->GetGMFFile().c_str());
1492 if (Hexotic_In != "")
1493 defaultInputFile = false;
1495 if (defaultInputFile) {
1497 Hexotic_In = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1498 removeHexoticFiles(Hexotic_In, Hexotic_Out);
1500 cout << "Creating Hexotic input mesh file : " << Hexotic_In << std::endl;
1501 aMesh.ExportGMF(Hexotic_In.ToCString(), meshDS, true);
1502 #ifdef WITH_BLSURFPLUGIN
1505 removeFile( Hexotic_Out );
1509 Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
1510 std::vector<std::string> sizeMapFiles = writeSizeMapFile( Hexotic_SizeMap_Prefix.ToCString() );
1512 std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix);
1513 run_Hexotic += std::string(" 1> ") + aLogFileName.ToCString(); // dump into file
1516 cout << "Hexotic command : " << run_Hexotic << std::endl;
1519 modeFile_In += Hexotic_In;
1520 system( modeFile_In.ToCString() );
1522 aSmdsToHexoticIdMap.clear();
1523 aHexoticIdToNodeMap.clear();
1525 MESSAGE("HexoticPlugin_Hexotic::Compute");
1527 int status = system( run_Hexotic.data() );
1533 std::ifstream fileRes( Hexotic_Out.ToCString() );
1534 modeFile_Out += Hexotic_Out;
1535 system( modeFile_Out.ToCString() );
1536 if ( ! fileRes.fail() ) {
1537 Ok = readResult( Hexotic_Out.ToCString(),
1538 #ifdef WITH_SMESH_CANCEL_COMPUTE
1541 meshDS, _nbShape, tabShape, tabBox );
1543 /*********************
1544 // TODO: Detect and remove elements in holes in case of sd mode = 4
1545 // Remove previous nodes and elements
1546 SMDS_ElemIteratorPtr itElement = meshDS->elementsIterator();
1547 SMDS_NodeIteratorPtr itNode = meshDS->nodesIterator();
1549 while ( itElement->more() )
1550 meshDS->RemoveElement( itElement->next() );
1551 while ( itNode->more() )
1552 meshDS->RemoveNode( itNode->next() );
1554 SMESH_ComputeErrorPtr myError = aMesh.GMFToMesh(Hexotic_Out.ToCString());
1557 hexahedraMessage = "success";
1559 removeFile(Hexotic_Out);
1560 removeFile(Hexotic_In);
1561 removeFile(aLogFileName);
1562 for( int i=0; i<sizeMapFiles.size(); i++)
1564 removeFile( TCollection_AsciiString( sizeMapFiles[i].c_str() ) );
1569 hexahedraMessage = "failed";
1573 hexahedraMessage = "failed";
1574 cout << "Problem with Hexotic output file " << Hexotic_Out.ToCString() << std::endl;
1577 SMESH_File logFile( aLogFileName.ToCString() );
1578 if ( !logFile.eof() )
1580 char msgLic[] = " Dlim ";
1581 const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
1582 if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1583 error("Licence problems.");
1586 if ( status > 0 && WEXITSTATUS(status) == 127 )
1587 error("hexotic: command not found");
1590 if ( status == 0 && err == ENOENT ) {
1591 error("hexotic: command not found");
1595 cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1598 // restore "always computed" flag of sub-meshes (0022127)
1599 for ( size_t iSM = 0; iSM < subMeshesAlwaysComp.size(); ++iSM )
1600 subMeshesAlwaysComp[ iSM ]->SetIsAlwaysComputed( false );
1603 for (int i=0; i<_nbShape; i++)
1604 delete [] tabBox[i];
1609 #ifdef WITH_SMESH_CANCEL_COMPUTE
1610 if(_compute_canceled)
1611 return error(SMESH_Comment("interruption initiated by user"));
1616 //=============================================================================
1618 * \brief Computes mesh without geometry
1619 * \param aMesh - the mesh
1620 * \param aHelper - helper that must be used for adding elements to \aaMesh
1621 * \retval bool - is a success
1623 * The method is called if ( !aMesh->HasShapeToMesh() )
1625 //=============================================================================
1627 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
1629 #ifdef WITH_SMESH_CANCEL_COMPUTE
1630 _compute_canceled = false;
1633 SMESH_ComputeErrorPtr myError = SMESH_ComputeError::New();
1636 TCollection_AsciiString hexahedraMessage;
1638 SetParameters(_hypothesis);
1640 TCollection_AsciiString aTmpDir = getTmpDir();
1641 TCollection_AsciiString Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix;
1642 TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1643 TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log"; // log
1645 std::map <int,int> aSmdsToHexoticIdMap;
1646 std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1648 Hexotic_In = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1649 Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1650 Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
1653 std::vector<std::string> sizeMapFiles = writeSizeMapFile( Hexotic_SizeMap_Prefix.ToCString() );
1655 std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix);
1656 run_Hexotic += std::string(" 1> ") + aLogFileName.ToCString(); // dump into file
1658 removeHexoticFiles(Hexotic_In, Hexotic_Out);
1661 cout << "Creating Hexotic input mesh file : " << Hexotic_In << std::endl;
1662 aMesh.ExportGMF(Hexotic_In.ToCString(), aHelper->GetMeshDS());
1664 modeFile_In += Hexotic_In;
1665 system( modeFile_In.ToCString() );
1667 aSmdsToHexoticIdMap.clear();
1668 aHexoticIdToNodeMap.clear();
1670 MESSAGE("HexoticPlugin_Hexotic::Compute");
1673 cout << "Hexotic command : " << run_Hexotic << std::endl;
1674 system( run_Hexotic.data() );
1680 std::ifstream fileRes( Hexotic_Out.ToCString() );
1681 modeFile_Out += Hexotic_Out;
1682 system( modeFile_Out.ToCString() );
1683 if ( ! fileRes.fail() ) {
1684 Ok = readResult( Hexotic_Out.ToCString(),
1685 #ifdef WITH_SMESH_CANCEL_COMPUTE
1691 // Remove previous nodes and elements
1692 SMDS_ElemIteratorPtr itElement = aHelper->GetMeshDS()->elementsIterator();
1693 SMDS_NodeIteratorPtr itNode = aHelper->GetMeshDS()->nodesIterator();
1695 while ( itElement->more() )
1696 aHelper->GetMeshDS()->RemoveElement( itElement->next() );
1697 while ( itNode->more() )
1698 aHelper->GetMeshDS()->RemoveNode( itNode->next() );
1701 myError = aMesh.GMFToMesh(Hexotic_Out.ToCString());
1703 itElement = aHelper->GetMeshDS()->elementsIterator();
1704 itNode = aHelper->GetMeshDS()->nodesIterator();
1706 // Assign nodes and elements to the pseudo shape
1707 while ( itNode->more() )
1708 aHelper->GetMeshDS()->SetNodeInVolume(itNode->next(), 1);
1709 while ( itElement->more() )
1710 aHelper->GetMeshDS()->SetMeshElementOnShape(itElement->next(), 1);
1714 hexahedraMessage = "success";
1716 hexahedraMessage = "failed";
1720 myError->myName = COMPERR_EXCEPTION;
1722 hexahedraMessage = "failed";
1723 cout << "Problem with Hexotic output file " << Hexotic_Out << std::endl;
1725 SMESH_File logFile( aLogFileName.ToCString() );
1726 if ( !logFile.eof() )
1728 char msgLic[] = " Dlim ";
1729 const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
1730 if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1731 return error("Licence problems.");
1733 return error(SMESH_Comment("Problem with Hexotic output file ")<<Hexotic_Out);
1735 cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1738 #ifdef WITH_SMESH_CANCEL_COMPUTE
1739 if(_compute_canceled)
1740 return error(SMESH_Comment("interruption initiated by user"));
1742 removeFile(Hexotic_Out);
1743 removeFile(Hexotic_In);
1744 removeFile(aLogFileName);
1745 for( int i=0; i<sizeMapFiles.size(); i++)
1747 removeFile( TCollection_AsciiString(sizeMapFiles[i].c_str()) );
1751 return myError->IsOK();
1755 //=============================================================================
1759 //=============================================================================
1761 bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh& aMesh,
1762 const TopoDS_Shape& aShape,
1763 MapShapeNbElems& aResMap)
1765 std::vector<int> aResVec(SMDSEntity_Last);
1766 for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1767 SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
1768 aResMap.insert(std::make_pair(sm,aResVec));
1770 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1771 smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Evaluation is not implemented",this));
1776 #ifdef WITH_SMESH_CANCEL_COMPUTE
1777 void HexoticPlugin_Hexotic::CancelCompute()
1779 _compute_canceled = true;
1782 TCollection_AsciiString aTmpDir = getTmpDir();
1783 TCollection_AsciiString Hexotic_In = aTmpDir + "Hexotic_In.mesh";
1784 TCollection_AsciiString cmd = TCollection_AsciiString("ps ux | grep ") + Hexotic_In;
1785 cmd += TCollection_AsciiString(" | grep -v grep | awk '{print $2}' | xargs kill -9 > /dev/null 2>&1");
1786 system( cmd.ToCString() );