]> SALOME platform Git repositories - plugins/ghs3dplugin.git/blob - src/GHS3DPlugin_GHS3D.cxx
Salome HOME
PAL19680: Meshers: BLSURF, GHS3D and holed shapes
[plugins/ghs3dplugin.git] / src / GHS3DPlugin_GHS3D.cxx
1 // Copyright (C) 2005  CEA/DEN, EDF R&D, OPEN CASCADE, PRINCIPIA 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.
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 // File      : GHS3DPlugin_GHS3D.cxx
21 // Created   : 
22 // Author    : Edward AGAPOV, modified by Lioka RAZAFINDRAZAKA (CEA) 09/02/2007
23 // Project   : SALOME
24 // Copyright : CEA 2003
25 // $Header$
26 //=============================================================================
27 using namespace std;
28
29 #include "GHS3DPlugin_GHS3D.hxx"
30 #include "GHS3DPlugin_Hypothesis.hxx"
31
32 #include "SMESH_Gen.hxx"
33 #include "SMESH_Mesh.hxx"
34 #include "SMESH_Comment.hxx"
35 #include "SMESH_MesherHelper.hxx"
36 #include "SMESH_MeshEditor.hxx"
37
38 #include "SMDS_MeshElement.hxx"
39 #include "SMDS_MeshNode.hxx"
40
41 #include <BRepAdaptor_Surface.hxx>
42 #include <BRepBndLib.hxx>
43 #include <BRepClass3d_SolidClassifier.hxx>
44 #include <BRep_Tool.hxx>
45 #include <Bnd_Box.hxx>
46 #include <GeomAPI_ProjectPointOnSurf.hxx>
47 #include <OSD_File.hxx>
48 #include <Precision.hxx>
49 #include <Quantity_Parameter.hxx>
50 #include <Standard_ErrorHandler.hxx>
51 #include <Standard_Failure.hxx>
52 #include <TopExp.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopTools_IndexedMapOfShape.hxx>
55 #include <TopTools_ListIteratorOfListOfShape.hxx>
56 #include <TopoDS.hxx>
57 //#include <BRepClass_FaceClassifier.hxx>
58 //#include <BRepGProp.hxx>
59 //#include <GProp_GProps.hxx>
60
61 #include "utilities.h"
62
63 #ifndef WIN32
64 #include <sys/sysinfo.h>
65 #endif
66
67 //#include <Standard_Stream.hxx>
68
69
70 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
71
72 #ifdef _DEBUG_
73 #define DUMP(txt) \
74 //  cout << txt
75 #else
76 #define DUMP(txt)
77 #endif
78
79 extern "C"
80 {
81 #ifndef WNT
82 #include <unistd.h>
83 #include <sys/mman.h>
84 #endif
85 #include <sys/stat.h>
86 #include <fcntl.h>
87 }
88
89 //=============================================================================
90 /*!
91  *  
92  */
93 //=============================================================================
94
95 GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, int studyId, SMESH_Gen* gen)
96   : SMESH_3D_Algo(hypId, studyId, gen)
97 {
98   MESSAGE("GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D");
99   _name = "GHS3D_3D";
100   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
101   _onlyUnaryInput = false; // Compute() will be called on a compound of solids
102   _iShape=0;
103   _nbShape=0;
104   _compatibleHypothesis.push_back("GHS3D_Parameters");
105 }
106
107 //=============================================================================
108 /*!
109  *  
110  */
111 //=============================================================================
112
113 GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D()
114 {
115   MESSAGE("GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D");
116 }
117
118 //=============================================================================
119 /*!
120  *  
121  */
122 //=============================================================================
123
124 bool GHS3DPlugin_GHS3D::CheckHypothesis ( SMESH_Mesh&         aMesh,
125                                           const TopoDS_Shape& aShape,
126                                           Hypothesis_Status&  aStatus )
127 {
128   aStatus = SMESH_Hypothesis::HYP_OK;
129
130   // there is only one compatible Hypothesis so far
131   _hyp = 0;
132   _keepFiles = false;
133   const list <const SMESHDS_Hypothesis * >& hyps = GetUsedHypothesis(aMesh, aShape);
134   if ( !hyps.empty() )
135     _hyp = static_cast<const GHS3DPlugin_Hypothesis*> ( hyps.front() );
136   if ( _hyp )
137     _keepFiles = _hyp->GetKeepFiles();
138
139   return true;
140 }
141
142 //=======================================================================
143 //function : findShape
144 //purpose  : 
145 //=======================================================================
146
147 static TopoDS_Shape findShape(const SMDS_MeshNode *aNode[],
148                               TopoDS_Shape        aShape,
149                               const TopoDS_Shape  shape[],
150                               double**            box,
151                               const int           nShape,
152                               TopAbs_State *      state = 0)
153 {
154   gp_XYZ aPnt(0,0,0);
155   int j, iShape, nbNode = 4;
156
157   for ( j=0; j<nbNode; j++ )
158     aPnt += gp_XYZ( aNode[j]->X(), aNode[j]->Y(), aNode[j]->Z() );
159   aPnt /= nbNode;
160
161   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
162   if (state) *state = SC.State();
163   if ( SC.State() != TopAbs_IN || aShape.IsNull() || aShape.ShapeType() != TopAbs_SOLID) {
164     for (iShape = 0; iShape < nShape; iShape++) {
165       aShape = shape[iShape];
166       if ( !( aPnt.X() < box[iShape][0] || box[iShape][1] < aPnt.X() ||
167               aPnt.Y() < box[iShape][2] || box[iShape][3] < aPnt.Y() ||
168               aPnt.Z() < box[iShape][4] || box[iShape][5] < aPnt.Z()) ) {
169         BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
170         if (state) *state = SC.State();
171         if (SC.State() == TopAbs_IN)
172           break;
173       }
174     }
175   }
176   return aShape;
177 }
178
179 //=======================================================================
180 //function : readMapIntLine
181 //purpose  : 
182 //=======================================================================
183
184 static char* readMapIntLine(char* ptr, int tab[]) {
185   long int intVal;
186   cout << endl;
187
188   for ( int i=0; i<17; i++ ) {
189     intVal = strtol(ptr, &ptr, 10);
190     if ( i < 3 )
191       tab[i] = intVal;
192   }
193   return ptr;
194 }
195
196 //=======================================================================
197 //function : readLine
198 //purpose  : 
199 //=======================================================================
200
201 #define GHS3DPlugin_BUFLENGTH 256
202 #define GHS3DPlugin_ReadLine(aPtr,aBuf,aFile,aLineNb) \
203 {  aPtr = fgets( aBuf, GHS3DPlugin_BUFLENGTH - 2, aFile ); aLineNb++; DUMP(endl); }
204
205 //=======================================================================
206 //function : countShape
207 //purpose  :
208 //=======================================================================
209
210 template < class Mesh, class Shape >
211 static int countShape( Mesh* mesh, Shape shape ) {
212   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
213   int nbShape = 0;
214   for ( ; expShape.More(); expShape.Next() ) {
215       nbShape++;
216   }
217   return nbShape;
218 }
219
220 //=======================================================================
221 //function : writeFaces
222 //purpose  : 
223 //=======================================================================
224
225 static bool writeFaces (ofstream &            theFile,
226                         SMESHDS_Mesh *        theMesh,
227                         const map <int,int> & theSmdsToGhs3dIdMap)
228 {
229   // record structure:
230   //
231   // NB_ELEMS DUMMY_INT
232   // Loop from 1 to NB_ELEMS
233   // NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
234
235   int nbShape = countShape( theMesh, TopAbs_FACE );
236
237   int *tabID;             tabID    = new int[nbShape];
238   TopoDS_Shape *tabShape; tabShape = new TopoDS_Shape[nbShape];
239   TopoDS_Shape aShape;
240   SMESHDS_SubMesh* theSubMesh;
241   const SMDS_MeshElement* aFace;
242   const char* space    = "  ";
243   const int   dummyint = 0;
244   map<int,int>::const_iterator itOnMap;
245   SMDS_ElemIteratorPtr itOnSubMesh, itOnSubFace;
246   int shapeID, nbNodes, aSmdsID;
247   bool idFound;
248
249   cout << "    " << theMesh->NbFaces() << " shapes of 2D dimension" << endl;
250   cout << endl;
251
252   theFile << space << theMesh->NbFaces() << space << dummyint << endl;
253
254   TopExp_Explorer expface( theMesh->ShapeToMesh(), TopAbs_FACE );
255   for ( int i = 0; expface.More(); expface.Next(), i++ ) {
256     tabID[i] = 0;
257     aShape   = expface.Current();
258     shapeID  = theMesh->ShapeToIndex( aShape );
259     idFound  = false;
260     for ( int j=0; j<=i; j++) {
261       if ( shapeID == tabID[j] ) {
262         idFound = true;
263         break;
264       }
265     }
266     if ( ! idFound ) {
267       tabID[i]    = shapeID;
268       tabShape[i] = aShape;
269     }
270   }
271   for ( int i =0; i < nbShape; i++ ) {
272     if ( tabID[i] != 0 ) {
273       aShape      = tabShape[i];
274       shapeID     = tabID[i];
275       theSubMesh  = theMesh->MeshElements( aShape );
276       if ( !theSubMesh ) continue;
277       itOnSubMesh = theSubMesh->GetElements();
278       while ( itOnSubMesh->more() ) {
279         aFace   = itOnSubMesh->next();
280         nbNodes = aFace->NbNodes();
281
282         theFile << space << nbNodes;
283
284         itOnSubFace = aFace->nodesIterator();
285         while ( itOnSubFace->more() ) {
286           // find GHS3D ID
287           aSmdsID = itOnSubFace->next()->GetID();
288           itOnMap = theSmdsToGhs3dIdMap.find( aSmdsID );
289           ASSERT( itOnMap != theSmdsToGhs3dIdMap.end() );
290
291           theFile << space << (*itOnMap).second;
292         }
293
294         // (NB_NODES + 1) times: DUMMY_INT
295         for ( int j=0; j<=nbNodes; j++)
296           theFile << space << dummyint;
297
298         theFile << endl;
299       }
300     }
301   }
302
303   delete [] tabID;
304   delete [] tabShape;
305
306   return true;
307 }
308
309 //=======================================================================
310 //function : writeFaces
311 //purpose  : Write Faces in case if generate 3D mesh w/o geometry
312 //=======================================================================
313
314 static bool writeFaces (ofstream &            theFile,
315                         SMESHDS_Mesh *        theMesh,
316                         vector <const SMDS_MeshNode*> & theNodeByGhs3dId)
317 {
318   // record structure:
319   //
320   // NB_ELEMS DUMMY_INT
321   // Loop from 1 to NB_ELEMS
322   //   NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
323
324
325   int nbFaces = 0;
326   list< const SMDS_MeshElement* > faces;
327   list< const SMDS_MeshElement* >::iterator f;
328   map< const SMDS_MeshNode*,int >::iterator it;
329   SMDS_ElemIteratorPtr nodeIt;
330   const SMDS_MeshElement* elem;
331   int nbNodes;
332
333   const char* space    = "  ";
334   const int   dummyint = 0;
335
336   //get all faces from mesh
337   SMDS_FaceIteratorPtr eIt = theMesh->facesIterator();
338   while ( eIt->more() ) {
339     const SMDS_MeshElement* elem = eIt->next();
340     if ( !elem )
341       return false;
342     faces.push_back( elem );
343     nbFaces++;
344   }
345
346   if ( nbFaces == 0 )
347     return false;
348   
349   cout << "The initial 2D mesh contains " << nbFaces << " faces and ";
350
351   // NB_ELEMS DUMMY_INT
352   theFile << space << nbFaces << space << dummyint << endl;
353
354   // Loop from 1 to NB_ELEMS
355
356   map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
357   f = faces.begin();
358   for ( ; f != faces.end(); ++f )
359   {
360     // NB_NODES PER FACE
361     elem = *f;
362     nbNodes = elem->NbNodes();
363     theFile << space << nbNodes;
364
365     // NODE_NB_1 NODE_NB_2 ...
366     nodeIt = elem->nodesIterator();
367     while ( nodeIt->more() )
368     {
369       // find GHS3D ID
370       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
371       int newId = aNodeToGhs3dIdMap.size() + 1; // ghs3d ids count from 1
372       it = aNodeToGhs3dIdMap.insert( make_pair( node, newId )).first;
373       theFile << space << it->second;
374     }
375
376     // (NB_NODES + 1) times: DUMMY_INT
377     for ( int i=0; i<=nbNodes; i++)
378       theFile << space << dummyint;
379
380     theFile << endl;
381   }
382
383   // put nodes to theNodeByGhs3dId vector
384   theNodeByGhs3dId.resize( aNodeToGhs3dIdMap.size() );
385   map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToGhs3dIdMap.begin();
386   for ( ; n2id != aNodeToGhs3dIdMap.end(); ++ n2id)
387   {
388     theNodeByGhs3dId[ n2id->second - 1 ] = n2id->first; // ghs3d ids count from 1
389   }
390
391   return true;
392 }
393
394 //=======================================================================
395 //function : writePoints
396 //purpose  : 
397 //=======================================================================
398
399 static bool writePoints (ofstream &                       theFile,
400                          SMESHDS_Mesh *                   theMesh,
401                          map <int,int> &                  theSmdsToGhs3dIdMap,
402                          map <int,const SMDS_MeshNode*> & theGhs3dIdToNodeMap)
403 {
404   // record structure:
405   //
406   // NB_NODES
407   // Loop from 1 to NB_NODES
408   //   X Y Z DUMMY_INT
409
410   int nbNodes = theMesh->NbNodes();
411   if ( nbNodes == 0 )
412     return false;
413
414   const char* space    = "  ";
415   const int   dummyint = 0;
416
417   int aGhs3dID = 1;
418   SMDS_NodeIteratorPtr it = theMesh->nodesIterator();
419   const SMDS_MeshNode* node;
420
421   // NB_NODES
422   theFile << space << nbNodes << endl;
423   cout << endl;
424   cout << "The initial 2D mesh contains :" << endl;
425   cout << "    " << nbNodes << " vertices" << endl;
426
427   // Loop from 1 to NB_NODES
428
429   while ( it->more() )
430   {
431     node = it->next();
432     theSmdsToGhs3dIdMap.insert( map <int,int>::value_type( node->GetID(), aGhs3dID ));
433     theGhs3dIdToNodeMap.insert (map <int,const SMDS_MeshNode*>::value_type( aGhs3dID, node ));
434     aGhs3dID++;
435
436     // X Y Z DUMMY_INT
437     theFile
438       << space << node->X()
439       << space << node->Y()
440       << space << node->Z()
441       << space << dummyint;
442
443     theFile << endl;
444   }
445
446   return true;
447 }
448
449 //=======================================================================
450 //function : writePoints
451 //purpose  : 
452 //=======================================================================
453
454 static bool writePoints (ofstream &                            theFile,
455                          SMESHDS_Mesh *                        theMesh,
456                          const vector <const SMDS_MeshNode*> & theNodeByGhs3dId)
457 {
458   // record structure:
459   //
460   // NB_NODES
461   // Loop from 1 to NB_NODES
462   //   X Y Z DUMMY_INT
463
464   //int nbNodes = theMesh->NbNodes();
465   int nbNodes = theNodeByGhs3dId.size();
466   if ( nbNodes == 0 )
467     return false;
468
469   const char* space    = "  ";
470   const int   dummyint = 0;
471
472   const SMDS_MeshNode* node;
473
474   // NB_NODES
475   theFile << space << nbNodes << endl;
476   cout << nbNodes << " nodes" << endl;
477
478   // Loop from 1 to NB_NODES
479
480   vector<const SMDS_MeshNode*>::const_iterator nodeIt = theNodeByGhs3dId.begin();
481   vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByGhs3dId.end();
482   for ( ; nodeIt != after; ++nodeIt )
483   {
484     node = *nodeIt;
485
486     // X Y Z DUMMY_INT
487     theFile
488       << space << node->X()
489       << space << node->Y()
490       << space << node->Z()
491       << space << dummyint;
492
493     theFile << endl;
494   }
495
496   return true;
497 }
498
499 //=======================================================================
500 //function : findShapeID
501 //purpose  : find the solid corresponding to GHS3D sub-domain following
502 //           the technique propsed in GHS3D manual in chapter
503 //           "B.4 Subdomain (sub-region) assignment"
504 //=======================================================================
505
506 static int findShapeID(SMESH_Mesh&          mesh,
507                        const SMDS_MeshNode* node1,
508                        const SMDS_MeshNode* node2,
509                        const SMDS_MeshNode* node3)
510 {
511   const int invalidID = 0;
512   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
513
514   // face th enodes belong to
515   const SMDS_MeshElement * face = meshDS->FindFace(node1,node2,node3);
516   if ( !face )
517     return invalidID;
518
519   // geom face the face assigned to
520   SMESH_MeshEditor editor(&mesh);
521   int geomFaceID = editor.FindShape( face );
522   if ( !geomFaceID )
523     return invalidID;
524   TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
525   if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
526     return invalidID;
527   TopoDS_Face geomFace = TopoDS::Face( shape );
528
529   // solids bounded by geom face
530   TopTools_IndexedMapOfShape solids;
531   TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
532   for ( ; ansIt.More(); ansIt.Next() ) {
533     if ( ansIt.Value().ShapeType() == TopAbs_SOLID )
534       solids.Add( ansIt.Value() );
535   }
536   // analyse found solids
537   if ( solids.Extent() == 0 )
538     return invalidID;
539   if ( solids.Extent() == 1 )
540     return meshDS->ShapeToIndex( solids(1) );
541
542   // find orientation of geom face within the first solid
543   TopoDS_Shape solid1 = solids(1);
544   TopExp_Explorer fExp( solid1, TopAbs_FACE );
545   for ( ; fExp.More(); fExp.Next() )
546     if ( geomFace.IsSame( fExp.Current() )) {
547       geomFace = TopoDS::Face( fExp.Current() );
548       break;
549     }
550   if ( !fExp.More() )
551     return invalidID; // face not found
552
553   // find UV of node1 on geomFace
554   SMESH_MesherHelper helper( mesh );
555   gp_XY uv = helper.GetNodeUV( geomFace, node1 );
556
557   // check that uv is correct
558   gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
559   double tol = BRep_Tool::Tolerance( geomFace );
560   BRepAdaptor_Surface surface( geomFace );
561   if ( node1Pnt.Distance( surface.Value( uv.X(), uv.Y() )) > 2 * tol ) {
562     // project node1 onto geomFace to get right UV
563     GeomAPI_ProjectPointOnSurf projector( node1Pnt, surface.Surface().Surface() );
564     if ( !projector.IsDone() || projector.NbPoints() < 1 )
565       return invalidID;
566     Quantity_Parameter U,V;
567     projector.LowerDistanceParameters(U,V);
568     uv = gp_XY( U,V );
569   }
570   // normale to face at node1
571   gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
572   gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
573   gp_Vec vec12( node1Pnt, node2Pnt );
574   gp_Vec vec13( node1Pnt, node3Pnt );
575   gp_Vec meshNormal = vec12 ^ vec13;
576   if ( meshNormal.SquareMagnitude() < DBL_MIN )
577     return invalidID;
578   
579   // normale to geomFace at UV
580   gp_Vec du, dv;
581   surface.D1( uv.X(), uv.Y(), node1Pnt, du, dv );
582   gp_Vec geomNormal = du ^ dv;
583   if ( geomNormal.SquareMagnitude() < DBL_MIN )
584     return findShapeID( mesh, node2, node3, node1 );
585   if ( geomFace.Orientation() == TopAbs_REVERSED )
586     geomNormal.Reverse();
587
588   // compare normals
589   bool isReverse = ( meshNormal * geomNormal ) < 0;
590   if ( isReverse )
591     return meshDS->ShapeToIndex( solids(2) );
592   else
593     return meshDS->ShapeToIndex( solid1 );
594 }
595                        
596 //=======================================================================
597 //function : readResultFile
598 //purpose  : 
599 //=======================================================================
600
601 static bool readResultFile(const int                       fileOpen,
602                            SMESH_Mesh&                     theMesh,
603                            TopoDS_Shape                    tabShape[],
604                            double**                        tabBox,
605                            const int                       nbShape,
606                            map <int,const SMDS_MeshNode*>& theGhs3dIdToNodeMap,
607                            bool                            toMeshHoles)
608 {
609   struct stat status;
610   size_t      length;
611
612   char *ptr, *mapPtr;
613   char *tetraPtr;
614   char *shapePtr;
615
616   SMESHDS_Mesh* theMeshDS = theMesh.GetMeshDS();
617
618   int fileStat;
619   int nbElems, nbNodes, nbInputNodes;
620   int nodeId/*, triangleId*/;
621   int nbTriangle;
622   int ID, shapeID, ghs3dShapeID;
623   int IdShapeRef = 1;
624   int compoundID =
625     nbShape ? theMeshDS->ShapeToIndex( tabShape[0] ) : theMeshDS->ShapeToIndex( theMeshDS->ShapeToMesh() );
626
627   int *tab, *tabID, *nodeID, *nodeAssigne;
628   double *coord;
629   const SMDS_MeshNode **node;
630
631   tab    = new int[3];
632   //tabID  = new int[nbShape];
633   nodeID = new int[4];
634   coord  = new double[3];
635   node   = new const SMDS_MeshNode*[4];
636
637   TopoDS_Shape aSolid;
638   SMDS_MeshNode * aNewNode;
639   map <int,const SMDS_MeshNode*>::iterator itOnNode;
640   SMDS_MeshElement* aTet;
641 #ifdef _DEBUG_
642   set<int> shapeIDs;
643 #endif
644
645   // Read the file state
646   fileStat = fstat(fileOpen, &status);
647   length   = status.st_size;
648
649   // Mapping the result file into memory
650   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
651   mapPtr = ptr;
652
653   ptr      = readMapIntLine(ptr, tab);
654   tetraPtr = ptr;
655
656   nbElems      = tab[0];
657   nbNodes      = tab[1];
658   nbInputNodes = tab[2];
659
660   nodeAssigne = new int[ nbNodes+1 ];
661
662   if (nbShape > 0)
663     aSolid = tabShape[0];
664
665   // Reading the nodeId
666   for (int i=0; i < 4*nbElems; i++)
667     nodeId = strtol(ptr, &ptr, 10);
668
669   // Reading the nodeCoor and update the nodeMap
670   for (int iNode=1; iNode <= nbNodes; iNode++) {
671     for (int iCoor=0; iCoor < 3; iCoor++)
672       coord[ iCoor ] = strtod(ptr, &ptr);
673     nodeAssigne[ iNode ] = 1;
674     if ( iNode > nbInputNodes ) {
675       nodeAssigne[ iNode ] = 0;
676       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
677       theGhs3dIdToNodeMap.insert(theGhs3dIdToNodeMap.end(), make_pair( iNode, aNewNode ));
678     }
679   }
680
681   // Reading the number of triangles which corresponds to the number of sub-domains
682   nbTriangle = strtol(ptr, &ptr, 10);
683
684   tabID = new int[nbTriangle];
685   for (int i=0; i < nbTriangle; i++) {
686     tabID[i] = 0;
687     // find the solid corresponding to GHS3D sub-domain following
688     // the technique propsed in GHS3D manual in chapter
689     // "B.4 Subdomain (sub-region) assignment"
690     int nodeId1 = strtol(ptr, &ptr, 10);
691     int nodeId2 = strtol(ptr, &ptr, 10);
692     int nodeId3 = strtol(ptr, &ptr, 10);
693     const SMDS_MeshNode* n1 = theGhs3dIdToNodeMap[ nodeId1 ];
694     const SMDS_MeshNode* n2 = theGhs3dIdToNodeMap[ nodeId2 ];
695     const SMDS_MeshNode* n3 = theGhs3dIdToNodeMap[ nodeId3 ];
696     try {
697       OCC_CATCH_SIGNALS;
698       tabID[i] = findShapeID( theMesh, n1, n2, n3 );
699 #ifdef _DEBUG_
700       cout << i+1 << " subdomain: findShapeID() returns " << tabID[i] << endl;
701 #endif
702     } catch ( Standard_Failure ) {
703     } catch (...) {}
704   }
705
706   shapePtr = ptr;
707
708   if ( nbTriangle <= nbShape ) // no holes
709     toMeshHoles = true; // not avoid creating tetras in holes
710
711   // Associating the tetrahedrons to the shapes
712   shapeID = compoundID;
713   for (int iElem = 0; iElem < nbElems; iElem++) {
714     for (int iNode = 0; iNode < 4; iNode++) {
715       ID = strtol(tetraPtr, &tetraPtr, 10);
716       itOnNode = theGhs3dIdToNodeMap.find(ID);
717       node[ iNode ] = itOnNode->second;
718       nodeID[ iNode ] = ID;
719     }
720     // We always run GHS3D with "to mesh holes'==TRUE but we must not create
721     // tetras within holes depending on hypo option,
722     // so we first check if aTet is inside a hole and then create it 
723     //aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
724     if ( nbTriangle > 1 ) {
725       shapeID = -1; // negative shapeID means not to create tetras if !toMeshHoles
726       ghs3dShapeID = strtol(shapePtr, &shapePtr, 10) - IdShapeRef;
727       if ( tabID[ ghs3dShapeID ] == 0 ) {
728         TopAbs_State state;
729         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape, &state);
730         if ( toMeshHoles || state == TopAbs_IN )
731           shapeID = theMeshDS->ShapeToIndex( aSolid );
732         tabID[ ghs3dShapeID ] = shapeID;
733       }
734       else
735         shapeID = tabID[ ghs3dShapeID ];
736     }
737     else if ( nbShape > 1 ) {
738       // Case where nbTriangle == 1 while nbShape == 2 encountered
739       // with compound of 2 boxes and "To mesh holes"==False,
740       // so there are no subdomains specified for each tetrahedron.
741       // Try to guess a solid by a node already bound to shape
742       shapeID = 0;
743       for ( int i=0; i<4 && shapeID==0; i++ ) {
744         if ( nodeAssigne[ nodeID[i] ] == 1 &&
745              node[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE &&
746              node[i]->GetPosition()->GetShapeId() > 1 )
747         {
748           shapeID = node[i]->GetPosition()->GetShapeId();
749         }
750       }
751       if ( shapeID==0 ) {
752         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape);
753         shapeID = theMeshDS->ShapeToIndex( aSolid );
754       }
755     }
756     // set new nodes and tetrahedron onto the shape
757     for ( int i=0; i<4; i++ ) {
758       if ( nodeAssigne[ nodeID[i] ] == 0 ) {
759         if ( shapeID > 0 )
760           theMeshDS->SetNodeInVolume( node[i], shapeID );
761         nodeAssigne[ nodeID[i] ] = shapeID;
762       }
763     }
764     if ( toMeshHoles || shapeID > 0 ) {
765       aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
766       theMeshDS->SetMeshElementOnShape( aTet, shapeID );
767     }
768 #ifdef _DEBUG_
769     shapeIDs.insert( shapeID );
770 #endif
771   }
772   // Remove nodes of tetras inside holes if !toMeshHoles
773   if ( !toMeshHoles ) {
774     itOnNode = theGhs3dIdToNodeMap.find( nbInputNodes );
775     for ( ; itOnNode != theGhs3dIdToNodeMap.end(); ++itOnNode) {
776       ID = itOnNode->first;
777       if ( nodeAssigne[ ID ] < 0 )
778         theMeshDS->RemoveFreeNode( itOnNode->second, 0 );
779     }
780   }
781
782   if ( nbElems )
783     cout << nbElems << " tetrahedrons have been associated to " << nbShape << " shapes" << endl;
784   munmap(mapPtr, length);
785   close(fileOpen);
786
787   delete [] tab;
788   delete [] tabID;
789   delete [] nodeID;
790   delete [] coord;
791   delete [] node;
792   delete [] nodeAssigne;
793
794 #ifdef _DEBUG_
795   if ( shapeIDs.size() != nbShape ) {
796     cout << "Only " << shapeIDs.size() << " solids of " << nbShape << " found" << endl;
797     for (int i=0; i<nbShape; i++) {
798       shapeID = theMeshDS->ShapeToIndex( tabShape[i] );
799       if ( shapeIDs.find( shapeID ) == shapeIDs.end() )
800         cout << "  Solid #" << shapeID << " not found" << endl;
801     }
802   }
803 #endif
804
805   return true;
806 }
807
808 //=======================================================================
809 //function : readResultFile
810 //purpose  : 
811 //=======================================================================
812
813 static bool readResultFile(const int                      fileOpen,
814                            SMESHDS_Mesh*                  theMeshDS,
815                            TopoDS_Shape                   aSolid,
816                            vector <const SMDS_MeshNode*>& theNodeByGhs3dId) {
817
818   struct stat  status;
819   size_t       length;
820
821   char *ptr, *mapPtr;
822   char *tetraPtr;
823   char *shapePtr;
824
825   int fileStat;
826   int nbElems, nbNodes, nbInputNodes;
827   int nodeId, triangleId;
828   int nbTriangle;
829   int ID, shapeID;
830
831   int *tab;
832   double *coord;
833   const SMDS_MeshNode **node;
834
835   tab   = new int[3];
836   coord = new double[3];
837   node  = new const SMDS_MeshNode*[4];
838
839   SMDS_MeshNode * aNewNode;
840   map <int,const SMDS_MeshNode*>::iterator IdNode;
841   SMDS_MeshElement* aTet;
842
843   // Read the file state
844   fileStat = fstat(fileOpen, &status);
845   length   = status.st_size;
846
847   // Mapping the result file into memory
848   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
849   mapPtr = ptr;
850
851   ptr      = readMapIntLine(ptr, tab);
852   tetraPtr = ptr;
853
854   nbElems      = tab[0];
855   nbNodes      = tab[1];
856   nbInputNodes = tab[2];
857
858   theNodeByGhs3dId.resize( nbNodes );
859
860   // Reading the nodeId
861   for (int i=0; i < 4*nbElems; i++)
862     nodeId = strtol(ptr, &ptr, 10);
863
864   // Reading the nodeCoor and update the nodeMap
865   shapeID = theMeshDS->ShapeToIndex( aSolid );
866   for (int iNode=0; iNode < nbNodes; iNode++) {
867     for (int iCoor=0; iCoor < 3; iCoor++)
868       coord[ iCoor ] = strtod(ptr, &ptr);
869     if ((iNode+1) > nbInputNodes) {
870       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
871       theMeshDS->SetNodeInVolume( aNewNode, shapeID );
872       theNodeByGhs3dId[ iNode ] = aNewNode;
873     }
874   }
875
876   // Reading the triangles
877   nbTriangle = strtol(ptr, &ptr, 10);
878
879   for (int i=0; i < 3*nbTriangle; i++)
880     triangleId = strtol(ptr, &ptr, 10);
881
882   shapePtr = ptr;
883
884   // Associating the tetrahedrons to the shapes
885   for (int iElem = 0; iElem < nbElems; iElem++) {
886     for (int iNode = 0; iNode < 4; iNode++) {
887       ID = strtol(tetraPtr, &tetraPtr, 10);
888       node[ iNode ] = theNodeByGhs3dId[ ID-1 ];
889     }
890     aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
891     shapeID = theMeshDS->ShapeToIndex( aSolid );
892     theMeshDS->SetMeshElementOnShape( aTet, shapeID );
893   }
894   if ( nbElems )
895     cout << nbElems << " tetrahedrons have been associated to " << nbTriangle << " shapes" << endl;
896   munmap(mapPtr, length);
897   close(fileOpen);
898
899   delete [] tab;
900   delete [] coord;
901   delete [] node;
902
903   return true;
904 }
905
906 //================================================================================
907 /*!
908  * \brief Look for a line containing a text in a file
909   * \retval bool - true if the line is found
910  */
911 //================================================================================
912
913 static bool findLineContaing(const TCollection_AsciiString& theText,
914                              const TCollection_AsciiString& theFile,
915                              TCollection_AsciiString &      theFoundLine)
916 {
917   bool found = false;
918   if ( FILE * aFile = fopen( theFile.ToCString(), "r" ))
919   {
920     char * aPtr;
921     char aBuffer[ GHS3DPlugin_BUFLENGTH ];
922     int aLineNb = 0;
923     do {
924       GHS3DPlugin_ReadLine( aPtr, aBuffer, aFile, aLineNb );
925       if ( aPtr ) {
926         theFoundLine = aPtr;
927         found = theFoundLine.Search( theText ) >= 0;
928       }
929     } while ( aPtr && !found );
930
931     fclose( aFile );
932   }
933   return found;
934 }
935
936 //================================================================================
937 /*!
938  * \brief Provide human readable text by error code reported by ghs3d
939  */
940 //================================================================================
941
942 static TCollection_AsciiString translateError(const TCollection_AsciiString& errorLine)
943 {
944   int beg = errorLine.Location("ERR ", 1, errorLine.Length());
945   if ( !beg ) return errorLine;
946
947   TCollection_AsciiString errCodeStr = errorLine.SubString( beg + 4 , errorLine.Length());
948   if ( !errCodeStr.IsIntegerValue() )
949     return errorLine;
950   Standard_Integer errCode = errCodeStr.IntegerValue();
951
952   int codeEnd = beg + 7;
953   while ( codeEnd < errorLine.Length() && isdigit( errorLine.Value(codeEnd+1) ))
954     codeEnd++;
955   TCollection_AsciiString error = errorLine.SubString( beg, codeEnd ) + ": ";
956
957   switch ( errCode ) {
958   case 0:
959     return "The surface mesh includes a face of type type other than edge, "
960       "triangle or quadrilateral. This face type is not supported.";
961   case 1:
962     return error + "Not enough memory for the face table";
963   case 2:
964     return error + "Not enough memory";
965   case 3:
966     return error + "Not enough memory";
967   case 4:
968     return error + "Face is ignored";
969   case 5:
970     return error + errorLine.SubString( beg + 5, errorLine.Length()) +
971       ": End of file. Some data are missing in the file.";
972   case 6:
973     return error + errorLine.SubString( beg + 5, errorLine.Length()) +
974       ": Read error on the file. There are wrong data in the file.";
975   case 7:
976     return error + "the metric file is inadequate (dimension other than 3).";
977   case 8:
978     return error + "the metric file is inadequate (values not per vertices).";
979   case 9:
980       return error + "the metric file contains more than one field.";
981   case 10:
982     return error + "the number of values in the \".bb\" (metric file) is incompatible with the expected"
983       "value of number of mesh vertices in the \".noboite\" file.";
984   case 12:
985     return error + "Too many sub-domains";
986   case 13:
987     return error + "the number of vertices is negative or null.";
988   case 14:
989     return error + "the number of faces is negative or null.";
990   case 15:
991     return error + "A facehas a null vertex.";
992   case 22:
993     return error + "incompatible data";
994   case 131:
995     return error + "the number of vertices is negative or null.";
996   case 132:
997     return error + "the number of vertices is negative or null (in the \".mesh\" file).";
998   case 133:
999     return error + "the number of faces is negative or null.";
1000   case 1000:
1001     return error + "A face appears more than once in the input surface mesh.";
1002   case 1001:
1003     return error + "An edge appears more than once in the input surface mesh.";
1004   case 1002:
1005     return error + "A face has a vertex negative or null.";
1006   case 1003:
1007     return error + "NOT ENOUGH MEMORY";
1008   case 2000:
1009     return error + "Not enough available memory.";
1010   case 2002:
1011     return error + "Some initial points cannot be inserted. The surface mesh is probably very bad "
1012       "in terms of quality or the input list of points is wrong";
1013   case 2003:
1014     return error + "Some vertices are too close to one another or coincident.";
1015   case 2004:
1016     return error + "Some vertices are too close to one another or coincident.";
1017   case 2012:
1018     return error + "A vertex cannot be inserted.";
1019   case 2014:
1020     return error + "There are at least two points considered as coincident";
1021   case 2103:
1022     return error + "Some vertices are too close to one another or coincident";
1023   case 3000:
1024     return error + "The surface mesh regeneration step has failed";
1025   case 3009:
1026     return error + "Constrained edge cannot be enforced";
1027   case 3019:
1028     return error + "Constrained face cannot be enforced";
1029   case 3029:
1030     return error + "Missing faces";
1031   case 3100:
1032     return error + "No guess to start the definition of the connected component(s)";
1033   case 3101:
1034     return error + "The surface mesh includes at least one hole. The domain is not well defined";
1035   case 3102:
1036     return error + "Impossible to define a component";
1037   case 3103:
1038     return error + "The surface edge intersects another surface edge";
1039   case 3104:
1040     return error + "The surface edge intersects the surface face";
1041   case 3105:
1042     return error + "One boundary point lies within a surface face";
1043   case 3106:
1044     return error + "One surface edge intersects a surface face";
1045   case 3107:
1046     return error + "One boundary point lies within a surface edge";
1047   case 3108:
1048     return error + "Insufficient memory ressources detected due to a bad quality surface mesh leading "
1049       "to too many swaps";
1050   case 3109:
1051     return error + "Edge is unique (i.e., bounds a hole in the surface)";
1052   case 3122:
1053     return error + "Presumably, the surface mesh is not compatible with the domain being processed";
1054   case 3123:
1055     return error + "Too many components, too many sub-domain";
1056   case 3209:
1057     return error + "The surface mesh includes at least one hole. "
1058       "Therefore there is no domain properly defined";
1059   case 3300:
1060     return error + "Statistics.";
1061   case 3400:
1062     return error + "Statistics.";
1063   case 3500:
1064     return error + "Warning, it is dramatically tedious to enforce the boundary items";
1065   case 4000:
1066     return error + "Not enough memory at this time, nevertheless, the program continues. "
1067       "The expected mesh will be correct but not really as large as required";
1068   case 4002:
1069     return error + "see above error code, resulting quality may be poor.";
1070   case 4003:
1071     return error + "Not enough memory at this time, nevertheless, the program continues (warning)";
1072   case 8000:
1073     return error + "Unknown face type.";
1074   case 8005:
1075   case 8006:
1076     return error + errorLine.SubString( beg + 5, errorLine.Length()) +
1077       ": End of file. Some data are missing in the file.";
1078   case 9000:
1079     return error + "A too small volume element is detected";
1080   case 9001:
1081     return error + "There exists at least a null or negative volume element";
1082   case 9002:
1083     return error + "There exist null or negative volume elements";
1084   case 9003:
1085     return error + "A too small volume element is detected. A face is considered being degenerated";
1086   case 9100:
1087     return error + "Some element is suspected to be very bad shaped or wrong";
1088   case 9102:
1089     return error + "A too bad quality face is detected. This face is considered degenerated";
1090   case 9112:
1091     return error + "A too bad quality face is detected. This face is degenerated";
1092   case 9122:
1093     return error + "Presumably, the surface mesh is not compatible with the domain being processed";
1094   case 9999:
1095     return error + "Abnormal error occured, contact hotline";
1096   case 23600:
1097     return error + "Not enough memory for the face table";
1098   case 23601:
1099     return error + "The algorithm cannot run further. "
1100       "The surface mesh is probably very bad in terms of quality.";
1101   case 23602:
1102     return error + "Bad vertex number";
1103   }
1104   return errorLine;
1105 }
1106
1107 //=============================================================================
1108 /*!
1109  *Here we are going to use the GHS3D mesher
1110  */
1111 //=============================================================================
1112
1113 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1114                                 const TopoDS_Shape& theShape)
1115 {
1116   bool Ok(false);
1117   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1118
1119   _nbShape = countShape( meshDS, TopAbs_SOLID ); // we count the number of shapes
1120
1121   // create bounding box for every shape inside the compound
1122
1123   int iShape = 0;
1124   TopoDS_Shape* tabShape;
1125   double**      tabBox;
1126   tabShape = new TopoDS_Shape[_nbShape];
1127   tabBox   = new double*[_nbShape];
1128   for (int i=0; i<_nbShape; i++)
1129     tabBox[i] = new double[6];
1130   Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1131
1132   TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID);
1133   for (; expBox.More(); expBox.Next()) {
1134     tabShape[iShape] = expBox.Current();
1135     Bnd_Box BoundingBox;
1136     BRepBndLib::Add(expBox.Current(), BoundingBox);
1137     BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1138     tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1139     tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1140     tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1141     iShape++;
1142   }
1143
1144   // a unique working file name
1145   // to avoid access to the same files by eg different users
1146   TCollection_AsciiString aGenericName
1147     = (char*) GHS3DPlugin_Hypothesis::GetFileName(_hyp).c_str();
1148
1149   TCollection_AsciiString aFacesFileName, aPointsFileName, aResultFileName;
1150   TCollection_AsciiString aBadResFileName, aBbResFileName, aLogFileName;
1151   aFacesFileName  = aGenericName + ".faces";  // in faces
1152   aPointsFileName = aGenericName + ".points"; // in points
1153   aResultFileName = aGenericName + ".noboite";// out points and volumes
1154   aBadResFileName = aGenericName + ".boite";  // out bad result
1155   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
1156   aLogFileName    = aGenericName + ".log";    // log
1157
1158   // -----------------
1159   // make input files
1160   // -----------------
1161
1162   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
1163   ofstream aPointsFile ( aPointsFileName.ToCString() , ios::out);
1164
1165   Ok =
1166 #ifdef WIN32
1167     aFacesFile->is_open() && aPointsFile->is_open();
1168 #else
1169     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
1170 #endif
1171   if (!Ok) {
1172     INFOS( "Can't write into " << aFacesFileName);
1173     return error(SMESH_Comment("Can't write into ") << aFacesFileName);
1174   }
1175   map <int,int> aSmdsToGhs3dIdMap;
1176   map <int,const SMDS_MeshNode*> aGhs3dIdToNodeMap;
1177
1178   Ok = writePoints( aPointsFile, meshDS, aSmdsToGhs3dIdMap, aGhs3dIdToNodeMap ) &&
1179        writeFaces ( aFacesFile,  meshDS, aSmdsToGhs3dIdMap );
1180
1181   aFacesFile.close();
1182   aPointsFile.close();
1183
1184   if ( ! Ok ) {
1185     if ( !_keepFiles ) {
1186       OSD_File( aFacesFileName ).Remove();
1187       OSD_File( aPointsFileName ).Remove();
1188     }
1189     return error(COMPERR_BAD_INPUT_MESH);
1190   }
1191   OSD_File( aResultFileName ).Remove(); // needed for boundary recovery module usage
1192
1193   // -----------------
1194   // run ghs3d mesher
1195   // -----------------
1196
1197   TCollection_AsciiString cmd( (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp ).c_str() );
1198   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
1199   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1200
1201   cout << endl;
1202   cout << "Ghs3d execution..." << endl;
1203   cout << cmd << endl;
1204
1205   system( cmd.ToCString() ); // run
1206
1207   cout << endl;
1208   cout << "End of Ghs3d execution !" << endl;
1209
1210   // --------------
1211   // read a result
1212   // --------------
1213
1214   // Mapping the result file
1215
1216   int fileOpen;
1217   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
1218   if ( fileOpen < 0 ) {
1219     cout << endl;
1220     cout << "Can't open the " << aResultFileName.ToCString() << " GHS3D output file" << endl;
1221     Ok = false;
1222   }
1223   else {
1224     bool toMeshHoles =
1225       _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
1226     Ok = readResultFile( fileOpen, theMesh, tabShape, tabBox, _nbShape, aGhs3dIdToNodeMap,
1227                          toMeshHoles );
1228   }
1229
1230   // ---------------------
1231   // remove working files
1232   // ---------------------
1233
1234   if ( Ok )
1235   {
1236     if ( !_keepFiles )
1237       OSD_File( aLogFileName ).Remove();
1238   }
1239   else if ( OSD_File( aLogFileName ).Size() > 0 )
1240   {
1241     INFOS( "GHS3D Error, see the " << aLogFileName.ToCString() << " file" );
1242
1243     // get problem description from the log file
1244     SMESH_Comment comment;
1245     TCollection_AsciiString foundLine;
1246     if ( findLineContaing( "has expired",aLogFileName,foundLine) &&
1247          foundLine.Search("Licence") >= 0)
1248     {
1249       foundLine.LeftAdjust();
1250       comment << foundLine;
1251     }
1252     if ( findLineContaing( "%% ERROR",aLogFileName,foundLine) ||
1253          findLineContaing( " ERR ",aLogFileName,foundLine))
1254     {
1255       foundLine.LeftAdjust();
1256       comment << translateError( foundLine );
1257     }
1258     else if ( findLineContaing( "%% NO SAVING OPERATION",aLogFileName,foundLine))
1259     {
1260       comment << "Too many elements generated for a trial version.\n";
1261     }
1262     if ( comment.empty() )
1263       comment << "See " << aLogFileName << " for problem description";
1264     else
1265       comment << "\nSee " << aLogFileName << " for more information";
1266     error(COMPERR_ALGO_FAILED, comment);
1267   }
1268   else
1269   {
1270     // the log file is empty
1271     OSD_File( aLogFileName ).Remove();
1272     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
1273     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
1274   }
1275
1276   if ( !_keepFiles ) {
1277     OSD_File( aFacesFileName ).Remove();
1278     OSD_File( aPointsFileName ).Remove();
1279     OSD_File( aResultFileName ).Remove();
1280     OSD_File( aBadResFileName ).Remove();
1281     OSD_File( aBbResFileName ).Remove();
1282   }
1283   cout << "<" << aResultFileName.ToCString() << "> GHS3D output file ";
1284   if ( !Ok )
1285     cout << "not ";
1286   cout << "treated !" << endl;
1287   cout << endl;
1288
1289   _nbShape = 0;    // re-initializing _nbShape for the next Compute() method call
1290   delete [] tabShape;
1291   delete [] tabBox;
1292
1293   return Ok;
1294 }
1295
1296 //=============================================================================
1297 /*!
1298  *Here we are going to use the GHS3D mesher w/o geometry
1299  */
1300 //=============================================================================
1301 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1302                                 SMESH_MesherHelper* aHelper)
1303 {
1304   MESSAGE("GHS3DPlugin_GHS3D::Compute()");
1305
1306   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1307   TopoDS_Shape theShape = aHelper->GetSubShape();
1308
1309   // a unique working file name
1310   // to avoid access to the same files by eg different users
1311   TCollection_AsciiString aGenericName
1312     = (char*) GHS3DPlugin_Hypothesis::GetFileName(_hyp).c_str();
1313
1314   TCollection_AsciiString aFacesFileName, aPointsFileName, aResultFileName;
1315   TCollection_AsciiString aBadResFileName, aBbResFileName, aLogFileName;
1316   aFacesFileName  = aGenericName + ".faces";  // in faces
1317   aPointsFileName = aGenericName + ".points"; // in points
1318   aResultFileName = aGenericName + ".noboite";// out points and volumes
1319   aBadResFileName = aGenericName + ".boite";  // out bad result
1320   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
1321   aLogFileName    = aGenericName + ".log";    // log
1322
1323   // -----------------
1324   // make input files
1325   // -----------------
1326
1327   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
1328   ofstream aPointsFile  ( aPointsFileName.ToCString()  , ios::out);
1329   bool Ok =
1330 #ifdef WIN32
1331     aFacesFile->is_open() && aPointsFile->is_open();
1332 #else
1333     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
1334 #endif
1335
1336   if (!Ok)
1337     return error( SMESH_Comment("Can't write into ") << aPointsFileName);
1338
1339   vector <const SMDS_MeshNode*> aNodeByGhs3dId;
1340
1341   Ok = (writeFaces ( aFacesFile, meshDS, aNodeByGhs3dId ) &&
1342         writePoints( aPointsFile, meshDS, aNodeByGhs3dId));
1343   
1344   aFacesFile.close();
1345   aPointsFile.close();
1346   
1347   if ( ! Ok ) {
1348     if ( !_keepFiles ) {
1349       OSD_File( aFacesFileName ).Remove();
1350       OSD_File( aPointsFileName ).Remove();
1351     }
1352     return error(COMPERR_BAD_INPUT_MESH);
1353   }
1354   OSD_File( aResultFileName ).Remove(); // needed for boundary recovery module usage
1355
1356   // -----------------
1357   // run ghs3d mesher
1358   // -----------------
1359
1360   TCollection_AsciiString cmd =
1361     (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false ).c_str();
1362   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
1363   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1364   
1365   system( cmd.ToCString() ); // run
1366
1367   // --------------
1368   // read a result
1369   // --------------
1370   int fileOpen;
1371   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
1372   if ( fileOpen < 0 ) {
1373     cout << endl;
1374     cout << "Error when opening the " << aResultFileName.ToCString() << " file" << endl;
1375     cout << endl;
1376     Ok = false;
1377   }
1378   else {
1379     Ok = readResultFile( fileOpen, meshDS, theShape ,aNodeByGhs3dId );
1380   }
1381   
1382   // ---------------------
1383   // remove working files
1384   // ---------------------
1385
1386   if ( Ok )
1387   {
1388     if ( !_keepFiles )
1389       OSD_File( aLogFileName ).Remove();
1390   }
1391   else if ( OSD_File( aLogFileName ).Size() > 0 )
1392   {
1393     INFOS( "GHS3D Error, see the " << aLogFileName.ToCString() << " file" );
1394
1395     // get problem description from the log file
1396     SMESH_Comment comment;
1397     TCollection_AsciiString foundLine;
1398     if ( findLineContaing( "has expired",aLogFileName,foundLine) &&
1399          foundLine.Search("Licence") >= 0)
1400     {
1401       foundLine.LeftAdjust();
1402       comment << foundLine;
1403     }
1404     if ( findLineContaing( "%% ERROR",aLogFileName,foundLine) ||
1405          findLineContaing( " ERR ",aLogFileName,foundLine))
1406     {
1407       foundLine.LeftAdjust();
1408       comment << translateError( foundLine );
1409     }
1410     else if ( findLineContaing( "%% NO SAVING OPERATION",aLogFileName,foundLine))
1411     {
1412       comment << "Too many elements generated for a trial version.\n";
1413     }
1414     if ( comment.empty() )
1415       comment << "See " << aLogFileName << " for problem description";
1416     else
1417       comment << "\nSee " << aLogFileName << " for more information";
1418     error(COMPERR_ALGO_FAILED, comment);
1419   }
1420   else {
1421     // the log file is empty
1422     OSD_File( aLogFileName ).Remove();
1423     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
1424     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
1425   }
1426
1427   if ( !_keepFiles )
1428   {
1429     OSD_File( aFacesFileName ).Remove();
1430     OSD_File( aPointsFileName ).Remove();
1431     OSD_File( aResultFileName ).Remove();
1432     OSD_File( aBadResFileName ).Remove();
1433     OSD_File( aBbResFileName ).Remove();
1434   }
1435   
1436   return Ok;
1437 }