Salome HOME
remove "using namespace std" from SMESH headers
[plugins/hexoticplugin.git] / src / HexoticPlugin / HexoticPlugin_Hexotic.cxx
1 // Copyright (C) 2007-2015  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
28 #include "utilities.h"
29
30 #ifndef WIN32
31 #include <sys/sysinfo.h>
32 #else
33 #include <errno.h>
34 #include <process.h>
35 #endif
36
37 #ifdef _DEBUG_
38 #define DUMP(txt) \
39 //  cout << txt
40 #else
41 #define DUMP(txt)
42 #endif
43
44 #include <SMESHDS_Mesh.hxx>
45 #include <SMESHDS_GroupBase.hxx>
46 #include <SMESH_ComputeError.hxx>
47 #include <SMESH_File.hxx>
48 #include <SMESH_Gen.hxx>
49 #include <SMESH_HypoFilter.hxx>
50 #include <SMESH_MesherHelper.hxx>
51 #include <SMESH_subMesh.hxx>
52
53 #include <list>
54 #include <cstdlib>
55 #include <iostream>
56
57 #include <Standard_ProgramError.hxx>
58
59 #include <BRep_Tool.hxx>
60 #include <BRepBndLib.hxx>
61 #include <BRepClass3d_SolidClassifier.hxx>
62 #include <BRepBuilderAPI_MakeVertex.hxx>
63 #include <BRepExtrema_DistShapeShape.hxx>
64 #include <OSD_File.hxx>
65 #include <Precision.hxx>
66 #include <TopExp_Explorer.hxx>
67 #include <TopTools_MapOfShape.hxx>
68 #include <TopoDS.hxx>
69 #include <gp_Pnt.hxx>
70 #include <gp_Lin.hxx>
71 #include <GCPnts_UniformAbscissa.hxx>
72 #include <IntCurvesFace_Intersector.hxx>
73 #include <BRepMesh_IncrementalMesh.hxx>
74 #include <Poly_Triangulation.hxx>
75 #include <gp_Ax3.hxx>
76 #include <GeomAdaptor_Curve.hxx>
77
78 #include <Basics_Utils.hxx>
79 #include "GEOMImpl_Types.hxx"
80 #include "GEOM_wrap.hxx"
81
82 static void removeFile( const TCollection_AsciiString& fileName )
83 {
84   try {
85     OSD_File( fileName ).Remove();
86   }
87   catch ( Standard_ProgramError ) {
88     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
89   }
90 }
91
92 //=============================================================================
93 /*!
94  *  
95  */
96 //=============================================================================
97
98 HexoticPlugin_Hexotic::HexoticPlugin_Hexotic(int hypId, int studyId, SMESH_Gen* gen)
99   : SMESH_3D_Algo(hypId, studyId, gen)
100 {
101   MESSAGE("HexoticPlugin_Hexotic::HexoticPlugin_Hexotic");
102   _name = "MG-Hexa";
103   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
104 //   _onlyUnaryInput = false;
105   _requireShape = false;
106   _iShape=0;
107   _nbShape=0;
108   _hexoticFilesKept=false;
109   _compatibleHypothesis.push_back( HexoticPlugin_Hypothesis::GetHypType() );
110 #ifdef WITH_BLSURFPLUGIN
111   _blsurfHypo = NULL;
112 #endif
113   _compute_canceled = false;
114   
115   // Copy of what is done in BLSURFPLugin TODO : share the code
116   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
117   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
118   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
119   
120   myStudy = NULL;
121   myStudy = aStudyMgr->GetStudyByID(_studyId);
122   if (myStudy)
123     MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
124 }
125
126 //=============================================================================
127 /*!
128  *  
129  */
130 //=============================================================================
131
132 HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic()
133 {
134   MESSAGE("HexoticPlugin_Hexotic::~HexoticPlugin_Hexotic");
135 }
136
137
138 #ifdef WITH_BLSURFPLUGIN
139 bool HexoticPlugin_Hexotic::CheckBLSURFHypothesis( SMESH_Mesh&         aMesh,
140                                                    const TopoDS_Shape& aShape )
141 {
142   // MESSAGE("HexoticPlugin_Hexotic::CheckBLSURFHypothesis");
143   _blsurfHypo = NULL;
144
145   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
146   const SMESHDS_Hypothesis* theHyp;
147
148   // If a BLSURF hypothesis is applied, get it
149   SMESH_HypoFilter blsurfFilter;
150   blsurfFilter.Init( blsurfFilter.HasName( BLSURFPlugin_Hypothesis::GetHypType() ));
151   std::list<const SMESHDS_Hypothesis *> appliedHyps;
152   aMesh.GetHypotheses( aShape, blsurfFilter, appliedHyps, false );
153
154   if ( appliedHyps.size() > 0 ) {
155     itl = appliedHyps.begin();
156     theHyp = (*itl); // use only the first hypothesis
157     std::string hypName = theHyp->GetName();
158     if (hypName == BLSURFPlugin_Hypothesis::GetHypType()) {
159       _blsurfHypo = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
160       ASSERT(_blsurfHypo);
161       return true;
162     }
163   }
164   return false;
165 }
166 #endif
167
168 //=============================================================================
169 /*!
170  *  
171  */
172 //=============================================================================
173
174 bool HexoticPlugin_Hexotic::CheckHypothesis( SMESH_Mesh&                          aMesh,
175                                              const TopoDS_Shape&                  aShape,
176                                              SMESH_Hypothesis::Hypothesis_Status& aStatus )
177 {
178   // MESSAGE("HexoticPlugin_Hexotic::CheckHypothesis");
179   _hypothesis = NULL;
180
181   std::list<const SMESHDS_Hypothesis*>::const_iterator itl;
182   const SMESHDS_Hypothesis* theHyp;
183
184   const std::list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, false);
185   int nbHyp = hyps.size();
186   if (!nbHyp) {
187     aStatus = SMESH_Hypothesis::HYP_OK;
188     return true;  // can work with no hypothesis
189   }
190
191   itl = hyps.begin();
192   theHyp = (*itl); // use only the first hypothesis
193
194   std::string hypName = theHyp->GetName();
195   if (hypName == HexoticPlugin_Hypothesis::GetHypType() ) {
196     _hypothesis = static_cast<const HexoticPlugin_Hypothesis*> (theHyp);
197     ASSERT(_hypothesis);
198     aStatus = SMESH_Hypothesis::HYP_OK;
199   }
200   else
201     aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
202   
203 #ifdef WITH_BLSURFPLUGIN
204   CheckBLSURFHypothesis(aMesh, aShape);
205 #endif
206   
207   return aStatus == SMESH_Hypothesis::HYP_OK;
208 }
209
210 //=======================================================================
211 //function : findShape
212 //purpose  :
213 //=======================================================================
214
215 static TopoDS_Shape findShape(SMDS_MeshNode**     t_Node,
216                               TopoDS_Shape        aShape,
217                               const TopoDS_Shape* t_Shape,
218                               double**            t_Box,
219                               const int           nShape)
220 {
221   double pntCoor[3];
222   int iShape, nbNode = 8;
223
224   for ( int i=0; i<3; i++ ) {
225     pntCoor[i] = 0;
226     for ( int j=0; j<nbNode; j++ ) {
227       if ( i == 0) pntCoor[i] += t_Node[j]->X();
228       if ( i == 1) pntCoor[i] += t_Node[j]->Y();
229       if ( i == 2) pntCoor[i] += t_Node[j]->Z();
230     }
231     pntCoor[i] /= nbNode;
232   }
233   gp_Pnt aPnt(pntCoor[0], pntCoor[1], pntCoor[2]);
234
235   if ( aShape.IsNull() ) aShape = t_Shape[0];
236   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
237   if ( !(SC.State() == TopAbs_IN) ) {
238     aShape.Nullify();
239     for (iShape = 0; iShape < nShape && aShape.IsNull(); iShape++) {
240       if ( !( pntCoor[0] < t_Box[iShape][0] || t_Box[iShape][1] < pntCoor[0] ||
241               pntCoor[1] < t_Box[iShape][2] || t_Box[iShape][3] < pntCoor[1] ||
242               pntCoor[2] < t_Box[iShape][4] || t_Box[iShape][5] < pntCoor[2]) ) {
243         BRepClass3d_SolidClassifier SC (t_Shape[iShape], aPnt, Precision::Confusion());
244         if (SC.State() == TopAbs_IN)
245           aShape = t_Shape[iShape];
246       }
247     }
248   }
249   return aShape;
250 }
251
252 //=======================================================================
253 //function : getNbShape
254 //purpose  :
255 //=======================================================================
256
257 static int getNbShape(std::string aFile, std::string aString, int defaultValue=0) {
258   int number = defaultValue;
259   std::string aLine;
260   std::ifstream file(aFile.c_str());
261   while ( !file.eof() ) {
262     getline( file, aLine);
263     if ( aLine == aString ) {
264       getline( file, aLine);
265       std::istringstream stringFlux( aLine );
266       stringFlux >> number;
267       number = ( number + defaultValue + std::abs(number - defaultValue) ) / 2;
268       break;
269     }
270   }
271   file.close();
272   return number;
273 }
274
275 //=======================================================================
276 //function : countShape
277 //purpose  :
278 //=======================================================================
279
280 template < class Mesh, class Shape >
281 static int countShape( Mesh* mesh, Shape shape ) {
282   TopExp_Explorer expShape ( mesh->ShapeToMesh(), 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   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
301   TopTools_MapOfShape mapShape;
302   for ( int i=0; expShape.More(); expShape.Next() ) {
303     if (mapShape.Add(expShape.Current())) {
304       t_Shape[i] = expShape.Current();
305       i++;
306     }
307   }
308   return;
309 }
310
311 //=======================================================================
312 //function : printWarning
313 //purpose  :
314 //=======================================================================
315
316 static void printWarning(const int nbExpected, std::string aString, const int nbFound) {
317   cout << std::endl;
318   cout << "WARNING : " << nbExpected << " " << aString << " expected, MG-Hexa has found " << nbFound << std::endl;
319   cout << "=======" << std::endl;
320   cout << std::endl;
321   return;
322 }
323
324 //=======================================================================
325 //function : removeHexoticFiles
326 //purpose  :
327 //=======================================================================
328
329 static void removeHexoticFiles(TCollection_AsciiString file_In, TCollection_AsciiString file_Out) {
330   removeFile( file_In );
331   removeFile( file_Out );
332 }
333
334 //=======================================================================
335 //function : splitQuads
336 //purpose  : splits all quadrangles into triangles
337 //=======================================================================
338
339 static void splitQuads(SMESH_Mesh& aMesh)
340 {
341   SMESH_MeshEditor spliter( &aMesh );
342
343   TIDSortedElemSet elems;
344   SMDS_ElemIteratorPtr eIt = aMesh.GetMeshDS()->elementsIterator();
345   while( eIt->more() )
346     elems.insert( elems.end(), eIt->next() );
347   
348   spliter.QuadToTri ( elems, /*the13Diag=*/true);
349 }
350
351 //=======================================================================
352 //function : readResult
353 //purpose  : Read GMF file in case of a mesh with geometry
354 //=======================================================================
355
356 static bool readResult(std::string         theFile,
357                        HexoticPlugin_Hexotic*  theAlgo,
358                        SMESHDS_Mesh*       theMesh,
359                        const int           nbShape,
360                        const TopoDS_Shape* tabShape,
361                        double**            tabBox)
362 {
363   // ---------------------------------
364   // Read generated elements and nodes
365   // ---------------------------------
366
367   TopoDS_Shape aShape;
368   TopoDS_Vertex aVertex;
369   std::string token;
370   int EndOfFile = 0, nbElem = 0, nField = 9, nbRef = 0;
371   int aHexoticNodeID = 0, shapeID, hexoticShapeID;
372   const int IdShapeRef = 2;
373   int *tabID, *tabRef, *nodeAssigne;
374   bool *tabDummy, hasDummy = false;
375   double epsilon = Precision::Confusion();
376   std::map <std::string,int> mapField;
377   SMDS_MeshNode** HexoticNode;
378   TopoDS_Shape *tabCorner, *tabEdge;
379
380   const int nbDomains = countShape( theMesh, TopAbs_SHELL );
381   const int holeID = -1;
382
383   // tabID    = new int[nbShape];
384   tabID    = new int[nbDomains];
385   tabRef   = new int[nField];
386   tabDummy = new bool[nField];
387
388   for (int i=0; i<nbDomains; i++)
389     tabID[i] = 0;
390   if ( nbDomains == 1 )
391     tabID[0] = theMesh->ShapeToIndex( tabShape[0] );
392
393   mapField["MeshVersionFormatted"] = 0; tabRef[0] = 0; tabDummy[0] = false;
394   mapField["Dimension"]            = 1; tabRef[1] = 0; tabDummy[1] = false;
395   mapField["Vertices"]             = 2; tabRef[2] = 3; tabDummy[2] = true;
396   mapField["Corners"]              = 3; tabRef[3] = 1; tabDummy[3] = false;
397   mapField["Edges"]                = 4; tabRef[4] = 2; tabDummy[4] = true;
398   mapField["Ridges"]               = 5; tabRef[5] = 1; tabDummy[5] = false;
399   mapField["Quadrilaterals"]       = 6; tabRef[6] = 4; tabDummy[6] = true;
400   mapField["Hexahedra"]            = 7; tabRef[7] = 8; tabDummy[7] = true;
401   mapField["End"]                  = 8; tabRef[8] = 0; tabDummy[0] = false;
402
403   SMDS_NodeIteratorPtr itOnHexoticInputNode = theMesh->nodesIterator();
404   while ( itOnHexoticInputNode->more() )
405     theMesh->RemoveNode( itOnHexoticInputNode->next() );
406
407   int nbVertices   = getNbShape(theFile, "Vertices");
408   int nbCorners    = getNbShape(theFile, "Corners", countShape( theMesh, TopAbs_VERTEX ));
409   int nbShapeEdge  = countShape( theMesh, TopAbs_EDGE );
410
411   tabCorner   = new TopoDS_Shape[ nbCorners ];
412   tabEdge     = new TopoDS_Shape[ nbShapeEdge ];
413   nodeAssigne = new int[ nbVertices + 1 ];
414   HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
415
416   getShape(theMesh, TopAbs_VERTEX, tabCorner);
417   getShape(theMesh, TopAbs_EDGE,   tabEdge);
418
419   MESSAGE("Read " << theFile << " file");
420   std::ifstream fileRes(theFile.c_str());
421   ASSERT(fileRes);
422
423   while ( EndOfFile == 0  ) {
424     int dummy;
425     fileRes >> token;
426
427     if (mapField.count(token)) {
428       nField   = mapField[token];
429       nbRef    = tabRef[nField];
430       hasDummy = tabDummy[nField];
431     }
432     else {
433       nField = -1;
434       nbRef = 0;
435     }
436
437     nbElem = 0;
438     if ( nField < int(mapField.size() - 1) && nField >= 0 )
439       fileRes >> nbElem;
440
441     switch (nField) {
442       case 0: { // "MeshVersionFormatted"
443         MESSAGE(token << " " << nbElem);
444         break;
445       }
446       case 1: { // "Dimension"
447         MESSAGE("Mesh dimension " << nbElem << "D");
448         break;
449       }
450       case 2: { // "Vertices"
451         MESSAGE("Read " << nbElem << " " << token);
452         int aHexoticID;
453         double *coord;
454         SMDS_MeshNode * aHexoticNode;
455
456         coord = new double[nbRef];
457         for ( int iElem = 0; iElem < nbElem; iElem++ ) {
458           if(theAlgo->computeCanceled())
459             {
460               return false;
461             }
462           aHexoticID = iElem + 1;
463           for ( int iCoord = 0; iCoord < 3; iCoord++ )
464             fileRes >> coord[ iCoord ];
465           fileRes >> dummy;
466           aHexoticNode = theMesh->AddNode(coord[0], coord[1], coord[2]);
467           HexoticNode[ aHexoticID ] = aHexoticNode;
468           nodeAssigne[ aHexoticID ] = 0;
469         }
470         delete [] coord;
471         break;
472       }
473       case 3: // "Corners"
474       case 4: // "Edges"
475       case 5: // "Ridges"
476       case 6: // "Quadrilaterals"
477       case 7: { // "Hexahedra"
478         MESSAGE("Read " << nbElem << " " << token);
479         SMDS_MeshNode** node;
480         int nodeDim, *nodeID;
481         SMDS_MeshElement * aHexoticElement = 0;
482
483         node   = new SMDS_MeshNode*[ nbRef ];
484         nodeID = new int[ nbRef ];
485         for ( int iElem = 0; iElem < nbElem; iElem++ ) {
486           if(theAlgo->computeCanceled())
487             {
488               return false;
489             }
490           for ( int iRef = 0; iRef < nbRef; iRef++ ) {
491             fileRes >> aHexoticNodeID;                          // read nbRef aHexoticNodeID
492             node[ iRef ]   = HexoticNode[ aHexoticNodeID ];
493             nodeID[ iRef ] = aHexoticNodeID;
494           }
495           if ( hasDummy )
496             fileRes >> dummy;
497           switch (nField) {
498             case 3: { // "Corners"
499               nodeDim = 1;
500               gp_Pnt HexoticPnt ( node[0]->X(), node[0]->Y(), node[0]->Z() );
501               for ( int i=0; i<nbElem; i++ ) {
502                 aVertex = TopoDS::Vertex( tabCorner[i] );
503                 gp_Pnt aPnt = BRep_Tool::Pnt( aVertex );
504                 if ( aPnt.Distance( HexoticPnt ) < epsilon )
505                   break;
506               }
507               if ( nodeAssigne[ nodeID[0] ] != 0 ) { // because "Edges" go before "Corners"
508                 theMesh->UnSetNodeOnShape( node[0] );
509                 nodeAssigne[ nodeID[0] ] = 0;
510               }
511               break;
512             }
513             case 4: { // "Edges"
514               nodeDim = 2;
515               aHexoticElement = theMesh->AddEdge( node[0], node[1] );
516               int iNode = 1;
517               if ( nodeAssigne[ nodeID[0] ] == 0 || nodeAssigne[ nodeID[0] ] == 2 )
518                 iNode = 0;
519               shapeID = dummy;
520               break;
521             }
522             case 5: { // "Ridges"
523               break;
524             }
525             case 6: { // "Quadrilaterals"
526               nodeDim = 3;
527               aHexoticElement = theMesh->AddFace( node[0], node[1], node[2], node[3] );
528               shapeID = dummy;
529               break;
530             }
531             case 7: { // "Hexahedra"
532               nodeDim = 4;
533               if ( nbDomains > 1 ) {
534                 hexoticShapeID = dummy - IdShapeRef;
535                 if ( tabID[ hexoticShapeID ] == 0 ) {
536                   aShape = findShape(node, aShape, tabShape, tabBox, nbShape);
537                   shapeID = aShape.IsNull() ? holeID : theMesh->ShapeToIndex( aShape );
538                   tabID[ hexoticShapeID ] = shapeID;
539                 }
540                 else
541                   shapeID = tabID[ hexoticShapeID ];
542                 if ( iElem == (nbElem - 1) ) {
543                   int shapeAssociated = 0;
544                   for ( int i=0; i<nbDomains; i++ ) {
545                     if (tabID[i] > 0 )
546                       shapeAssociated += 1;
547                   }
548                   if ( shapeAssociated != nbShape )
549                     printWarning(nbShape, "domains", shapeAssociated);
550                 }
551               }
552               else {
553                 shapeID = tabID[0];
554               }
555               if ( shapeID != holeID )
556                 aHexoticElement = theMesh->AddVolume( node[0], node[3], node[2], node[1], node[4], node[7], node[6], node[5] );
557               break;
558             }
559           } // switch (nField)
560
561           if ( token != "Ridges" && ( shapeID > 0 || token == "Corners")) {
562             for ( int i=0; i<nbRef; i++ ) {
563               if ( nodeAssigne[ nodeID[i] ] == 0 ) {
564                 if      ( token == "Corners" )        theMesh->SetNodeOnVertex( node[0], aVertex );
565                 else if ( token == "Edges" )          theMesh->SetNodeOnEdge( node[i], shapeID );
566                 else if ( token == "Quadrilaterals" ) theMesh->SetNodeOnFace( node[i], shapeID );
567                 else if ( token == "Hexahedra" )      theMesh->SetNodeInVolume( node[i], shapeID );
568                 nodeAssigne[ nodeID[i] ] = nodeDim;
569               }
570             }
571             if ( token != "Corners" && aHexoticElement )
572               theMesh->SetMeshElementOnShape( aHexoticElement, shapeID );
573           }
574         }
575         delete [] node;
576         delete [] nodeID;
577         break;
578       }
579       case 8: { // "End"
580         EndOfFile = 1;
581         MESSAGE("End of " << theFile << " file");
582         break;
583       }
584       default: {
585         MESSAGE("Unknown Token: " << token);
586       }
587     }
588   }
589   cout << std::endl;
590
591   // remove nodes in holes
592   if ( nbDomains > 1 )
593   {
594     SMESHDS_SubMesh* subMesh;
595     for ( int i = 1; i <= nbVertices; ++i )
596       if ( HexoticNode[i]->NbInverseElements() == 0 )
597       {
598         subMesh =  HexoticNode[i]->getshapeId() > 0 ? theMesh->MeshElements(HexoticNode[i]->getshapeId() ) : 0;
599         theMesh->RemoveFreeNode( HexoticNode[i], subMesh, /*fromGroups=*/false );
600       }
601   }
602   delete [] tabID;
603   delete [] tabRef;
604   delete [] tabDummy;
605   delete [] tabCorner;
606   delete [] tabEdge;
607   delete [] nodeAssigne;
608   delete [] HexoticNode;
609   return true;
610 }
611
612
613 //=======================================================================
614 //function : readResult
615 //purpose  : Read GMF file in case of a mesh w/o geometry
616 //=======================================================================
617
618 static bool readResult(std::string theFile,
619                        HexoticPlugin_Hexotic*  theAlgo,
620                        SMESH_MesherHelper* theHelper)
621 {
622   SMESHDS_Mesh* theMesh = theHelper->GetMeshDS();
623
624   // ---------------------------------
625   // Read generated elements and nodes
626   // ---------------------------------
627
628   std::string token;
629   const int nbField = 9;
630   int nField, EndOfFile = 0, nbElem = 0, nbRef = 0;
631   int aHexoticNodeID = 0, shapeID;
632   int tabRef[nbField], *nodeAssigne;
633   bool tabDummy[nbField], hasDummy = false;
634   std::map <std::string,int> mapField;
635   SMDS_MeshNode** HexoticNode;
636
637   mapField["MeshVersionFormatted"] = 0; tabRef[0] = 0; tabDummy[0] = false;
638   mapField["Dimension"]            = 1; tabRef[1] = 0; tabDummy[1] = false;
639   mapField["Vertices"]             = 2; tabRef[2] = 3; tabDummy[2] = true;
640   mapField["Corners"]              = 3; tabRef[3] = 1; tabDummy[3] = false;
641   mapField["Edges"]                = 4; tabRef[4] = 2; tabDummy[4] = true;
642   mapField["Ridges"]               = 5; tabRef[5] = 1; tabDummy[5] = false;
643   mapField["Quadrilaterals"]       = 6; tabRef[6] = 4; tabDummy[6] = true;
644   mapField["Hexahedra"]            = 7; tabRef[7] = 8; tabDummy[7] = true;
645   mapField["End"]                  = 8; tabRef[8] = 0; tabDummy[8] = false;
646
647   {
648     // theMesh->Clear(); -- this does not remove imported mesh
649     SMDS_ElemIteratorPtr eIt = theMesh->elementsIterator();
650     while( eIt->more() )
651       theMesh->RemoveFreeElement( eIt->next(), /*sm=*/0 );
652     SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator();
653     while ( nIt->more() )
654       theMesh->RemoveFreeNode( nIt->next(), /*sm=*/0 );
655   }
656
657   int nbVertices = getNbShape(theFile, "Vertices");
658   HexoticNode = new SMDS_MeshNode*[ nbVertices + 1 ];
659   nodeAssigne = new int[ nbVertices + 1 ];
660
661   MESSAGE("Read " << theFile << " file");
662   std::ifstream fileRes(theFile.c_str());
663   ASSERT(fileRes);
664
665   while ( !EndOfFile  )
666   {
667     int dummy;
668     fileRes >> token;
669
670     if (mapField.count(token)) {
671       nField   = mapField[token];
672       nbRef    = tabRef[nField];
673       hasDummy = tabDummy[nField];
674     }
675     else {
676       nField = -1;
677       nbRef = 0;
678     }
679
680     nbElem = 0;
681     if ( nField < int(mapField.size() - 1) && nField >= 0 )
682       fileRes >> nbElem;
683
684     switch (nField) {
685     case 0: { // "MeshVersionFormatted"
686       MESSAGE(token << " " << nbElem);
687       break;
688     }
689     case 1: { // "Dimension"
690       MESSAGE("Mesh dimension " << nbElem << "D");
691       break;
692     }
693     case 2: { // "Vertices"
694       MESSAGE("Read " << nbElem << " " << token);
695       int aHexoticID;
696       double coord[3];
697       SMDS_MeshNode * aHexoticNode;
698
699       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
700         if(theAlgo->computeCanceled())
701           {
702             return false;
703           }
704         aHexoticID = iElem + 1;
705         for ( int iCoord = 0; iCoord < 3; iCoord++ )
706           fileRes >> coord[ iCoord ];
707         fileRes >> dummy;
708         aHexoticNode = theMesh->AddNode(coord[0], coord[1], coord[2]);
709         HexoticNode[ aHexoticID ] = aHexoticNode;
710         nodeAssigne[ aHexoticID ] = 0;
711       }
712       break;
713     }
714     case 3: // "Corners"
715     case 4: // "Edges"
716     case 5: // "Ridges"
717     case 6: // "Quadrilaterals"
718     case 7: { // "Hexahedra"
719       MESSAGE("Read " << nbElem << " " << token);
720       std::vector< SMDS_MeshNode* > node( nbRef );
721       std::vector< int >          nodeID( nbRef );
722
723       for ( int iElem = 0; iElem < nbElem; iElem++ )
724       {
725         if(theAlgo->computeCanceled())
726           {
727             return false;
728           }
729         for ( int iRef = 0; iRef < nbRef; iRef++ )
730         {
731           fileRes >> aHexoticNodeID;                          // read nbRef aHexoticNodeID
732           node  [ iRef ] = HexoticNode[ aHexoticNodeID ];
733           nodeID[ iRef ] = aHexoticNodeID;
734         }
735         if ( hasDummy )
736           fileRes >> dummy;
737         switch (nField)
738         {
739         case 4: // "Edges"
740           theHelper->AddEdge( node[0], node[1] ); break;
741         case 6:  // "Quadrilaterals"
742           theMesh->AddFace( node[0], node[1], node[2], node[3] ); break;
743         case 7: // "Hexahedra"
744           theHelper->AddVolume( node[0], node[3], node[2], node[1],
745                                 node[4], node[7], node[6], node[5] ); break;
746         default: continue;
747         }
748         if ( nField == 6 )
749           for ( int iRef = 0; iRef < nbRef; iRef++ )
750             nodeAssigne[ nodeID[ iRef ]] = 1;
751       }
752       break;
753     }
754     case 8: { // "End"
755       EndOfFile = 1;
756       MESSAGE("End of " << theFile << " file");
757       break;
758     }
759     default: {
760       MESSAGE("Unknown Token: " << token);
761     }
762     }
763   }
764   cout << std::endl;
765
766   shapeID = theHelper->GetSubShapeID();
767   for ( int i = 0; i < nbVertices; ++i )
768     if ( !nodeAssigne[ i+1 ])
769       theMesh->SetNodeInVolume( HexoticNode[ i+1 ], shapeID );
770
771   delete [] HexoticNode;
772   delete [] nodeAssigne;
773   return true;
774 }
775
776 //=============================================================================
777 /*!
778  * Pass parameters to MG-Hexa
779  */
780 //=============================================================================
781
782 void HexoticPlugin_Hexotic::SetParameters(const HexoticPlugin_Hypothesis* hyp) {
783
784   MESSAGE("HexoticPlugin_Hexotic::SetParameters");
785   if (hyp) {
786     _hexesMinLevel = hyp->GetHexesMinLevel();
787     _hexesMaxLevel = hyp->GetHexesMaxLevel();
788     _hexesMinSize = hyp->GetMinSize();
789     _hexesMaxSize = hyp->GetMaxSize();
790     _hexoticIgnoreRidges = hyp->GetHexoticIgnoreRidges();
791     _hexoticInvalidElements = hyp->GetHexoticInvalidElements();
792     _hexoticSharpAngleThreshold = hyp->GetHexoticSharpAngleThreshold();
793     _hexoticNbProc = hyp->GetHexoticNbProc();
794     _hexoticWorkingDirectory = hyp->GetHexoticWorkingDirectory();
795     _hexoticVerbosity = hyp->GetHexoticVerbosity();
796     _hexoticMaxMemory = hyp->GetHexoticMaxMemory();
797     _hexoticSdMode = hyp->GetHexoticSdMode();
798     _textOptions = hyp->GetTextOptions();
799     _sizeMaps = hyp->GetSizeMaps();
800     _nbLayers = hyp->GetNbLayers();
801     _firstLayerSize = hyp->GetFirstLayerSize();
802     _direction = hyp->GetDirection();
803     _growth = hyp->GetGrowth();
804     _facesWithLayers = hyp->GetFacesWithLayers();
805     _imprintedFaces = hyp->GetImprintedFaces();
806   }
807   else {
808     cout << std::endl;
809     cout << "WARNING : The MG-Hexa default parameters are taken into account" << std::endl;
810     cout << "=======" << std::endl;
811     _hexesMinLevel = hyp->GetDefaultHexesMinLevel();
812     _hexesMaxLevel = hyp->GetDefaultHexesMaxLevel();
813     _hexesMinSize = hyp->GetDefaultMinSize();
814     _hexesMaxSize = hyp->GetDefaultMaxSize();
815     _hexoticIgnoreRidges = hyp->GetDefaultHexoticIgnoreRidges();
816     _hexoticInvalidElements = hyp->GetDefaultHexoticInvalidElements();
817     _hexoticSharpAngleThreshold = hyp->GetDefaultHexoticSharpAngleThreshold();
818     _hexoticNbProc = hyp->GetDefaultHexoticNbProc();
819     _hexoticWorkingDirectory = hyp->GetDefaultHexoticWorkingDirectory();
820     _hexoticVerbosity = hyp->GetDefaultHexoticVerbosity();
821     _hexoticMaxMemory = hyp->GetDefaultHexoticMaxMemory();
822     _hexoticSdMode = hyp->GetDefaultHexoticSdMode();
823     _textOptions = hyp->GetDefaultTextOptions();
824     _sizeMaps = hyp->GetDefaultHexoticSizeMaps();
825     _nbLayers = hyp->GetDefaultNbLayers();
826     _firstLayerSize = hyp->GetDefaultFirstLayerSize();
827     _direction = hyp->GetDefaultDirection();
828     _growth = hyp->GetDefaultGrowth();
829     _facesWithLayers = hyp->GetDefaultFacesWithLayers();
830     _imprintedFaces = hyp->GetDefaultImprintedFaces();
831   }
832 }
833
834 //=======================================================================
835 //function : getTmpDir
836 //purpose  :
837 //=======================================================================
838
839 // static TCollection_AsciiString getTmpDir()
840 // {
841 //   TCollection_AsciiString aTmpDir;
842
843 //   char *Tmp_dir = getenv("SALOME_TMP_DIR");
844 // #ifdef WIN32
845 //   if(Tmp_dir == NULL) {
846 //     Tmp_dir = getenv("TEMP");
847 //     if( Tmp_dir== NULL )
848 //       Tmp_dir = getenv("TMP");
849 //   }
850 // #endif
851
852 //   if(Tmp_dir != NULL) {
853 //     aTmpDir = Tmp_dir;
854 // #ifdef WIN32
855 //     if(aTmpDir.Value(aTmpDir.Length()) != '\\') aTmpDir+='\\';
856 // #else
857 //     if(aTmpDir.Value(aTmpDir.Length()) != '/') aTmpDir+='/';
858 // #endif
859 //   }
860 //   else {
861 // #ifdef WIN32
862 //     aTmpDir = TCollection_AsciiString("C:\\");
863 // #else
864 //     aTmpDir = TCollection_AsciiString("/tmp/");
865 // #endif
866 //   }
867 //   return aTmpDir;
868 // }
869
870 //=======================================================================
871 //function : getSuffix
872 //purpose  : Returns a suffix that will be unique for the current process
873 //=======================================================================
874
875 static TCollection_AsciiString getSuffix()
876 {
877   TCollection_AsciiString aSuffix = "";
878   aSuffix += "_";
879 #ifndef WIN32
880   aSuffix += getenv("USER");
881 #else
882   aSuffix += getenv("USERNAME");
883 #endif
884   aSuffix += "_";
885   aSuffix += Kernel_Utils::GetHostname().c_str();
886   aSuffix += "_";
887 #ifndef WIN32
888   aSuffix += getpid();
889 #else
890   aSuffix += _getpid();
891 #endif
892
893   return aSuffix;
894 }
895
896 //================================================================================
897 /*!
898  * \brief Returns a command to run MG-Hexa mesher
899  */
900 //================================================================================
901
902 std::string HexoticPlugin_Hexotic::getHexoticCommand(const TCollection_AsciiString& Hexotic_In,
903                                                      const TCollection_AsciiString& Hexotic_Out,
904                                                      const TCollection_AsciiString& Hexotic_SizeMap_Prefix) const
905 {
906   cout << std::endl;
907   cout << "MG-Hexa execution..." << std::endl;
908   cout << _name << " parameters :" << std::endl;
909   cout << "    " << _name << " Verbosity = " << _hexoticVerbosity << std::endl;
910   cout << "    " << _name << " Max Memory = " << _hexoticMaxMemory << std::endl;
911   cout << "    " << _name << " Segments Min Level = " << _hexesMinLevel << std::endl;
912   cout << "    " << _name << " Segments Max Level = " << _hexesMaxLevel << std::endl;
913   cout << "    " << _name << " Segments Min Size = " << _hexesMinSize << std::endl;
914   cout << "    " << _name << " Segments Max Size = " << _hexesMaxSize << std::endl;
915   cout << "    " << "MG-Hexa can ignore ridges : " << (_hexoticIgnoreRidges ? "yes":"no") << std::endl;
916   cout << "    " << "MG-Hexa authorize invalide elements : " << ( _hexoticInvalidElements ? "yes":"no") << std::endl;
917   cout << "    " << _name << " Sharp angle threshold = " << _hexoticSharpAngleThreshold << " degrees" << std::endl;
918   cout << "    " << _name << " Number of threads = " << _hexoticNbProc << std::endl;
919   cout << "    " << _name << " Working directory = \"" << _hexoticWorkingDirectory << "\"" << std::endl;
920   cout << "    " << _name << " Sub. Dom mode = " << _hexoticSdMode << std::endl;
921   cout << "    " << _name << " Text options = \"" << _textOptions << "\"" << std::endl;
922   cout << "    " << _name << " Number of layers = " << _nbLayers << std::endl;
923   cout << "    " << _name << " Size of the first layer  = " << _firstLayerSize << std::endl;
924   cout << "    " << _name << " Direction of the layers = " << ( _direction ? "Inward" : "Outward" ) << std::endl;
925   cout << "    " << _name << " Growth = " << _growth << std::endl;
926   if (!_facesWithLayers.empty()) {
927     cout << "    " << _name << " Faces with layers = ";
928     for (size_t i = 0; i < _facesWithLayers.size(); i++)
929     {
930       cout << _facesWithLayers.at(i);
931       if ((i + 1) != _facesWithLayers.size())
932         cout << ", ";
933     }
934     cout << std::endl;
935   }
936   if (!_imprintedFaces.empty()) {
937     cout << "    " << _name << " Imprinted faces = ";
938     for (size_t i = 0; i < _imprintedFaces.size(); i++)
939     {
940       cout << _imprintedFaces.at(i);
941       if ((i + 1) != _imprintedFaces.size())
942         cout << ", ";
943     }
944     cout << std::endl;
945   }
946
947   TCollection_AsciiString run_Hexotic( "mg-hexa.exe" );
948
949   TCollection_AsciiString minl = " --min_level ", maxl = " --max_level ", angle = " --ridge_angle ";
950   TCollection_AsciiString mins = " --min_size ", maxs = " --max_size ";
951   TCollection_AsciiString in   = " --in ",   out  = " --out ";
952   TCollection_AsciiString sizeMap = " --read_sizemap ";
953   TCollection_AsciiString ignoreRidges = " --compute_ridges no ", invalideElements = " --allow_invalid_elements yes ";
954   TCollection_AsciiString subdom = " --components ";
955 #ifndef WIN32
956   TCollection_AsciiString proc = " --max_number_of_threads ";
957 #endif
958   TCollection_AsciiString verb = " --verbose ";
959   TCollection_AsciiString maxmem = " --max_memory ";
960
961   TCollection_AsciiString comNbLayers = " --number_of_boundary_layers ";
962   TCollection_AsciiString comFirstLayerSize = " --height_of_the_first_layer ";
963   TCollection_AsciiString comDirection = " --boundary_layers_subdomain_direction ";
964   TCollection_AsciiString comGrowth = " --boundary_layers_geometric_progression ";
965   TCollection_AsciiString comFacesWithLayers = " --boundary_layers_surface_ids ";
966   TCollection_AsciiString comImptintedFaces = " --imprinted_surface_ids ";
967
968   TCollection_AsciiString minLevel, maxLevel, minSize, maxSize, sharpAngle, mode, nbproc, verbosity, maxMemory,
969                           textOptions, nbLayers, firstLayerSize, direction, growth, facesWithLayers, imprintedFaces;
970   minLevel = _hexesMinLevel;
971   maxLevel = _hexesMaxLevel;
972   minSize = _hexesMinSize;
973   maxSize = _hexesMaxSize;
974   sharpAngle = _hexoticSharpAngleThreshold;
975   // Mode translation for mg-tetra 1.1
976   switch ( _hexoticSdMode )
977   {
978     case 1:
979       mode = "outside_skin_only";
980       break;
981     case 2:
982       mode = "outside_components";
983       break;
984     case 3:
985       mode = "all";
986       break;
987     case 4:
988       mode = "all --manifold_geometry no";
989       break;
990   }
991   nbproc = _hexoticNbProc;
992   verbosity = _hexoticVerbosity;
993   maxMemory = _hexoticMaxMemory;
994   textOptions = (" " + _textOptions + " ").c_str();
995   nbLayers = _nbLayers;
996   firstLayerSize = _firstLayerSize;
997   direction = _direction ? "1" : "-1";
998   growth = _growth;
999   for (size_t i = 0; i < _facesWithLayers.size(); i++)
1000   {
1001     facesWithLayers += _facesWithLayers[i];
1002     if ((i + 1) != _facesWithLayers.size())
1003       facesWithLayers += ",";
1004   }
1005   for (size_t i = 0; i < _imprintedFaces.size(); i++)
1006   {
1007     imprintedFaces += _imprintedFaces[i];
1008     if ((i + 1) != _imprintedFaces.size())
1009       imprintedFaces += ",";
1010   }
1011
1012   if (_hexoticIgnoreRidges)
1013     run_Hexotic +=  ignoreRidges;
1014
1015   if (_hexoticInvalidElements)
1016     run_Hexotic +=  invalideElements;
1017
1018   if (_hexesMinSize > 0)
1019     run_Hexotic +=  mins + minSize;
1020
1021   if (_hexesMaxSize > 0)
1022     run_Hexotic +=  maxs + maxSize;
1023
1024   if (_hexesMinLevel > 0)
1025     run_Hexotic +=  minl + minLevel;
1026
1027   if (_hexesMaxLevel > 0)
1028     run_Hexotic +=  maxl + maxLevel;
1029
1030   if (_hexoticSharpAngleThreshold > 0)
1031     run_Hexotic +=  angle + sharpAngle;
1032   
1033   if (_sizeMaps.begin() != _sizeMaps.end())
1034     run_Hexotic += sizeMap + Hexotic_SizeMap_Prefix;
1035
1036   if (_nbLayers       > 0 &&
1037       _firstLayerSize > 0 &&
1038       _growth         > 0 &&
1039       !_facesWithLayers.empty())
1040   {
1041     run_Hexotic += comNbLayers + nbLayers;
1042     run_Hexotic += comFirstLayerSize + firstLayerSize;
1043     run_Hexotic += comDirection + direction;
1044     run_Hexotic += comGrowth + growth;
1045     run_Hexotic += comFacesWithLayers + facesWithLayers;
1046     if (!_imprintedFaces.empty())
1047       run_Hexotic += comImptintedFaces + imprintedFaces;
1048   }
1049   run_Hexotic += in + Hexotic_In + out + Hexotic_Out;
1050   run_Hexotic += subdom + mode;
1051 #ifndef WIN32
1052   run_Hexotic += proc + nbproc;
1053 #endif
1054   run_Hexotic += verb + verbosity;
1055   run_Hexotic += maxmem + maxMemory;
1056
1057   if (!_textOptions.empty())
1058     run_Hexotic += textOptions;
1059
1060   return run_Hexotic.ToCString();
1061 }
1062
1063 // TODO : this is a duplication of some code found in BLSURFPlugin_BLSURF find a proper
1064 // way to share it
1065 TopoDS_Shape HexoticPlugin_Hexotic::entryToShape(std::string entry)
1066 {
1067   MESSAGE("HexoticPlugin_Hexotic::entryToShape "<<entry );
1068   GEOM::GEOM_Object_var aGeomObj;
1069   TopoDS_Shape S = TopoDS_Shape();
1070   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
1071   if (!aSObj->_is_nil()) {
1072     CORBA::Object_var obj = aSObj->GetObject();
1073     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
1074     aSObj->UnRegister();
1075   }
1076   if ( !aGeomObj->_is_nil() )
1077     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
1078   return S;
1079 }
1080
1081 //================================================================================
1082 /*!
1083  * \brief Produces a .mesh file with the size maps informations to give to Hexotic
1084  */
1085 //================================================================================
1086 std::vector<std::string> HexoticPlugin_Hexotic::writeSizeMapFile( std::string sizeMapPrefix )
1087 {
1088   HexoticPlugin_Hypothesis::THexoticSizeMaps::iterator it ;
1089   
1090   // The GMF driver will be used to write the size map file
1091   DriverGMF_Write aWriter;
1092   aWriter.SetSizeMapPrefix( sizeMapPrefix ); 
1093   
1094   std::vector<Control_Pnt> points;
1095   // Iterate on the size maps
1096   for (it=_sizeMaps.begin(); it!=_sizeMaps.end(); it++)
1097   {
1098     // Step 1 : Get the GEOM object entry and the size 
1099     // from the _sizeMaps infos
1100     std::string anEntry = it->first;
1101     double aLocalSize = it->second;
1102     TopoDS_Shape aShape = entryToShape( anEntry );
1103     
1104     // Step 2 : Create the points
1105     createControlPoints( aShape, aLocalSize, points );
1106   }
1107   // Write the .mesh size map file
1108   aWriter.PerformSizeMap(points); 
1109   return aWriter.GetSizeMapFiles();
1110 }
1111
1112 //================================================================================
1113 /*!
1114  * \brief Fills a vector of points from which a size map input file can be written
1115  */
1116 //================================================================================
1117 void HexoticPlugin_Hexotic::createControlPoints( const TopoDS_Shape& aShape, 
1118                                                  const double& theSize, 
1119                                                  std::vector<Control_Pnt>& thePoints )
1120
1121   if ( aShape.ShapeType() == TopAbs_VERTEX )
1122   {
1123     gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex(aShape) );
1124     Control_Pnt aControl_Pnt( aPnt, theSize );
1125     thePoints.push_back( aControl_Pnt );
1126   }
1127   if ( aShape.ShapeType() == TopAbs_EDGE )
1128   {
1129     createPointsSampleFromEdge( aShape, theSize, thePoints );  
1130   }
1131   else if ( aShape.ShapeType() == TopAbs_WIRE )
1132   {
1133     TopExp_Explorer Ex;
1134     for (Ex.Init(aShape,TopAbs_EDGE); Ex.More(); Ex.Next()) 
1135     {
1136       createPointsSampleFromEdge( Ex.Current(), theSize, thePoints );
1137     } 
1138   }
1139   else if ( aShape.ShapeType() ==  TopAbs_FACE )
1140   {
1141     createPointsSampleFromFace( aShape, theSize, thePoints ); 
1142   }
1143   else if ( aShape.ShapeType() ==  TopAbs_SOLID )
1144   {
1145     createPointsSampleFromSolid( aShape, theSize, thePoints ); 
1146   }
1147   else if ( aShape.ShapeType() == TopAbs_COMPOUND )
1148   {
1149     TopoDS_Iterator it( aShape );
1150     for(; it.More(); it.Next())
1151     {
1152       createControlPoints( it.Value(), theSize, thePoints );
1153     }
1154   }
1155 }
1156
1157 //================================================================================
1158 /*!
1159  * \brief Fills a vector of points with point samples approximately 
1160  * \brief spaced with a given size
1161  */
1162 //================================================================================
1163 void HexoticPlugin_Hexotic::createPointsSampleFromEdge( const TopoDS_Shape& aShape, 
1164                                                         const double& theSize, 
1165                                                         std::vector<Control_Pnt>& thePoints )
1166 {
1167   double step = theSize;
1168   double first, last;  
1169   Handle( Geom_Curve ) aCurve = BRep_Tool::Curve( TopoDS::Edge( aShape ), first, last );
1170   GeomAdaptor_Curve C ( aCurve );
1171   GCPnts_UniformAbscissa DiscretisationAlgo(C, step , first, last, Precision::Confusion());
1172   int nbPoints = DiscretisationAlgo.NbPoints();
1173   
1174   for ( int i = 1; i <= nbPoints; i++ )
1175   {
1176     double param = DiscretisationAlgo.Parameter( i );
1177     Control_Pnt aPnt;
1178     aCurve->D0( param, aPnt );
1179     aPnt.SetSize(theSize);
1180     thePoints.push_back( aPnt );
1181   }  
1182 }
1183
1184 //================================================================================
1185 /*!
1186  * \brief Fills a vector of points with point samples approximately 
1187  * \brief spaced with a given size
1188  */
1189 //================================================================================
1190 void HexoticPlugin_Hexotic::createPointsSampleFromFace( const TopoDS_Shape& aShape, 
1191                                                         const double& theSize, 
1192                                                         std::vector<Control_Pnt>& thePoints )
1193 {
1194   BRepMesh_IncrementalMesh M(aShape, 0.01, Standard_True);
1195   TopLoc_Location aLocation;
1196   TopoDS_Face aFace = TopoDS::Face(aShape);
1197
1198   // Triangulate the face
1199   Handle(Poly_Triangulation) aTri = BRep_Tool::Triangulation (aFace, aLocation);
1200   
1201   // Get the transformation associated to the face location
1202   gp_Trsf aTrsf = aLocation.Transformation();
1203   
1204   // Get triangles
1205   int nbTriangles = aTri->NbTriangles();
1206   Poly_Array1OfTriangle triangles(1,nbTriangles);
1207   triangles=aTri->Triangles();
1208   
1209   // GetNodes
1210   int nbNodes = aTri->NbNodes();
1211   TColgp_Array1OfPnt nodes(1,nbNodes);
1212   nodes = aTri->Nodes();
1213
1214   // Iterate on triangles and subdivide them
1215   for(int i=1; i<=nbTriangles; i++)
1216   {
1217      Poly_Triangle aTriangle = triangles.Value(i);
1218      gp_Pnt p1 = nodes.Value(aTriangle.Value(1));
1219      gp_Pnt p2 = nodes.Value(aTriangle.Value(2));
1220      gp_Pnt p3 = nodes.Value(aTriangle.Value(3));
1221      
1222      p1.Transform(aTrsf);
1223      p2.Transform(aTrsf);
1224      p3.Transform(aTrsf);
1225      
1226      subdivideTriangle(p1, p2, p3, theSize, thePoints);  
1227   }
1228 }
1229
1230 //================================================================================
1231 /*!
1232  * \brief Fills a vector of points with point samples approximately 
1233  * \brief spaced with a given size
1234  */
1235 //================================================================================
1236 void HexoticPlugin_Hexotic::createPointsSampleFromSolid( const TopoDS_Shape& aShape, 
1237                                                          const double& theSize, 
1238                                                          std::vector<Control_Pnt>& thePoints )
1239 {
1240   // Compute the bounding box
1241   double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1242   Bnd_Box B;               
1243   BRepBndLib::Add(aShape, B);
1244   B.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1245   
1246   // Create the points
1247   double step = theSize;
1248   
1249   for ( double x=Xmin; x-Xmax<Precision::Confusion(); x=x+step )
1250   {
1251     for ( double y=Ymin; y-Ymax<Precision::Confusion(); y=y+step )
1252     {
1253       // Step1 : generate the Zmin -> Zmax line
1254       gp_Pnt startPnt(x, y, Zmin);
1255       gp_Pnt endPnt(x, y, Zmax);
1256       gp_Vec aVec(startPnt, endPnt);
1257       gp_Lin aLine(startPnt, aVec);
1258       double endParam = Zmax - Zmin;
1259       
1260       // Step2 : for each face of aShape:
1261       std::set<double> intersections;
1262       std::set<double>::iterator it = intersections.begin();
1263       
1264       TopExp_Explorer Ex;
1265       for (Ex.Init(aShape,TopAbs_FACE); Ex.More(); Ex.Next()) 
1266       { 
1267         // check if there is an intersection
1268         IntCurvesFace_Intersector anIntersector(TopoDS::Face(Ex.Current()), Precision::Confusion());
1269         anIntersector.Perform(aLine, 0, endParam);
1270         
1271         // get the intersection's parameter and store it
1272         int nbPoints = anIntersector.NbPnt();
1273         for(int i = 0 ; i < nbPoints ; i++ )
1274         {
1275           it = intersections.insert( it, anIntersector.WParameter(i+1) );
1276         }
1277       }
1278       // Step3 : go through the line chunk by chunk 
1279       if ( intersections.begin() != intersections.end() )
1280       {
1281         std::set<double>::iterator intersectionsIterator=intersections.begin();
1282         double first = *intersectionsIterator;
1283         intersectionsIterator++;
1284         bool innerPoints = true; 
1285         for ( ; intersectionsIterator!=intersections.end() ; intersectionsIterator++ )
1286         {
1287           double second = *intersectionsIterator;
1288           if ( innerPoints )
1289           {
1290             // If the last chunk was outside of the shape or this is the first chunk
1291             // add the points in the range [first, second] to the points vector
1292             double localStep = (second -first) / ceil( (second - first) / step );
1293             for ( double z = Zmin + first; z < Zmin + second; z = z + localStep )
1294             {
1295               thePoints.push_back(Control_Pnt( x, y, z, theSize ));
1296             }
1297             thePoints.push_back(Control_Pnt( x, y, Zmin + second, theSize ));
1298           }
1299           first = second;
1300           innerPoints = !innerPoints;
1301         }
1302       }
1303     }
1304   }
1305 }
1306
1307 //================================================================================
1308 /*!
1309  * \brief Subdivides a triangle until it reaches a certain size (recursive function)
1310  */
1311 //================================================================================
1312 void HexoticPlugin_Hexotic::subdivideTriangle( const gp_Pnt& p1, 
1313                                                const gp_Pnt& p2, 
1314                                                const gp_Pnt& p3, 
1315                                                const double& theSize, 
1316                                                std::vector<Control_Pnt>& thePoints)
1317 {
1318   // Size threshold to stop subdividing
1319   // This value ensures that two control points are distant no more than 2*theSize
1320   // as shown below
1321   //
1322   // The greater distance D of the mass center M to each Edge is 1/3 * Median 
1323   // and Median < sqrt(3/4) * a  where a is the greater side (by using Apollonius' thorem). 
1324   // So D < 1/3 * sqrt(3/4) * a and if a < sqrt(3) * S then D < S/2
1325   // and the distance between two mass centers of two neighbouring triangles 
1326   // sharing an edge is < 2 * 1/2 * S = S
1327   // If the traingles share a Vertex and no Edge the distance of the mass centers 
1328   // to the Vertices is 2*D < S so the mass centers are distant of less than 2*S 
1329   
1330   double threshold = sqrt( 3. ) * theSize;
1331   
1332   if ( (p1.Distance(p2) > threshold ||
1333         p2.Distance(p3) > threshold ||
1334         p3.Distance(p1) > threshold))
1335   { 
1336     std::vector<gp_Pnt> midPoints = computePointsForSplitting(p1, p2, p3);
1337  
1338     subdivideTriangle( midPoints[0], midPoints[1], midPoints[2], theSize, thePoints );
1339     subdivideTriangle( midPoints[0], p2, midPoints[1], theSize, thePoints );
1340     subdivideTriangle( midPoints[2], midPoints[1], p3, theSize, thePoints );
1341     subdivideTriangle( p1, midPoints[0], midPoints[2], theSize, thePoints );
1342   }
1343   else
1344   {
1345     double x = (p1.X() + p2.X() + p3.X()) / 3 ;
1346     double y = (p1.Y() + p2.Y() + p3.Y()) / 3 ;
1347     double z = (p1.Z() + p2.Z() + p3.Z()) / 3 ;
1348     
1349     Control_Pnt massCenter( x ,y ,z, theSize );
1350     thePoints.push_back( massCenter );
1351   }
1352 }
1353
1354 //================================================================================
1355 /*!
1356  * \brief Returns the appropriate points for splitting a triangle
1357  * \brief the tangency points of the incircle are used in order to have mostly
1358  * \brief well-shaped sub-triangles
1359  */
1360 //================================================================================
1361 std::vector<gp_Pnt> HexoticPlugin_Hexotic::computePointsForSplitting( const gp_Pnt& p1, 
1362                                                                       const gp_Pnt& p2, 
1363                                                                       const gp_Pnt& p3 )
1364 {
1365   std::vector<gp_Pnt> midPoints;
1366   //Change coordinates
1367   gp_Trsf Trsf_1;            // Identity transformation
1368   gp_Ax3 reference_system(gp::Origin(), gp::DZ(), gp::DX());   // OXY
1369  
1370   gp_Vec Vx(p1, p3);
1371   gp_Vec Vaux(p1, p2);
1372   gp_Dir Dx(Vx);
1373   gp_Dir Daux(Vaux);
1374   gp_Dir Dz = Dx.Crossed(Daux);
1375   gp_Ax3 current_system(p1, Dz, Dx);
1376   
1377   Trsf_1.SetTransformation( reference_system, current_system );
1378   
1379   gp_Pnt A = p1.Transformed(Trsf_1);
1380   gp_Pnt B = p2.Transformed(Trsf_1);
1381   gp_Pnt C = p3.Transformed(Trsf_1);
1382   
1383   double a =  B.Distance(C) ;
1384   double b =  A.Distance(C) ;
1385   double c =  B.Distance(A) ;
1386   
1387   // Incenter coordinates
1388   // see http://mathworld.wolfram.com/Incenter.html
1389   double Xi = ( b*B.X() + c*C.X() ) / ( a + b + c );
1390   double Yi = ( b*B.Y() ) / ( a + b + c );
1391   gp_Pnt Center(Xi, Yi, 0);
1392   
1393   // Calculate the tangency points of the incircle
1394   gp_Pnt T1 = tangencyPoint( A, B, Center);
1395   gp_Pnt T2 = tangencyPoint( B, C, Center);
1396   gp_Pnt T3 = tangencyPoint( C, A, Center);
1397   
1398   gp_Pnt p1_2 = T1.Transformed(Trsf_1.Inverted());
1399   gp_Pnt p2_3 = T2.Transformed(Trsf_1.Inverted());
1400   gp_Pnt p3_1 = T3.Transformed(Trsf_1.Inverted());
1401
1402   midPoints.push_back(p1_2);
1403   midPoints.push_back(p2_3);
1404   midPoints.push_back(p3_1);
1405   
1406   return midPoints;
1407 }
1408
1409 //================================================================================
1410 /*!
1411  * \brief Computes the tangency points of the circle of center Center with
1412  * \brief the straight line (p1 p2)
1413  */
1414 //================================================================================
1415 gp_Pnt HexoticPlugin_Hexotic::tangencyPoint(const gp_Pnt& p1,
1416                                             const gp_Pnt& p2,
1417                                             const gp_Pnt& Center)
1418 {
1419   double Xt = 0;
1420   double Yt = 0;
1421   
1422   // The tangency point is the intersection of the straight line (p1 p2)
1423   // and the straight line (Center T) which is orthogonal to (p1 p2)
1424   if ( fabs(p1.X() - p2.X()) <= Precision::Confusion() )
1425   {
1426     Xt=p1.X();     // T is on (p1 p2)
1427     Yt=Center.Y(); // (Center T) is orthogonal to (p1 p2)
1428   }
1429   else if ( fabs(p1.Y() - p2.Y()) <= Precision::Confusion() )
1430   {
1431     Yt=p1.Y();     // T is on (p1 p2) 
1432     Xt=Center.X(); // (Center T) is orthogonal to (p1 p2)
1433   }
1434   else
1435   {
1436     // First straight line coefficients (equation y=a*x+b)
1437     double a = (p2.Y() - p1.Y()) / (p2.X() - p1.X())  ;
1438     double b = p1.Y() - a*p1.X();         // p1 is on this straight line
1439     
1440     // Second straight line coefficients (equation y=c*x+d)
1441     double c = -1 / a;                    // The 2 lines are orthogonal
1442     double d = Center.Y() - c*Center.X(); // Center is on this straight line
1443     
1444     Xt = (d - b) / (a - c);
1445     Yt = a*Xt + b;
1446   }
1447   
1448   return gp_Pnt( Xt, Yt, 0 );
1449 }
1450
1451 //=============================================================================
1452 /*!
1453  * Here we are going to use the MG-Hexa mesher
1454  */
1455 //=============================================================================
1456
1457 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh&          aMesh,
1458                                     const TopoDS_Shape& aShape)
1459 {
1460   _compute_canceled = false;
1461   bool Ok = true;
1462   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1463   TCollection_AsciiString hexahedraMessage;
1464
1465   if (_iShape == 0 && _nbShape == 0) {
1466     _nbShape = countShape( meshDS, TopAbs_SOLID );  // we count the number of shapes
1467   }
1468
1469   // to prevent from displaying error message after computing,
1470   // SetIsAlwaysComputed( true ) to empty sub-meshes
1471   std::vector< SMESH_subMesh* > subMeshesAlwaysComp;
1472   for ( int i = 0; i < _nbShape; ++i )
1473     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( aShape ))
1474     {
1475       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true,
1476                                                                /*complexShapeFirst=*/false);
1477       while ( smIt->more() )
1478       {
1479         sm = smIt->next();
1480         if ( !sm->IsMeshComputed() )
1481         {
1482           sm->SetIsAlwaysComputed( true );
1483           subMeshesAlwaysComp.push_back( sm );
1484         }
1485       }
1486     }
1487
1488   _iShape++;
1489
1490   if (_iShape == _nbShape ) {
1491
1492     // create bounding box for each shape of the compound
1493
1494     int iShape = 0;
1495     TopoDS_Shape *tabShape;
1496     double **tabBox;
1497
1498     tabShape = new TopoDS_Shape[_nbShape];
1499     tabBox   = new double*[_nbShape];
1500     for (int i=0; i<_nbShape; i++)
1501       tabBox[i] = new double[6];
1502     double Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1503
1504     TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1505     for (; expBox.More(); expBox.Next()) {
1506       tabShape[iShape] = expBox.Current();
1507       Bnd_Box BoundingBox;
1508       BRepBndLib::Add(expBox.Current(), BoundingBox);
1509       BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1510       tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1511       tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1512       tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1513       iShape++;
1514     }
1515
1516     SetParameters(_hypothesis);
1517
1518 //     TCollection_AsciiString aTmpDir = getTmpDir();
1519     TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();
1520 #ifdef WIN32
1521     if ( aTmpDir.Value(aTmpDir.Length()) != '\\' ) aTmpDir += '\\';
1522 #else
1523     if ( aTmpDir.Value(aTmpDir.Length()) != '/' ) aTmpDir += '/';
1524 #endif
1525     TCollection_AsciiString Hexotic_In(""), Hexotic_Out, Hexotic_SizeMap_Prefix;
1526     TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );    TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
1527
1528     std::map <int,int> aSmdsToHexoticIdMap;
1529     std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1530
1531     Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1532 #ifdef WITH_BLSURFPLUGIN
1533     bool defaultInputFile = true;
1534     if (_blsurfHypo && !_blsurfHypo->GetQuadAllowed()) {
1535       Hexotic_In = _blsurfHypo->GetGMFFile().c_str();
1536       if ( !Hexotic_In.IsEmpty() &&
1537            SMESH_File( _blsurfHypo->GetGMFFile() ).exists() )
1538         defaultInputFile = false;
1539     }
1540     if (defaultInputFile) {
1541 #endif
1542       Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1543       removeHexoticFiles(Hexotic_In, Hexotic_Out);
1544       splitQuads(aMesh); // quadrangles are no longer acceptable as input
1545       cout << std::endl;
1546       cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1547       aMesh.ExportGMF(Hexotic_In.ToCString(), meshDS, true);
1548 #ifdef WITH_BLSURFPLUGIN
1549     }
1550     else {
1551       removeFile( Hexotic_Out );
1552     }
1553 #endif
1554     
1555     Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap" + getSuffix();
1556     std::vector<std::string> sizeMapFiles = writeSizeMapFile( Hexotic_SizeMap_Prefix.ToCString() );
1557     
1558     std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix);
1559     run_Hexotic += std::string(" 1> ") + aLogFileName.ToCString();  // dump into file
1560
1561     cout << std::endl;
1562     cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1563
1564 #ifndef WIN32    
1565     modeFile_In += Hexotic_In;
1566     system( modeFile_In.ToCString() );
1567 #endif
1568     aSmdsToHexoticIdMap.clear();
1569     aHexoticIdToNodeMap.clear();
1570
1571     MESSAGE("HexoticPlugin_Hexotic::Compute");
1572
1573     int status = system( run_Hexotic.data() );
1574
1575     // --------------
1576     // read a result
1577     // --------------
1578
1579     std::ifstream fileRes( Hexotic_Out.ToCString() );
1580 #ifndef WIN32  
1581     modeFile_Out += Hexotic_Out;
1582     system( modeFile_Out.ToCString() );
1583 #endif
1584     if ( ! fileRes.fail() ) {
1585       Ok = readResult( Hexotic_Out.ToCString(),
1586                        this,
1587                        meshDS, _nbShape, tabShape, tabBox );
1588       if(Ok) {
1589 /*********************
1590 // TODO: Detect and remove elements in holes in case of sd mode = 4
1591       // Remove previous nodes and elements
1592       SMDS_ElemIteratorPtr itElement = meshDS->elementsIterator();
1593       SMDS_NodeIteratorPtr itNode = meshDS->nodesIterator();
1594     
1595       while ( itElement->more() )
1596         meshDS->RemoveElement( itElement->next() );
1597       while ( itNode->more() )
1598         meshDS->RemoveNode( itNode->next() );
1599   
1600       SMESH_ComputeErrorPtr myError = aMesh.GMFToMesh(Hexotic_Out.ToCString());
1601       if (myError)
1602 */
1603         hexahedraMessage = "success";
1604         #ifndef _DEBUG_
1605         removeFile(Hexotic_Out);
1606         removeFile(Hexotic_In);
1607         removeFile(aLogFileName);
1608         for( int i=0; i<sizeMapFiles.size(); i++)
1609         {
1610           removeFile( TCollection_AsciiString( sizeMapFiles[i].c_str() ) );
1611         }
1612         #endif
1613       }
1614       else {
1615         hexahedraMessage = "failed"; 
1616       }
1617     }
1618     else {
1619       hexahedraMessage = "failed";
1620       cout << "Problem with MG-Hexa output file " << Hexotic_Out.ToCString() << std::endl;
1621       Ok = false;
1622       // analyse log file
1623       SMESH_File logFile( aLogFileName.ToCString() );
1624       if ( !logFile.eof() )
1625       {
1626         char msgLic[] = " Dlim ";
1627         const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
1628         if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1629           error("Licence problems.");
1630       }
1631 #ifndef WIN32
1632       if ( status > 0 && WEXITSTATUS(status) == 127 )
1633         error("mg-hexa.exe: command not found");
1634 #else
1635       int err = errno;
1636       if ( status == 0 && err == ENOENT ) {
1637         error("mg-hexa.exe: command not found");
1638       }
1639 #endif
1640     }
1641     cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1642     cout << std::endl;
1643
1644     // restore "always computed" flag of sub-meshes (0022127)
1645     for  ( size_t iSM = 0; iSM < subMeshesAlwaysComp.size(); ++iSM )
1646       subMeshesAlwaysComp[ iSM ]->SetIsAlwaysComputed( false );
1647
1648     delete [] tabShape;
1649     for (int i=0; i<_nbShape; i++)
1650       delete [] tabBox[i];
1651     delete [] tabBox;
1652     _nbShape = 0;
1653     _iShape  = 0;
1654   }
1655   if(_compute_canceled)
1656     return error(SMESH_Comment("interruption initiated by user"));
1657   return Ok;
1658 }
1659
1660 //=============================================================================
1661 /*!
1662  * \brief Computes mesh without geometry
1663  *  \param aMesh - the mesh
1664  *  \param aHelper - helper that must be used for adding elements to \aaMesh
1665  *  \retval bool - is a success
1666  *
1667  * The method is called if ( !aMesh->HasShapeToMesh() )
1668  */
1669 //=============================================================================
1670
1671 bool HexoticPlugin_Hexotic::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
1672 {
1673   _compute_canceled = false;
1674 /*
1675   SMESH_ComputeErrorPtr myError = SMESH_ComputeError::New();
1676 */
1677   bool Ok = true;
1678   TCollection_AsciiString hexahedraMessage;
1679
1680   SetParameters(_hypothesis);
1681
1682   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str();//getTmpDir();
1683   TCollection_AsciiString Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix;
1684   TCollection_AsciiString modeFile_In( "chmod 666 " ), modeFile_Out( "chmod 666 " );
1685   TCollection_AsciiString aLogFileName = aTmpDir + "Hexotic"+getSuffix()+".log";    // log
1686
1687   std::map <int,int> aSmdsToHexoticIdMap;
1688   std::map <int,const SMDS_MeshNode*> aHexoticIdToNodeMap;
1689
1690   Hexotic_In  = aTmpDir + "Hexotic"+getSuffix()+"_In.mesh";
1691   Hexotic_Out = aTmpDir + "Hexotic"+getSuffix()+"_Out.mesh";
1692   Hexotic_SizeMap_Prefix = aTmpDir + "Hexotic_SizeMap";
1693  
1694   
1695   std::vector<std::string> sizeMapFiles = writeSizeMapFile( Hexotic_SizeMap_Prefix.ToCString() );
1696
1697   std::string run_Hexotic = getHexoticCommand(Hexotic_In, Hexotic_Out, Hexotic_SizeMap_Prefix);
1698   run_Hexotic += std::string(" 1> ") + aLogFileName.ToCString();  // dump into file
1699
1700   removeHexoticFiles(Hexotic_In, Hexotic_Out);
1701
1702   splitQuads(aMesh); // quadrangles are no longer acceptable as input
1703
1704   cout << std::endl;
1705   cout << "Creating MG-Hexa input mesh file : " << Hexotic_In << std::endl;
1706   aMesh.ExportGMF(Hexotic_In.ToCString(), aHelper->GetMeshDS());
1707 #ifndef WIN32    
1708   modeFile_In += Hexotic_In;
1709   system( modeFile_In.ToCString() );
1710 #endif
1711   aSmdsToHexoticIdMap.clear();
1712   aHexoticIdToNodeMap.clear();
1713
1714   MESSAGE("HexoticPlugin_Hexotic::Compute");
1715
1716   cout << std::endl;
1717   cout << "MG-Hexa command : " << run_Hexotic << std::endl;
1718   system( run_Hexotic.data() );
1719
1720   // --------------
1721   // read a result
1722   // --------------
1723
1724   std::ifstream fileRes( Hexotic_Out.ToCString() );
1725   modeFile_Out += Hexotic_Out;
1726   system( modeFile_Out.ToCString() );
1727   if ( ! fileRes.fail() ) {
1728     Ok = readResult( Hexotic_Out.ToCString(),
1729                      this,
1730                      aHelper );
1731     if(Ok)
1732 /*
1733     // Remove previous nodes and elements
1734     SMDS_ElemIteratorPtr itElement = aHelper->GetMeshDS()->elementsIterator();
1735     SMDS_NodeIteratorPtr itNode = aHelper->GetMeshDS()->nodesIterator();
1736     
1737     while ( itElement->more() )
1738       aHelper->GetMeshDS()->RemoveElement( itElement->next() );
1739     while ( itNode->more() )
1740       aHelper->GetMeshDS()->RemoveNode( itNode->next() );
1741
1742     // Import GMF mesh
1743     myError = aMesh.GMFToMesh(Hexotic_Out.ToCString());
1744     
1745     itElement = aHelper->GetMeshDS()->elementsIterator();
1746     itNode = aHelper->GetMeshDS()->nodesIterator();
1747
1748     // Assign nodes and elements to the pseudo shape
1749     while ( itNode->more() )
1750       aHelper->GetMeshDS()->SetNodeInVolume(itNode->next(), 1);
1751     while ( itElement->more() )
1752       aHelper->GetMeshDS()->SetMeshElementOnShape(itElement->next(), 1);
1753
1754     if(myError->IsOK())
1755 */
1756       hexahedraMessage = "success";
1757     else
1758       hexahedraMessage = "failed";
1759   }
1760   else {
1761 /*
1762     myError->myName = COMPERR_EXCEPTION;
1763 */
1764     hexahedraMessage = "failed";
1765     cout << "Problem with MG-Hexa output file " << Hexotic_Out << std::endl;
1766     // analyse log file
1767     SMESH_File logFile( aLogFileName.ToCString() );
1768     if ( !logFile.eof() )
1769     {
1770       char msgLic[] = " Dlim ";
1771       const char* fileBeg = logFile.getPos(), *fileEnd = fileBeg + logFile.size();
1772       if ( std::search( fileBeg, fileEnd, msgLic, msgLic+strlen(msgLic)) != fileEnd )
1773         return error("Licence problems.");
1774     }
1775     return error(SMESH_Comment("Problem with MG-Hexa output file ")<<Hexotic_Out);
1776   }
1777   cout << "Hexahedra meshing " << hexahedraMessage << std::endl;
1778   cout << std::endl;
1779
1780   if(_compute_canceled)
1781     return error(SMESH_Comment("interruption initiated by user"));
1782   removeFile(Hexotic_Out);
1783   removeFile(Hexotic_In);
1784   removeFile(aLogFileName);
1785   for( size_t i=0; i<sizeMapFiles.size(); i++)
1786   {
1787     removeFile( TCollection_AsciiString(sizeMapFiles[i].c_str()) );
1788   }
1789   return Ok;
1790 /*
1791   return myError->IsOK();
1792 */
1793 }
1794
1795 //=============================================================================
1796 /*!
1797  *
1798  */
1799 //=============================================================================
1800
1801 bool HexoticPlugin_Hexotic::Evaluate(SMESH_Mesh& aMesh,
1802                                      const TopoDS_Shape& aShape,
1803                                      MapShapeNbElems& aResMap)
1804 {
1805   std::vector<int> aResVec(SMDSEntity_Last);
1806   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
1807   SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
1808   aResMap.insert(std::make_pair(sm,aResVec));
1809
1810   SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1811   smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,"Evaluation is not implemented",this));
1812
1813   return true;
1814 }
1815
1816 void HexoticPlugin_Hexotic::CancelCompute()
1817 {
1818   _compute_canceled = true;
1819 #ifdef WIN32
1820 #else
1821   TCollection_AsciiString aTmpDir = _hexoticWorkingDirectory.c_str(); //getTmpDir();
1822   TCollection_AsciiString Hexotic_In = aTmpDir + "Hexotic_In.mesh";
1823   TCollection_AsciiString cmd = TCollection_AsciiString("ps ux | grep ") + Hexotic_In;
1824   cmd += TCollection_AsciiString(" | grep -v grep | awk '{print $2}' | xargs kill -9 > /dev/null 2>&1");
1825   system( cmd.ToCString() );
1826 #endif
1827 }