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