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