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