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