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