Salome HOME
80dd20ffca115be03219165e426e93b5986bd795
[plugins/hexoticplugin.git] / src / HexoticPlugin / HexoticPlugin_Hexotic.cxx
1 // Copyright (C) 2007-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // ---
21 // File   : HexoticPlugin_Hexotic.cxx
22 // Author : Lioka RAZAFINDRAZAKA (CEA)
23 // ---
24 //
25 #include "HexoticPlugin_Hexotic.hxx"
26 #include "HexoticPlugin_Hypothesis.hxx"
27 #include "MG_Hexotic_API.hxx"
28
29 #include "utilities.h"
30
31 #ifdef WIN32
32 #include <process.h>
33 #endif
34
35 #ifdef _DEBUG_
36 #define DUMP(txt) \
37 //  std::cout << txt
38 #else
39 #define DUMP(txt)
40 #endif
41
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>
52
53 #include <list>
54 #include <cstdlib>
55
56 #include <Standard_ProgramError.hxx>
57
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>
66 #include <TopoDS.hxx>
67 #include <TopoDS_Vertex.hxx>
68 #include <gp_Pnt.hxx>
69
70 #include <Basics_Utils.hxx>
71 #include <GEOMImpl_Types.hxx>
72 #include <GEOM_wrap.hxx>
73
74 #define GMFVERSION GmfDouble
75 #define GMFDIMENSION 3
76
77 using SMESHUtils::ControlPnt;
78
79 static void removeFile( const TCollection_AsciiString& fileName )
80 {
81   try {
82     OSD_File( fileName ).Remove();
83   }
84   catch ( Standard_ProgramError& ) {
85     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
86   }
87 }
88
89 //=============================================================================
90 /*!
91  *  
92  */
93 //=============================================================================
94
95 HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, SMESH_Gen* gen)
96   : SMESH_3D_Algo(hypId, gen)
97 {
98   _name = "MG-Hexa";
99   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
100   _onlyUnaryInput = false;
101   _requireShape = false;
102   _iShape=0;
103   _nbShape=0;
104   _hexoticFilesKept=false;
105   _compatibleHypothesis.push_back( HexoticPlugin_Hypothesis::GetHypType() );
106 #ifdef WITH_BLSURFPLUGIN
107   _blsurfHypo = NULL;
108 #endif
109   _computeCanceled = false;
110   
111 }
112
113 //=============================================================================
114 /*!
115  *  
116  */
117 //=============================================================================
118
119 HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
120 {
121 }
122
123
124 #ifdef WITH_BLSURFPLUGIN
125 bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh&         aMesh,
126                                                    const TopoDS_Shape& aShape )
127 {
128   _blsurfHypo = NULL;
129
130   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
131   const SMESHDS_Hypothesis* theHyp;
132
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 );
139
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) )
146     {
147       _blsurfHypo = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
148       ASSERT(_blsurfHypo);
149       return true;
150     }
151   }
152   return false;
153 }
154 #endif
155
156 //=============================================================================
157 /*!
158  *  
159  */
160 //=============================================================================
161
162 bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh&                          aMesh,
163                                              const TopoDS_Shape&                  aShape,
164                                              SMESH_Hypothesis::Hypothesis_Status& aStatus )
165 {
166   _hypothesis = NULL;
167
168   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
169   const SMESHDS_Hypothesis* theHyp;
170
171   const std::list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
172   int nbHyp = hyps.size();
173   if (!nbHyp) {
174     // retrieve BLSURF hypothesis if no hexotic hypothesis has been set
175 #ifdef WITH_BLSURFPLUGIN
176     CheckBLSURFHypothesis(aMesh, aShape);
177 #endif
178     aStatus = SMESH_Hypothesis::HYP_OK;
179     return true;  // can work with no hypothesis
180   }
181
182   itl = hyps.begin();
183   theHyp = (*itl); // use only the first hypothesis
184
185   std::string hypName = theHyp->GetName();
186   if (hypName == HexoticPlugin_Hypothesis::GetHypType() ) {
187     _hypothesis = static_cast<const HexoticPlugin_Hypothesis*> (theHyp);
188     ASSERT(_hypothesis);
189     aStatus = SMESH_Hypothesis::HYP_OK;
190   }
191   else
192     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
193   
194 #ifdef WITH_BLSURFPLUGIN
195   CheckBLSURFHypothesis(aMesh, aShape);
196 #endif
197   
198   return aStatus == SMESH_Hypothesis::HYP_OK;
199 }
200
201 //=======================================================================
202 //function : findShape
203 //purpose  :
204 //=======================================================================
205
206 static TopoDS_Shape findShape(SMDS_MeshNode**     t_Node,
207                               TopoDS_Shape        aShape,
208                               const TopoDS_Shape* t_Shape,
209                               double**            t_Box,
210                               const int           nShape)
211 {
212   double pntCoor[3];
213   int iShape, nbNode = 8;
214
215   for ( int i=0; i<3; i++ ) {
216     pntCoor[i] = 0;
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();
221     }
222     pntCoor[i] /= nbNode;
223   }
224   gp_Pnt aPnt(pntCoor[0], pntCoor[1], pntCoor[2]);
225
226   if ( aShape.IsNull() ) aShape = t_Shape[0];
227   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
228   if ( !(SC.State() == TopAbs_IN) ) {
229     aShape.Nullify();
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];
237       }
238     }
239   }
240   return aShape;
241 }
242
243 //=======================================================================
244 //function : getNbShape
245 //purpose  :
246 //=======================================================================
247
248 static int getNbShape(MG_Hexotic_API* hexaOutput, int iMesh, GmfKwdCod what, int defaultValue=0)
249 {
250   int number = hexaOutput->GmfStatKwd( iMesh, what );
251   if ( number > 0 )
252   {
253     number = ( number + defaultValue + std::abs(number - defaultValue) ) / 2;
254   }
255   else
256   {
257     number = defaultValue;
258   }
259   return number;
260 }
261
262 //=======================================================================
263 //function : countShape
264 //purpose  :
265 //=======================================================================
266
267 static int countShape( SMESH_Mesh* mesh, TopAbs_ShapeEnum shape )
268 {
269   if ( !mesh->HasShapeToMesh() )
270     return 0;
271   TopExp_Explorer expShape ( mesh->GetShapeToMesh(), shape );
272   TopTools_MapOfShape mapShape;
273   int nbShape = 0;
274   for ( ; expShape.More(); expShape.Next() ) {
275     if (mapShape.Add(expShape.Current())) {
276       nbShape++;
277     }
278   }
279   return nbShape;
280 }
281
282 //=======================================================================
283 //function : getShape
284 //purpose  :
285 //=======================================================================
286
287 template < class Mesh, class Shape, class Tab >
288 void getShape(Mesh* mesh, Shape shape, Tab *t_Shape)
289 {
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();
295       i++;
296     }
297   }
298   return;
299 }
300
301 //=======================================================================
302 //function : printWarning
303 //purpose  :
304 //=======================================================================
305
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;
311   return;
312 }
313
314 //=======================================================================
315 //function : removeHexoticFiles
316 //purpose  :
317 //=======================================================================
318
319 static void removeHexoticFiles(TCollection_AsciiString file_In, TCollection_AsciiString file_Out)
320 {
321   removeFile( file_In );
322   removeFile( file_Out );
323 }
324
325 //=======================================================================
326 //function : splitQuads
327 //purpose  : splits all quadrangles into triangles
328 //=======================================================================
329
330 static void splitQuads(SMESH_Mesh& aMesh)
331 {
332   SMESH_MeshEditor spliter( &aMesh );
333
334   TIDSortedElemSet elems;
335   SMDS_ElemIteratorPtr eIt = aMesh.GetMeshDS()->elementsIterator();
336   while( eIt->more() )
337     elems.insert( elems.end(), eIt->next() );
338   
339   spliter.QuadToTri ( elems, /*the13Diag=*/true);
340 }
341
342 //=======================================================================
343 //function : writeInput
344 //purpose  : pass a mesh to input of MG-Hexa
345 //=======================================================================
346
347 static void writeInput(MG_Hexotic_API*     theHexaInput,
348                        const char*         theFile,
349                        const SMESHDS_Mesh* theMeshDS)
350 {
351   int meshID = theHexaInput->GmfOpenMesh( theFile, GmfWrite, GMFVERSION, GMFDIMENSION);
352   
353   // nodes
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();
358   SMESH_TNodeXYZ n;
359   while ( nodeIt->more() )
360   {
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 ));
364   }
365
366   // edges
367   SMDS_ElemIteratorPtr elemIt = theMeshDS->elementsIterator( SMDSAbs_Edge );
368   if ( elemIt->more() )
369   {
370     int nbEdges = theMeshDS->GetMeshInfo().NbElements( SMDSAbs_Edge );
371     theHexaInput->GmfSetKwd(meshID, GmfEdges, nbEdges );
372     for ( int gmfID = 1; elemIt->more(); ++gmfID )
373     {
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() );
379     }
380   }
381
382   // triangles
383   elemIt = theMeshDS->elementGeomIterator( SMDSGeom_TRIANGLE );
384   if ( elemIt->more() )
385   {
386     int nbTria = theMeshDS->GetMeshInfo().NbElements( SMDSGeom_TRIANGLE );
387     theHexaInput->GmfSetKwd(meshID, GmfTriangles, nbTria );
388     for ( int gmfID = 1; elemIt->more(); ++gmfID )
389     {
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() );
396     }
397   }
398   theHexaInput->GmfCloseMesh( meshID );
399 }
400
401 //=======================================================================
402 //function : readResult
403 //purpose  : Read GMF file in case of a mesh with geometry
404 //=======================================================================
405
406 static bool readResult(MG_Hexotic_API*       theHexaOutput,
407                        const char*           theFile,
408                        HexoticPlugin_Hexotic*theAlgo,
409                        SMESH_MesherHelper*   theHelper,
410                        const int             nbShape = 0,
411                        const TopoDS_Shape*   tabShape = 0,
412                        double**              tabBox = 0)
413 {
414   SMESH_Mesh*     theMesh = theHelper->GetMesh();
415   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
416
417   // ---------------------------------
418   // Read generated elements and nodes
419   // ---------------------------------
420
421   TopoDS_Shape aShape;
422   TopoDS_Vertex aVertex;
423   std::string token;
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;
431
432   const int nbDomains = countShape( theMesh, TopAbs_SHELL );
433   const int holeID = -1;
434
435   if ( nbDomains > 0 )
436   {
437     tabID.resize( nbDomains, 0 );
438     if ( nbDomains == 1 )
439       tabID[0] = theMeshDS->ShapeToIndex( tabShape[0] );
440   }
441   else
442   {
443     tabID.resize( 1, 1 );
444   }
445
446   SMDS_ElemIteratorPtr eIt = theMeshDS->elementsIterator();
447   while( eIt->more() )
448     theMeshDS->RemoveFreeElement( eIt->next(), /*sm=*/0 );
449   SMDS_NodeIteratorPtr nIt = theMeshDS->nodesIterator();
450   while ( nIt->more() )
451     theMeshDS->RemoveFreeNode( nIt->next(), /*sm=*/0 );
452
453   theHelper->SetElementsOnShape( false );
454
455   int ver, dim;
456   int meshID = theHexaOutput->GmfOpenMesh( theFile, GmfRead, &ver, &dim );
457
458   int nbVerticesInShape = countShape( theMesh, TopAbs_VERTEX );
459   int nbVertices  = getNbShape(theHexaOutput, meshID, GmfVertices );
460   int nbCorners   = getNbShape(theHexaOutput, meshID, GmfCorners, nbVerticesInShape);
461   if ( nbVertices == 0 )
462     return false;
463
464   tabCorner.resize( nbCorners );
465   HexoticNode.resize( nbVertices + 1 );
466
467   // get the shape vertices if the mesh lies on a shape (and this shape has corners)
468   if ( nbCorners > 0 && nbVerticesInShape > 0 )
469     getShape( theMeshDS, TopAbs_VERTEX, tabCorner.data() );
470
471   int nbNodes = theHexaOutput->GmfStatKwd( meshID, GmfVertices );
472   if ( nbNodes > 0 )
473   {
474     theHexaOutput->GmfGotoKwd( meshID, GmfVertices );
475     double x,y,z;
476     for ( int aHexoticID = 1; aHexoticID <= nbNodes; ++aHexoticID )
477     {
478       if ( theAlgo->computeCanceled() )
479         return false;
480       theHexaOutput->GmfGetLin( meshID, GmfVertices, &x, &y, &z, &shapeID );
481       HexoticNode[ aHexoticID ] = theHelper->AddNode( x,y,z );
482     }
483   }
484
485   int nodeID[8];
486   SMDS_MeshNode* node[8];
487   SMDS_MeshElement * aHexoticElement;
488
489   nbCorners = theHexaOutput->GmfStatKwd( meshID, GmfCorners );
490   if ( nbCorners > 0 && nbDomains > 0 )
491   {
492     theHexaOutput->GmfGotoKwd( meshID, GmfCorners );
493     for ( int iElem = 0; iElem < nbCorners; iElem++ )
494     {
495       if ( theAlgo->computeCanceled() )
496         return false;
497       theHexaOutput->GmfGetLin( meshID, GmfCorners, &nodeID[0] );
498       node[0] = HexoticNode[ nodeID[0] ];
499       gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
500       for ( int i = 0; i < nbCorners; i++ )
501       {
502         aVertex = TopoDS::Vertex( tabCorner[i] );
503         gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
504         if ( aPnt.Distance( HexoticPnt ) < epsilon )
505         {
506           theMeshDS->SetNodeOnVertex( node[0], aVertex );
507           break;
508         }
509       }
510     }
511   }
512
513   int nbEdges = theHexaOutput->GmfStatKwd( meshID, GmfEdges );
514   if ( nbEdges > 0 )
515   {
516     theHexaOutput->GmfGotoKwd( meshID, GmfEdges );
517     for ( int iElem = 0; iElem < nbEdges; iElem++ )
518     {
519       if ( theAlgo->computeCanceled() )
520         return false;
521       theHexaOutput->GmfGetLin( meshID, GmfEdges, &nodeID[0], &nodeID[1], &shapeID );
522       for ( int i = 0; i < 2; ++i )
523       {
524         node[i] = HexoticNode[ nodeID[i]];
525         if ( shapeID > 0 && node[i]->getshapeId() < 1 )
526           theMeshDS->SetNodeOnEdge( node[i], shapeID );
527       }
528       aHexoticElement = theHelper->AddEdge( node[0], node[1] );
529       if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
530         theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
531     }
532   }
533
534   int nbQuad = theHexaOutput->GmfStatKwd( meshID, GmfQuadrilaterals );
535   if ( nbQuad > 0 )
536   {
537     theHexaOutput->GmfGotoKwd( meshID, GmfQuadrilaterals );
538     for ( int iElem = 0; iElem < nbQuad; iElem++ )
539     {
540       if ( theAlgo->computeCanceled() )
541         return false;
542       theHexaOutput->GmfGetLin( meshID, GmfQuadrilaterals,
543                                 &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3], &shapeID );
544       for ( int i = 0; i < 4; ++i )
545       {
546         node[i] = HexoticNode[ nodeID[i]];
547         if ( shapeID > 0 && node[i]->getshapeId() < 1 )
548           theMeshDS->SetNodeOnFace( node[i], shapeID );
549       }
550       aHexoticElement = theHelper->AddFace( node[0], node[1], node[2], node[3] );
551       if ( shapeID > 0 && aHexoticElement->getshapeId() < 1 )
552         theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
553     }
554   }
555
556   int nbHexa = theHexaOutput->GmfStatKwd( meshID, GmfHexahedra );
557   if ( nbHexa > 0 )
558   {
559     theHexaOutput->GmfGotoKwd( meshID, GmfHexahedra );
560     for ( int iElem = 0; iElem < nbHexa; iElem++ )
561     {
562       if ( theAlgo->computeCanceled() )
563         return false;
564       theHexaOutput->GmfGetLin( meshID, GmfHexahedra,
565                                 &nodeID[0], &nodeID[1], &nodeID[2], &nodeID[3],
566                                 &nodeID[4], &nodeID[5], &nodeID[6], &nodeID[7],
567                                 &shapeID );
568       for ( int i = 0; i < 8; ++i )
569       {
570         node[i] = HexoticNode[ nodeID[i]];
571       }
572       if ( nbDomains > 1 ) {
573         hexoticShapeID = shapeID - IdShapeRef;
574         if ( tabID[ hexoticShapeID ] == 0 ) {
575           aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
576           shapeID = aShape.IsNull() ? holeID : theMeshDS->ShapeToIndex( aShape );
577           tabID[ hexoticShapeID ] = shapeID;
578         }
579         else {
580           shapeID = tabID[ hexoticShapeID ];
581         }
582         if ( iElem == ( nbHexa - 1) ) {
583           int shapeAssociated = 0;
584           for ( int i=0; i<nbDomains; i++ ) {
585             if (tabID[i] > 0 )
586               shapeAssociated += 1;
587           }
588           if ( shapeAssociated != nbShape )
589             printWarning(nbShape, "domains", shapeAssociated);
590         }
591       }
592       else {
593         shapeID = tabID[0];
594       }
595
596       if ( shapeID != holeID )
597       {
598         for ( int i = 0; i < 8; ++i )
599         {
600           if ( node[i]->NbInverseElements( SMDSAbs_Face ) == 0 )
601             theMeshDS->SetNodeInVolume( node[i], shapeID );
602         }
603         aHexoticElement = theHelper->AddVolume( node[0], node[3], node[2], node[1],
604                                                 node[4], node[7], node[6], node[5]);
605         if ( aHexoticElement->getshapeId() < 1 )
606           theMeshDS->SetMeshElementOnShape( aHexoticElement, shapeID );
607       }
608     }
609   }
610   std::cout << std::endl;
611
612   // remove nodes in holes
613   if ( nbDomains > 1 )
614   {
615     SMESHDS_SubMesh* subMesh = 0;
616     for ( int i = 1; i <= nbNodes; ++i )
617       if ( HexoticNode[i]->NbInverseElements() == 0 )
618       {
619         theMeshDS->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
620       }
621   }
622
623   // avoid "Error: No mesh on sub-shape"
624   if ( theMesh->NbVolumes() > 0 )
625   {
626     SMESH_subMesh*         smMain = theMesh->GetSubMesh( theMesh->GetShapeToMesh() );
627     SMESH_subMeshIteratorPtr smIt = smMain->getDependsOnIterator( /*includeSelf=*/true );
628     while ( smIt->more() )
629     {
630       SMESH_subMesh* sm = smIt->next();
631       if ( !sm->IsMeshComputed() )
632         sm->SetIsAlwaysComputed( true );
633     }
634   }
635
636   return true;
637 }
638
639 //=============================================================================
640 /*!
641  * Pass parameters to MG-Hexa
642  */
643 //=============================================================================
644
645 void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp)
646 {
647   if (hyp) {
648     _hexesMinLevel = hyp->GetHexesMinLevel();
649     _hexesMaxLevel = hyp->GetHexesMaxLevel();
650     _hexesMinSize = hyp->GetMinSize();
651     _hexesMaxSize = hyp->GetMaxSize();
652     _approxAngle = hyp->GetGeomApproxAngle();
653     _hexoticIgnoreRidges = hyp->GetHexoticIgnoreRidges();
654     _hexoticInvalidElements = hyp->GetHexoticInvalidElements();
655     _hexoticSharpAngleThreshold = hyp->GetHexoticSharpAngleThreshold();
656     _hexoticNbProc = hyp->GetHexoticNbProc();
657     _hexoticWorkingDirectory = hyp->GetHexoticWorkingDirectory();
658     _hexoticVerbosity = hyp->GetHexoticVerbosity();
659     _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
660     _hexoticSdMode = hyp->GetHexoticSdMode();
661     _textOptions = hyp->GetAdvancedOption();
662     _sizeMaps = hyp->GetSizeMaps();
663     _nbLayers = hyp->GetNbLayers();
664     _firstLayerSize = hyp->GetFirstLayerSize();
665     _direction = hyp->GetDirection();
666     _growth = hyp->GetGrowth();
667     _facesWithLayers = hyp->GetFacesWithLayers();
668     _imprintedFaces = hyp->GetImprintedFaces();
669     _keepFiles = hyp->GetKeepFiles();
670     _removeLogOnSuccess = hyp->GetRemoveLogOnSuccess();
671     _logInStandardOutput = hyp->GetStandardOutputLog();
672   }
673   else {
674     std::cout << std::endl;
675     std::cout << "WARNING : The MG-Hexa default parameters are taken into account" << std::endl;
676     std::cout << "=======" << std::endl;
677     _hexesMinLevel = hyp->GetDefaultHexesMinLevel();
678     _hexesMaxLevel = hyp->GetDefaultHexesMaxLevel();
679     _hexesMinSize = hyp->GetDefaultMinSize();
680     _hexesMaxSize = hyp->GetDefaultMaxSize();
681     _approxAngle = hyp->GetDefaultGeomApproxAngle();
682     _hexoticIgnoreRidges = hyp->GetDefaultHexoticIgnoreRidges();
683     _hexoticInvalidElements = hyp->GetDefaultHexoticInvalidElements();
684     _hexoticSharpAngleThreshold = hyp->GetDefaultHexoticSharpAngleThreshold();
685     _hexoticNbProc = hyp->GetDefaultHexoticNbProc();
686     _hexoticWorkingDirectory = hyp->GetDefaultHexoticWorkingDirectory();
687     _hexoticVerbosity = hyp->GetDefaultHexoticVerbosity();
688     _hexoticMaxMemory = hyp->GetDefaultHexoticMaxMemory();
689     _hexoticSdMode = hyp->GetDefaultHexoticSdMode();
690     _textOptions = hyp->GetDefaultTextOptions();
691     _sizeMaps = hyp->GetDefaultHexoticSizeMaps();
692     _nbLayers = hyp->GetDefaultNbLayers();
693     _firstLayerSize = hyp->GetDefaultFirstLayerSize();
694     _direction = hyp->GetDefaultDirection();
695     _growth = hyp->GetDefaultGrowth();
696     _facesWithLayers = hyp->GetDefaultFacesWithLayers();
697     _imprintedFaces = hyp->GetDefaultImprintedFaces();
698     _keepFiles = hyp->GetDefaultKeepFiles();
699     _removeLogOnSuccess = hyp->GetDefaultRemoveLogOnSuccess();
700     _logInStandardOutput = hyp->GetDefaultStandardOutputLog();
701   }
702 }
703
704 //=======================================================================
705 //function : getSuffix
706 //purpose  : Returns a suffix that will be unique for the current process
707 //=======================================================================
708
709 static TCollection_AsciiString getSuffix()
710 {
711   TCollection_AsciiString aSuffix = "";
712   aSuffix += "_";
713 #ifndef WIN32
714   aSuffix += getenv("USER");
715 #else
716   std::string uname = std::string(getenv("USERNAME"));
717   replace(uname.begin(), uname.end(), ' ', '_');
718   aSuffix += uname.c_str();
719 #endif
720   aSuffix += "_";
721   aSuffix += Kernel_Utils::GetHostname().c_str();
722   aSuffix += "_";
723 #ifndef WIN32
724   aSuffix += getpid();
725 #else
726   aSuffix += _getpid();
727 #endif
728
729   return aSuffix;
730 }
731
732 //================================================================================
733 /*!
734  * \brief Returns a command to run MG-Hexa mesher
735  */
736 //================================================================================
737
738 std::string
739 HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
740                                          const TCollection_AsciiString& Hexotic_Out,
741                                          const TCollection_AsciiString& Hexotic_SizeMap_Prefix,
742                                          const bool                     forExecutable) const
743 {
744   std::cout << std::endl;
745   std::cout << "MG-Hexa execution..." << std::endl;
746   std::cout << _name << " parameters :" << std::endl;
747   std::cout << "    " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
748   std::cout << "    " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
749   std::cout << "    " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
750   std::cout << "    " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
751   std::cout << "    " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
752   std::cout << "    " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
753   std::cout << "    " << "MG-Hexa can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
754   std::cout << "    " << "MG-Hexa authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
755   std::cout << "    " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
756   std::cout << "    " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
757   std::cout << "    " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
758   std::cout << "    " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
759   std::cout << "    " << _name << " Text options = \"" << _textOptions << "\"" << std::endl;
760   std::cout << "    " << _name << " Number of layers = " << _nbLayers << std::endl;
761   std::cout << "    " << _name << " Size of the first layer  = " << _firstLayerSize << std::endl;
762   std::cout << "    " << _name << " Direction of the layers = " << ( _direction ? "Inward" : "Outward" ) << std::endl;
763   std::cout << "    " << _name << " Growth = " << _growth << std::endl;
764   if (!_facesWithLayers.empty()) {
765     std::cout << "    " << _name << " Faces with layers = ";
766     for (size_t i = 0; i < _facesWithLayers.size(); i++)
767     {
768       std::cout << _facesWithLayers.at(i);
769       if ((i + 1) != _facesWithLayers.size())
770         std::cout << ", ";
771     }
772     std::cout << std::endl;
773   }
774   if (!_imprintedFaces.empty()) {
775     std::cout << "    " << _name << " Imprinted faces = ";
776     for (size_t i = 0; i < _imprintedFaces.size(); i++)
777     {
778       std::cout << _imprintedFaces.at(i);
779       if ((i + 1) != _imprintedFaces.size())
780         std::cout << ", ";
781     }
782     std::cout << std::endl;
783   }
784
785   TCollection_AsciiString run_Hexotic("mg-hexa.exe");
786
787   TCollection_AsciiString minl         = " --min_level ", maxl = " --max_level ", angle = " --ridge_angle ";
788   TCollection_AsciiString mins         = " --min_size ", maxs = " --max_size ";
789   TCollection_AsciiString in           = " --in ",   out  = " --out ";
790   TCollection_AsciiString sizeMap      = " --read_sizemap ";
791   TCollection_AsciiString ignoreRidges = " --compute_ridges no ", invalideElements = " --allow_invalid_elements yes ";
792   TCollection_AsciiString subdom       = " --components ";
793 #ifndef WIN32
794   TCollection_AsciiString proc         = " --max_number_of_threads ";
795 #endif
796   TCollection_AsciiString verb         = " --verbose ";
797   TCollection_AsciiString maxmem       = " --max_memory ";
798
799   TCollection_AsciiString comNbLayers        = " --number_of_boundary_layers ";
800   TCollection_AsciiString comFirstLayerSize  = " --height_of_the_first_layer ";
801   TCollection_AsciiString comDirection       = " --boundary_layers_subdomain_direction ";
802   TCollection_AsciiString comGrowth          = " --boundary_layers_geometric_progression ";
803   TCollection_AsciiString comFacesWithLayers = " --boundary_layers_surface_ids ";
804   TCollection_AsciiString comImptintedFaces  = " --imprinted_surface_ids ";
805
806   TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory,
807                           textOptions, nbLayers, firstLayerSize, direction, growth, facesWithLayers, imprintedFaces;
808   minLevel   = _hexesMinLevel;
809   maxLevel   = _hexesMaxLevel;
810   minSize    = _hexesMinSize;
811   maxSize    = _hexesMaxSize;
812   sharpAngle = _hexoticSharpAngleThreshold;
813   // Mode translation for mg-tetra 1.1
814   switch ( _hexoticSdMode )
815   {
816     case 1:
817       mode = "outside_skin_only";
818       break;
819     case 2:
820       mode = "outside_components";
821       break;
822     case 3:
823       mode = "all";
824       break;
825     case 4:
826       mode = "all --manifold_geometry no";
827       break;
828   }
829   nbproc         = _hexoticNbProc;
830   verbosity      = _hexoticVerbosity;
831   maxMemory      = _hexoticMaxMemory;
832   textOptions    = (" " + _textOptions + " ").c_str();
833   nbLayers       = _nbLayers;
834   firstLayerSize = _firstLayerSize;
835   direction      = _direction ? "1" : "-1";
836   growth         = _growth;
837   for (size_t i = 0; i < _facesWithLayers.size(); i++)
838   {
839     facesWithLayers += _facesWithLayers[i];
840     if ((i + 1) != _facesWithLayers.size())
841       facesWithLayers += ",";
842   }
843   for (size_t i = 0; i < _imprintedFaces.size(); i++)
844   {
845     imprintedFaces += _imprintedFaces[i];
846     if ((i + 1) != _imprintedFaces.size())
847       imprintedFaces += ",";
848   }
849
850   if (_hexoticIgnoreRidges)
851     run_Hexotic +=  ignoreRidges;
852
853   if (_hexoticInvalidElements)
854     run_Hexotic +=  invalideElements;
855
856   if (_hexesMinSize > 0)
857     run_Hexotic +=  mins + minSize;
858
859   if (_hexesMaxSize > 0)
860     run_Hexotic +=  maxs + maxSize;
861
862   if (_hexesMinLevel > 0)
863     run_Hexotic +=  minl + minLevel;
864
865   if (_hexesMaxLevel > 0)
866     run_Hexotic +=  maxl + maxLevel;
867
868   if (_hexoticSharpAngleThreshold > 0)
869     run_Hexotic +=  angle + sharpAngle;
870   
871   if (_sizeMaps.begin() != _sizeMaps.end() && forExecutable )
872     run_Hexotic += sizeMap + Hexotic_SizeMap_Prefix;
873
874   if (_nbLayers       > 0 &&
875       _firstLayerSize > 0 &&
876       _growth         > 0 &&
877       !_facesWithLayers.empty())
878   {
879     run_Hexotic += comNbLayers + nbLayers;
880     run_Hexotic += comFirstLayerSize + firstLayerSize;
881     run_Hexotic += comDirection + direction;
882     run_Hexotic += comGrowth + growth;
883     run_Hexotic += comFacesWithLayers + facesWithLayers;
884     if (!_imprintedFaces.empty())
885       run_Hexotic += comImptintedFaces + imprintedFaces;
886   }
887   if ( forExecutable )
888     run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
889   run_Hexotic += subdom + mode;
890 #ifndef WIN32
891   run_Hexotic += proc + nbproc;
892 #endif
893   run_Hexotic += verb + verbosity;
894   run_Hexotic += maxmem + maxMemory;
895
896   if (!_textOptions.empty())
897     run_Hexotic += textOptions;
898
899   return run_Hexotic.ToCString();
900 }
901
902 // TODO : this is a duplication of some code found in BLSURFPlugin_BLSURF find a proper
903 // way to share it
904 TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
905 {
906   GEOM::GEOM_Object_var aGeomObj;
907   TopoDS_Shape S = TopoDS_Shape();
908   SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
909   if (!aSObj->_is_nil()) {
910     CORBA::Object_var obj = aSObj->GetObject();
911     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
912     aSObj->UnRegister();
913   }
914   if ( !aGeomObj->_is_nil() )
915     S = SMESH_Gen_i::GetSMESHGen()->GeomObjectToShape( aGeomObj.in() );
916   return S;
917 }
918
919 //================================================================================
920 /*!
921  * \brief Produces a .mesh file with the size maps informations to give to Hexotic
922  */
923 //================================================================================
924
925 std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( MG_Hexotic_API* mgInput,
926                                                                   std::string     sizeMapPrefix )
927 {
928   HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it;
929
930   std::vector<ControlPnt> points;
931   // Iterate on the size maps
932   for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
933   {
934     // Step 1 : Get the GEOM object entry and the size 
935     // from the _sizeMaps infos
936     std::string anEntry = it->first;
937     double aLocalSize = it->second;
938     TopoDS_Shape aShape = entryToShape( anEntry );
939     
940     // Step 2 : Create the points
941     createControlPoints( aShape, aLocalSize, points );
942   }
943
944   // Write the .mesh size map file
945
946   std::string myVerticesFile = sizeMapPrefix + ".mesh";
947   std::string      mySolFile = sizeMapPrefix + ".sol";
948   
949   // Open files
950   int verticesFileID =
951     mgInput->GmfOpenMesh( myVerticesFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );  
952   int solFileID =
953     mgInput->GmfOpenMesh( mySolFile.c_str(), GmfWrite, GMFVERSION, GMFDIMENSION );
954   
955   int pointsNumber = points.size();
956   
957   // Vertices Keyword
958   mgInput->GmfSetKwd( verticesFileID, GmfVertices, pointsNumber );
959   // SolAtVertices Keyword
960   int TypTab[] = {GmfSca};
961   mgInput->GmfSetKwd(solFileID, GmfSolAtVertices, pointsNumber, 1, TypTab);
962   
963   // Read the control points information from the vector and write it into the files
964   double ValTab[1];
965   std::vector<ControlPnt>::const_iterator points_it;
966   for (points_it = points.begin(); points_it != points.end(); points_it++ )
967   {
968     mgInput->GmfSetLin( verticesFileID, GmfVertices, points_it->X(), points_it->Y(), points_it->Z(), 0 );
969     ValTab[0] = points_it->Size();
970     mgInput->GmfSetLin( solFileID, GmfSolAtVertices, ValTab);
971   }
972
973   // Close Files
974   mgInput->GmfCloseMesh( verticesFileID );
975   mgInput->GmfCloseMesh( solFileID );
976
977   std::vector<std::string> fileNames(2);
978   fileNames[0] = myVerticesFile;
979   fileNames[1] = mySolFile;
980
981   return fileNames;
982 }
983
984 //=============================================================================
985 /*!
986  * Here we are going to use the MG-Hexa mesher
987  */
988 //=============================================================================
989
990 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
991                                     const TopoDS_Shape& /*aShape*/)
992 {
993   _computeCanceled = false;
994   bool Ok = true;
995   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
996   TCollection_AsciiString hexahedraMessage;
997
998   _nbShape = countShape( &aMesh, TopAbs_SOLID );  // we count the number of shapes
999
1000   {
1001     // create bounding box for each shape of the compound
1002
1003     int iShape = 0;
1004     TopoDS_Shape *tabShape;
1005     double **tabBox;
1006
1007     tabShape = new TopoDS_Shape[_nbShape];
1008     tabBox   = new double*[_nbShape];
1009     for (int i=0; i<_nbShape; i++)
1010       tabBox[i] = new double[6];
1011     double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1012
1013     TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1014     for (; expBox.More(); expBox.Next()) {
1015       tabShape[iShape] = expBox.Current();
1016       Bnd_Box BoundingBox;
1017       BRepBndLib::Add(expBox.Current(), BoundingBox);
1018       BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1019       tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1020       tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1021       tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1022       iShape++;
1023     }
1024
1025     SetParameters(_hypothesis);
1026
1027     TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();
1028     TCollection_AsciiString aQuote("");
1029 #ifdef WIN32
1030     aQuote = "\"";
1031     if ( aTmpDir.Value(aTmpDir.Length()) != '\\' ) aTmpDir += '\\';
1032 #else
1033     if ( aTmpDir.Value(aTmpDir.Length()) != '/' ) aTmpDir += '/';
1034 #endif
1035     TCollection_AsciiString Hexotic_In(""), Hexotic_Out, Hexotic_SizeMap_Prefix;
1036     TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1037     TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
1038
1039     std::map <int,int> aSmdsToHexoticIdMap;
1040     std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1041
1042     MG_Hexotic_API mgHexa( _computeCanceled, _progress );
1043
1044     Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1045 #ifdef WITH_BLSURFPLUGIN
1046     bool defaultInputFile = true;
1047     if (_blsurfHypo && _blsurfHypo->GetElementType() == BLSURFPlugin_Hypothesis::Triangles ) {
1048       Hexotic_In = _blsurfHypo->GetGMFFile().c_str();
1049       if ( !Hexotic_In.IsEmpty() &&
1050            SMESH_File( _blsurfHypo->GetGMFFile() ).exists() )
1051       {
1052         MESSAGE("Use output file from blsurf as input file from hexotic: " << Hexotic_In);
1053         mgHexa.SetUseExecutable();
1054         defaultInputFile = false;
1055       }
1056     }
1057     if (defaultInputFile) {
1058 #endif
1059       Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1060       removeHexoticFiles(Hexotic_In, Hexotic_Out);
1061       splitQuads(aMesh); // quadrangles are no longer acceptable as input
1062       if ( mgHexa.IsExecutable() )
1063       {
1064         std::cout << std::endl;
1065         std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1066       }
1067       writeInput( &mgHexa, Hexotic_In.ToCString(), meshDS );
1068 #ifdef WITH_BLSURFPLUGIN
1069     }
1070     else {
1071       removeFile( Hexotic_Out );
1072     }
1073 #endif
1074     
1075     Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
1076     std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
1077     
1078     std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable() );
1079     run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString();  // dump into file
1080     mgHexa.SetLogFile( aLogFileName.ToCString() );
1081     std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1082
1083     std::cout << std::endl;
1084     std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1085
1086     if ( mgHexa.IsExecutable() )
1087     {
1088 #ifndef WIN32    
1089       modeFile_In += Hexotic_In;
1090       system( modeFile_In.ToCString() );
1091 #endif
1092     }
1093     aSmdsToHexoticIdMap.clear();
1094     aHexoticIdToNodeMap.clear();
1095
1096     MESSAGE("HexoticPlugin_Hexotic::Compute");
1097
1098     
1099     std::string errStr;
1100     Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
1101
1102
1103     // --------------
1104     // read a result
1105     // --------------
1106
1107     if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
1108     {
1109 #ifndef WIN32
1110       modeFile_Out += Hexotic_Out;
1111       system( modeFile_Out.ToCString() );
1112 #endif
1113     }
1114     SMESH_MesherHelper aHelper( aMesh );
1115
1116     Ok = readResult( &mgHexa, Hexotic_Out.ToCString(),
1117                      this,
1118                      &aHelper, _nbShape, tabShape, tabBox );
1119
1120     std::string log = mgHexa.GetLog();
1121     hexahedraMessage = "failed";
1122     if ( Ok )
1123     {
1124       hexahedraMessage = "success";
1125       if ( _removeLogOnSuccess )
1126         removeFile( aLogFileName );
1127     }
1128     else if ( !log.empty() )
1129     {
1130       if( _computeCanceled )
1131         error( "interruption initiated by user" );
1132       else
1133       {
1134         // get problem description from the log file
1135         char msgLic[] = " Dlim ";
1136         const char* fileBeg = &log[0], *fileEnd = fileBeg + log.size();
1137         if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1138           error("Licence problems.");
1139       }
1140     }
1141     else if ( !errStr.empty() )
1142     {
1143       // the log file is empty
1144       removeFile( aLogFileName );
1145       INFOS( "MG-Hexa Error, " << errStr);
1146       error(COMPERR_ALGO_FAILED, errStr);
1147     }
1148
1149     if ( !Ok && mgHexa.IsExecutable() )
1150       std::cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
1151
1152     if ( !_keepFiles )
1153     {
1154       if (! Ok && _computeCanceled )
1155         removeFile( aLogFileName );
1156       removeFile(Hexotic_Out);
1157       removeFile(Hexotic_In);
1158       for ( size_t i = 0; i < sizeMapFiles.size(); i++ )
1159         removeFile( sizeMapFiles[i].c_str() );
1160     }
1161     std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1162     std::cout << std::endl;
1163
1164     delete [] tabShape;
1165     for (int i=0; i<_nbShape; i++)
1166       delete [] tabBox[i];
1167     delete [] tabBox;
1168     _nbShape = 0;
1169     _iShape  = 0;
1170   }
1171
1172   return Ok;
1173 }
1174
1175 //=============================================================================
1176 /*!
1177  * \brief Computes mesh without geometry
1178  *  \param aMesh - the mesh
1179  *  \param aHelper - helper that must be used for adding elements to \aaMesh
1180  *  \retval bool - is a success
1181  *
1182  * The method is called if ( !aMesh->HasShapeToMesh() )
1183  */
1184 //=============================================================================
1185
1186 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
1187 {
1188   _computeCanceled = false;
1189
1190   bool Ok = true;
1191   TCollection_AsciiString hexahedraMessage;
1192   TCollection_AsciiString aQuote("");
1193 #ifdef WIN32
1194   aQuote = "\"";
1195 #endif
1196   SetParameters(_hypothesis);
1197
1198   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();//getTmpDir();
1199   TCollection_AsciiString Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix;
1200   TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1201   TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
1202
1203   std::map <int,int> aSmdsToHexoticIdMap;
1204   std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1205
1206   Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1207   Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1208   Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
1209
1210   MG_Hexotic_API mgHexa( _computeCanceled, _progress );
1211
1212   std::vector<std::string> sizeMapFiles = writeSizeMapFile( &mgHexa, Hexotic_SizeMap_Prefix.ToCString() );
1213
1214   std::string run_Hexotic = getHexoticCommand(aQuote + Hexotic_In + aQuote, aQuote + Hexotic_Out + aQuote, Hexotic_SizeMap_Prefix, mgHexa.IsExecutable());
1215   run_Hexotic += std::string(" 1> ") + aQuote.ToCString() + aLogFileName.ToCString() + aQuote.ToCString();  // dump into file
1216   mgHexa.SetLogFile( aLogFileName.ToCString() );
1217   std::cout << "Creating MG-Hexa log file : " << aLogFileName << std::endl;
1218
1219   removeHexoticFiles(Hexotic_In, Hexotic_Out);
1220
1221   splitQuads(aMesh); // quadrangles are no longer acceptable as input
1222
1223   std::cout << std::endl;
1224   std::cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1225   writeInput( &mgHexa, Hexotic_In.ToCString(), aHelper->GetMeshDS() );
1226   if ( mgHexa.IsExecutable() )
1227   {
1228 #ifndef WIN32    
1229     modeFile_In += Hexotic_In;
1230     system( modeFile_In.ToCString() );
1231 #endif
1232   }
1233   aSmdsToHexoticIdMap.clear();
1234   aHexoticIdToNodeMap.clear();
1235
1236   MESSAGE("HexoticPlugin_Hexotic::Compute");
1237
1238   std::cout << std::endl;
1239   std::cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1240
1241   std::string errStr;
1242   Ok = mgHexa.Compute( run_Hexotic, errStr ); // run
1243
1244   // --------------
1245   // read a result
1246   // --------------
1247
1248   if ( mgHexa.IsExecutable() && SMESH_File( Hexotic_Out.ToCString() ).exists() )
1249   {
1250     modeFile_Out += Hexotic_Out;
1251     system( modeFile_Out.ToCString() );
1252   }
1253
1254   Ok = Ok && readResult( &mgHexa, Hexotic_Out.ToCString(), this, aHelper );
1255
1256   std::string log = mgHexa.GetLog();
1257   if ( Ok )
1258   {
1259     hexahedraMessage = "success";
1260   }
1261   else
1262   {
1263     hexahedraMessage = "failed";
1264     if ( mgHexa.IsExecutable() )
1265       std::cout << "Problem with MG-Hexa output file " << Hexotic_Out << std::endl;
1266
1267     if ( log.find( " license " ) != std::string::npos ||
1268          log.find( " Dlim "    ) != std::string::npos )
1269       error("License problems.");
1270
1271     if ( !errStr.empty() )
1272       error(errStr);
1273   }
1274   std::cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1275   std::cout << std::endl;
1276
1277   if(_computeCanceled)
1278     return error(SMESH_Comment("interruption initiated by user"));
1279   removeFile(Hexotic_Out);
1280   removeFile(Hexotic_In);
1281   if ( Ok )
1282     removeFile(aLogFileName);
1283   for( size_t i=0; i<sizeMapFiles.size(); i++)
1284   {
1285     removeFile( TCollection_AsciiString(sizeMapFiles[i].c_str()) );
1286   }
1287   return Ok;
1288 }
1289
1290 //=============================================================================
1291 /*!
1292  *
1293  */
1294 //=============================================================================
1295
1296 bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh&         aMesh,
1297                                      const TopoDS_Shape& aShape,
1298                                      MapShapeNbElems&    aResMap)
1299 {
1300   std::vector<int> aResVec(SMDSEntity_Last);
1301   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1302   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
1303   aResMap.insert(std::make_pair(sm,aResVec));
1304
1305   SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1306   smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Evaluation is not implemented",this));
1307
1308   return true;
1309 }
1310
1311 void HexoticPlugin_Hexotic::CancelCompute()
1312 {
1313   _computeCanceled = true;
1314 #ifdef WIN32
1315 #else
1316   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str(); //getTmpDir();
1317   TCollection_AsciiString Hexotic_In = aTmpDir + "Hexotic_In.mesh";
1318   TCollection_AsciiString cmd = TCollection_AsciiString("ps ux | grep ") + Hexotic_In;
1319   cmd += TCollection_AsciiString(" | grep -v grep | awk '{print $2}' | xargs kill -9 > /dev/null 2>&1");
1320   system( cmd.ToCString() );
1321 #endif
1322 }