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