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