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