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