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