]> SALOME platform Git repositories - plugins/ghs3dplugin.git/blob - src/GHS3DPlugin_GHS3D.cxx
Salome HOME
0020682: EDF 1222 SMESH: 3D mesh from a skin mesh and with volumic cells
[plugins/ghs3dplugin.git] / src / GHS3DPlugin_GHS3D.cxx
1 //  Copyright (C) 2004-2008  CEA/DEN, EDF R&D
2 //
3 //  This library is free software; you can redistribute it and/or
4 //  modify it under the terms of the GNU Lesser General Public
5 //  License as published by the Free Software Foundation; either
6 //  version 2.1 of the License.
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 // $Header$
25 //=============================================================================
26 //
27 #include "GHS3DPlugin_GHS3D.hxx"
28 #include "GHS3DPlugin_Hypothesis.hxx"
29
30
31 #include <Basics_Utils.hxx>
32
33 #include "SMESH_Gen.hxx"
34 #include "SMESH_Mesh.hxx"
35 #include "SMESH_Comment.hxx"
36 #include "SMESH_MesherHelper.hxx"
37 #include "SMESH_MeshEditor.hxx"
38
39 #include "SMDS_MeshElement.hxx"
40 #include "SMDS_MeshNode.hxx"
41 #include "SMDS_FaceOfNodes.hxx"
42 #include "SMDS_VolumeOfNodes.hxx"
43
44 #include <BRepAdaptor_Surface.hxx>
45 #include <BRepBndLib.hxx>
46 #include <BRepClass3d_SolidClassifier.hxx>
47 #include <BRepTools.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_Box.hxx>
50 #include <GeomAPI_ProjectPointOnSurf.hxx>
51 #include <OSD_File.hxx>
52 #include <Precision.hxx>
53 #include <Quantity_Parameter.hxx>
54 #include <Standard_ProgramError.hxx>
55 #include <Standard_ErrorHandler.hxx>
56 #include <Standard_Failure.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopTools_IndexedMapOfShape.hxx>
60 #include <TopTools_ListIteratorOfListOfShape.hxx>
61 #include <TopoDS.hxx>
62 //#include <BRepClass_FaceClassifier.hxx>
63 #include <TopTools_MapOfShape.hxx>
64 #include <BRepGProp.hxx>
65 #include <GProp_GProps.hxx>
66
67 #include "utilities.h"
68
69 #ifdef WIN32
70 #include <io.h>
71 #else
72 #include <sys/sysinfo.h>
73 #endif
74
75 using namespace std;
76
77 //#include <Standard_Stream.hxx>
78
79
80 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
81
82 #ifdef _DEBUG_
83 #define DUMP(txt) \
84 //  std::cout << txt
85 #else
86 #define DUMP(txt)
87 #endif
88
89 extern "C"
90 {
91 #ifndef WNT
92 #include <unistd.h>
93 #include <sys/mman.h>
94 #endif
95 #include <sys/stat.h>
96 #include <fcntl.h>
97 }
98
99 #define HOLE_ID -1
100
101 static void removeFile( const TCollection_AsciiString& fileName )
102 {
103   try {
104     OSD_File( fileName ).Remove();
105   }
106   catch ( Standard_ProgramError ) {
107     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
108   }
109 }
110
111 //=============================================================================
112 /*!
113  *  
114  */
115 //=============================================================================
116
117 GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D(int hypId, int studyId, SMESH_Gen* gen)
118   : SMESH_3D_Algo(hypId, studyId, gen)
119 {
120   MESSAGE("GHS3DPlugin_GHS3D::GHS3DPlugin_GHS3D");
121   _name = "GHS3D_3D";
122   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
123   _onlyUnaryInput = false; // Compute() will be called on a compound of solids
124   _iShape=0;
125   _nbShape=0;
126   _compatibleHypothesis.push_back("GHS3D_Parameters");
127   _requireShape = false; // can work without shape
128 }
129
130 //=============================================================================
131 /*!
132  *  
133  */
134 //=============================================================================
135
136 GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D()
137 {
138   MESSAGE("GHS3DPlugin_GHS3D::~GHS3DPlugin_GHS3D");
139 }
140
141 //=============================================================================
142 /*!
143  *  
144  */
145 //=============================================================================
146
147 bool GHS3DPlugin_GHS3D::CheckHypothesis ( SMESH_Mesh&         aMesh,
148                                           const TopoDS_Shape& aShape,
149                                           Hypothesis_Status&  aStatus )
150 {
151   aStatus = SMESH_Hypothesis::HYP_OK;
152
153   // there is only one compatible Hypothesis so far
154   _hyp = 0;
155   _keepFiles = false;
156   const list <const SMESHDS_Hypothesis * >& hyps = GetUsedHypothesis(aMesh, aShape);
157   if ( !hyps.empty() )
158     _hyp = static_cast<const GHS3DPlugin_Hypothesis*> ( hyps.front() );
159   if ( _hyp )
160     _keepFiles = _hyp->GetKeepFiles();
161
162   return true;
163 }
164
165 //=======================================================================
166 //function : findShape
167 //purpose  : 
168 //=======================================================================
169
170 static TopoDS_Shape findShape(const SMDS_MeshNode *aNode[],
171                               TopoDS_Shape        aShape,
172                               const TopoDS_Shape  shape[],
173                               double**            box,
174                               const int           nShape,
175                               TopAbs_State *      state = 0)
176 {
177   gp_XYZ aPnt(0,0,0);
178   int j, iShape, nbNode = 4;
179
180   for ( j=0; j<nbNode; j++ ) {
181     gp_XYZ p ( aNode[j]->X(), aNode[j]->Y(), aNode[j]->Z() );
182     if ( aNode[j]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE ) {
183       aPnt = p;
184       break;
185     }
186     aPnt += p / nbNode;
187   }
188
189   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
190   if (state) *state = SC.State();
191   if ( SC.State() != TopAbs_IN || aShape.IsNull() || aShape.ShapeType() != TopAbs_SOLID) {
192     for (iShape = 0; iShape < nShape; iShape++) {
193       aShape = shape[iShape];
194       if ( !( aPnt.X() < box[iShape][0] || box[iShape][1] < aPnt.X() ||
195               aPnt.Y() < box[iShape][2] || box[iShape][3] < aPnt.Y() ||
196               aPnt.Z() < box[iShape][4] || box[iShape][5] < aPnt.Z()) ) {
197         BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
198         if (state) *state = SC.State();
199         if (SC.State() == TopAbs_IN)
200           break;
201       }
202     }
203   }
204   return aShape;
205 }
206
207 //=======================================================================
208 //function : readMapIntLine
209 //purpose  : 
210 //=======================================================================
211
212 static char* readMapIntLine(char* ptr, int tab[]) {
213   long int intVal;
214   std::cout << std::endl;
215
216   for ( int i=0; i<17; i++ ) {
217     intVal = strtol(ptr, &ptr, 10);
218     if ( i < 3 )
219       tab[i] = intVal;
220   }
221   return ptr;
222 }
223
224 //=======================================================================
225 //function : countShape
226 //purpose  :
227 //=======================================================================
228
229 template < class Mesh, class Shape >
230 static int countShape( Mesh* mesh, Shape shape ) {
231   TopExp_Explorer expShape ( mesh->ShapeToMesh(), shape );
232   int nbShape = 0;
233   for ( ; expShape.More(); expShape.Next() ) {
234       nbShape++;
235   }
236   return nbShape;
237 }
238
239 //=======================================================================
240 //function : writeFaces
241 //purpose  : 
242 //=======================================================================
243
244 static bool writeFaces (ofstream &            theFile,
245                         SMESHDS_Mesh *        theMesh,
246                         const map <int,int> & theSmdsToGhs3dIdMap)
247 {
248   // record structure:
249   //
250   // NB_ELEMS DUMMY_INT
251   // Loop from 1 to NB_ELEMS
252   // NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
253
254   int nbShape = countShape( theMesh, TopAbs_FACE );
255
256   int *tabID;             tabID    = new int[nbShape];
257   TopoDS_Shape *tabShape; tabShape = new TopoDS_Shape[nbShape];
258   TopoDS_Shape aShape;
259   SMESHDS_SubMesh* theSubMesh;
260   const SMDS_MeshElement* aFace;
261   const char* space    = "  ";
262   const int   dummyint = 0;
263   map<int,int>::const_iterator itOnMap;
264   SMDS_ElemIteratorPtr itOnSubMesh, itOnSubFace;
265   int shapeID, nbNodes, aSmdsID;
266   bool idFound;
267
268   std::cout << "    " << theMesh->NbFaces() << " shapes of 2D dimension" << std::endl;
269   std::cout << std::endl;
270
271   theFile << space << theMesh->NbFaces() << space << dummyint << std::endl;
272
273   TopExp_Explorer expface( theMesh->ShapeToMesh(), TopAbs_FACE );
274   for ( int i = 0; expface.More(); expface.Next(), i++ ) {
275     tabID[i] = 0;
276     aShape   = expface.Current();
277     shapeID  = theMesh->ShapeToIndex( aShape );
278     idFound  = false;
279     for ( int j=0; j<=i; j++) {
280       if ( shapeID == tabID[j] ) {
281         idFound = true;
282         break;
283       }
284     }
285     if ( ! idFound ) {
286       tabID[i]    = shapeID;
287       tabShape[i] = aShape;
288     }
289   }
290   for ( int i =0; i < nbShape; i++ ) {
291     if ( tabID[i] != 0 ) {
292       aShape      = tabShape[i];
293       shapeID     = tabID[i];
294       theSubMesh  = theMesh->MeshElements( aShape );
295       if ( !theSubMesh ) continue;
296       itOnSubMesh = theSubMesh->GetElements();
297       while ( itOnSubMesh->more() ) {
298         aFace   = itOnSubMesh->next();
299         nbNodes = aFace->NbNodes();
300
301         theFile << space << nbNodes;
302
303         itOnSubFace = aFace->nodesIterator();
304         while ( itOnSubFace->more() ) {
305           // find GHS3D ID
306           aSmdsID = itOnSubFace->next()->GetID();
307           itOnMap = theSmdsToGhs3dIdMap.find( aSmdsID );
308 //           if ( itOnMap == theSmdsToGhs3dIdMap.end() ) {
309 //             cout << "not found node: " << aSmdsID << endl;
310 //             return false;
311 //           }
312           ASSERT( itOnMap != theSmdsToGhs3dIdMap.end() );
313
314           theFile << space << (*itOnMap).second;
315         }
316
317         // (NB_NODES + 1) times: DUMMY_INT
318         for ( int j=0; j<=nbNodes; j++)
319           theFile << space << dummyint;
320
321         theFile << std::endl;
322       }
323     }
324   }
325   
326   
327   delete [] tabID;
328   delete [] tabShape;
329
330   return true;
331 }
332
333 //=======================================================================
334 //function : writeFaces
335 //purpose  : Write Faces in case if generate 3D mesh w/o geometry
336 //=======================================================================
337
338 static bool writeFaces (ofstream &            theFile,
339                         SMESHDS_Mesh *        theMesh,
340                         vector <const SMDS_MeshNode*> & theNodeByGhs3dId)
341 {
342   // record structure:
343   //
344   // NB_ELEMS DUMMY_INT
345   // Loop from 1 to NB_ELEMS
346   //   NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
347
348
349   int nbFaces = 0;
350   list< const SMDS_MeshElement* > faces;
351   list< const SMDS_MeshElement* >::iterator f;
352   map< const SMDS_MeshNode*,int >::iterator it;
353   SMDS_ElemIteratorPtr nodeIt;
354   const SMDS_MeshElement* elem;
355   int nbNodes;
356
357   const char* space    = "  ";
358   const int   dummyint = 0;
359
360   //get all faces from mesh
361   SMDS_FaceIteratorPtr eIt = theMesh->facesIterator();
362   while ( eIt->more() ) {
363     const SMDS_MeshElement* elem = eIt->next();
364     if ( !elem )
365       return false;
366     faces.push_back( elem );
367     nbFaces++;
368   }
369
370   if ( nbFaces == 0 )
371     return false;
372   
373   std::cout << "The initial 2D mesh contains " << nbFaces << " faces and ";
374
375   // NB_ELEMS DUMMY_INT
376   theFile << space << nbFaces << space << dummyint << std::endl;
377
378   // Loop from 1 to NB_ELEMS
379
380   map<const SMDS_MeshNode*,int> aNodeToGhs3dIdMap;
381   f = faces.begin();
382   for ( ; f != faces.end(); ++f )
383   {
384     // NB_NODES PER FACE
385     elem = *f;
386     nbNodes = elem->NbNodes();
387     theFile << space << nbNodes;
388
389     // NODE_NB_1 NODE_NB_2 ...
390     nodeIt = elem->nodesIterator();
391     while ( nodeIt->more() )
392     {
393       // find GHS3D ID
394       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
395       int newId = aNodeToGhs3dIdMap.size() + 1; // ghs3d ids count from 1
396       it = aNodeToGhs3dIdMap.insert( make_pair( node, newId )).first;
397       theFile << space << it->second;
398     }
399
400     // (NB_NODES + 1) times: DUMMY_INT
401     for ( int i=0; i<=nbNodes; i++)
402       theFile << space << dummyint;
403
404     theFile << std::endl;
405   }
406
407   // put nodes to theNodeByGhs3dId vector
408   theNodeByGhs3dId.resize( aNodeToGhs3dIdMap.size() );
409   map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToGhs3dIdMap.begin();
410   for ( ; n2id != aNodeToGhs3dIdMap.end(); ++ n2id)
411   {
412     theNodeByGhs3dId[ n2id->second - 1 ] = n2id->first; // ghs3d ids count from 1
413   }
414
415   return true;
416 }
417
418 //=======================================================================
419 //function : writePoints
420 //purpose  : 
421 //=======================================================================
422
423 static bool writePoints (ofstream &                       theFile,
424                          SMESH_MesherHelper&              theHelper,
425                          map <int,int> &                  theSmdsToGhs3dIdMap,
426                          map <int,const SMDS_MeshNode*> & theGhs3dIdToNodeMap,
427                          map<vector<double>,double> &     theEnforcedVertices)
428 {
429   // record structure:
430   //
431   // NB_NODES
432   // Loop from 1 to NB_NODES
433   //   X Y Z DUMMY_INT
434
435   SMESHDS_Mesh * theMesh = theHelper.GetMeshDS();
436   int nbNodes = theMesh->NbNodes();
437   if ( nbNodes == 0 )
438     return false;
439   int nbEnforcedVertices = theEnforcedVertices.size();
440
441   // Issue 020674: EDF 870 SMESH: Mesh generated by Netgen not usable by GHS3D
442   // The problem is in nodes on degenerated edges, we need to skip them
443   if ( theHelper.HasDegeneratedEdges() )
444   {
445     // here we decrease total nb of nodes by nb of nodes on degenerated edges
446     set<int> checkedSM;
447     for (TopExp_Explorer e(theMesh->ShapeToMesh(), TopAbs_EDGE ); e.More(); e.Next())
448     {
449       SMESH_subMesh* sm = theHelper.GetMesh()->GetSubMesh( e.Current() );
450       if ( checkedSM.insert( sm->GetId() ).second && theHelper.IsDegenShape(sm->GetId() )) {
451         if ( sm->GetSubMeshDS() )
452           nbNodes -= sm->GetSubMeshDS()->NbNodes();
453       }
454     }
455   }
456   const char* space    = "  ";
457   const int   dummyint = 0;
458
459   int aGhs3dID = 1;
460   SMDS_NodeIteratorPtr it = theMesh->nodesIterator();
461   const SMDS_MeshNode* node;
462
463   // NB_NODES
464   std::cout << std::endl;
465   std::cout << "The initial 2D mesh contains :" << std::endl;
466   std::cout << "    " << nbNodes << " nodes" << std::endl;
467   if (nbEnforcedVertices > 0) {
468     std::cout << "    " << nbEnforcedVertices << " enforced vertices" << std::endl;
469   }
470   std::cout << std::endl;
471   std::cout << "Start writing in 'points' file ..." << std::endl;
472   theFile << space << nbNodes << std::endl;
473
474   // Loop from 1 to NB_NODES
475
476   while ( it->more() )
477   {
478     node = it->next();
479     if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE &&
480          theHelper.IsDegenShape( node->GetPosition()->GetShapeId() )) // Issue 020674
481       continue;
482
483     theSmdsToGhs3dIdMap.insert( make_pair( node->GetID(), aGhs3dID ));
484     theGhs3dIdToNodeMap.insert( make_pair( aGhs3dID, node ));
485     aGhs3dID++;
486
487     // X Y Z DUMMY_INT
488     theFile
489     << space << node->X()
490     << space << node->Y()
491     << space << node->Z()
492     << space << dummyint;
493
494     theFile << std::endl;
495
496   }
497   
498   // Iterate over the enforced vertices
499   GHS3DPlugin_Hypothesis::TEnforcedVertexValues::const_iterator vertexIt;
500   const TopoDS_Shape shapeToMesh = theMesh->ShapeToMesh();
501   for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
502     double x = vertexIt->first[0];
503     double y = vertexIt->first[1];
504     double z = vertexIt->first[2];
505     // Test if point is inside shape to mesh
506     gp_Pnt myPoint(x,y,z);
507     BRepClass3d_SolidClassifier scl(shapeToMesh);
508     scl.Perform(myPoint, 1e-7);
509     TopAbs_State result = scl.State();
510     if ( result == TopAbs_IN ) {
511         MESSAGE("Adding enforced vertex (" << x << "," << y <<"," << z << ") = " << vertexIt->second);
512         // X Y Z PHY_SIZE DUMMY_INT
513         theFile
514         << space << x
515         << space << y
516         << space << z
517         << space << vertexIt->second
518         << space << dummyint;
519     
520         theFile << std::endl;
521     }
522     else
523         MESSAGE("Enforced vertex (" << x << "," << y <<"," << z << ") is not inside the geometry: it was not added ");
524   }
525   
526   
527   std::cout << std::endl;
528   std::cout << "End writing in 'points' file." << std::endl;
529
530   return true;
531 }
532
533 //=======================================================================
534 //function : writePoints
535 //purpose  : 
536 //=======================================================================
537
538 static bool writePoints (ofstream &                                     theFile,
539                          SMESHDS_Mesh *                                 theMesh,
540                          const vector <const SMDS_MeshNode*> &          theNodeByGhs3dId,
541                          map<vector<double>,double> & theEnforcedVertices)
542 {
543   // record structure:
544   //
545   // NB_NODES
546   // Loop from 1 to NB_NODES
547   //   X Y Z DUMMY_INT
548   
549   //int nbNodes = theMesh->NbNodes();
550   int nbNodes = theNodeByGhs3dId.size();
551   if ( nbNodes == 0 )
552     return false;
553
554   int nbEnforcedVertices = theEnforcedVertices.size();
555
556   const char* space    = "  ";
557   const int   dummyint = 0;
558
559   const SMDS_MeshNode* node;
560
561   // NB_NODES
562   std::cout << std::endl;
563   std::cout << "The initial 2D mesh contains :" << std::endl;
564   std::cout << "    " << nbNodes << " nodes" << std::endl;
565   std::cout << "    " << nbEnforcedVertices << " enforced vertices" << std::endl;
566   std::cout << std::endl;
567   std::cout << "Start writing in 'points' file ..." << std::endl;
568   theFile << space << nbNodes << std::endl;
569
570   // Loop from 1 to NB_NODES
571
572   vector<const SMDS_MeshNode*>::const_iterator nodeIt = theNodeByGhs3dId.begin();
573   vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByGhs3dId.end();
574   for ( ; nodeIt != after; ++nodeIt )
575   {
576     node = *nodeIt;
577
578     // X Y Z DUMMY_INT
579     theFile
580     << space << node->X()
581     << space << node->Y()
582     << space << node->Z()
583     << space << dummyint;
584
585     theFile << std::endl;
586
587   }
588   
589   // Iterate over the enforced vertices
590   GHS3DPlugin_Hypothesis::TEnforcedVertexValues::const_iterator vertexIt;
591   const TopoDS_Shape shapeToMesh = theMesh->ShapeToMesh();
592   for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
593     double x = vertexIt->first[0];
594     double y = vertexIt->first[1];
595     double z = vertexIt->first[2];
596     // Test if point is inside shape to mesh
597     gp_Pnt myPoint(x,y,z);
598     BRepClass3d_SolidClassifier scl(shapeToMesh);
599     scl.Perform(myPoint, 1e-7);
600     TopAbs_State result = scl.State();
601     if ( result == TopAbs_IN ) {
602         std::cout << "Adding enforced vertex (" << x << "," << y <<"," << z << ") = " << vertexIt->second << std::endl;
603
604         // X Y Z PHY_SIZE DUMMY_INT
605         theFile
606         << space << x
607         << space << y
608         << space << z
609         << space << vertexIt->second
610         << space << dummyint;
611     
612         theFile << std::endl;
613     }
614   }
615   std::cout << std::endl;
616   std::cout << "End writing in 'points' file." << std::endl;
617
618   return true;
619 }
620
621 //=======================================================================
622 //function : findShapeID
623 //purpose  : find the solid corresponding to GHS3D sub-domain following
624 //           the technique proposed in GHS3D manual in chapter
625 //           "B.4 Subdomain (sub-region) assignment"
626 //=======================================================================
627
628 static int findShapeID(SMESH_Mesh&          mesh,
629                        const SMDS_MeshNode* node1,
630                        const SMDS_MeshNode* node2,
631                        const SMDS_MeshNode* node3,
632                        const bool           toMeshHoles)
633 {
634   const int invalidID = 0;
635   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
636
637   // face the nodes belong to
638   const SMDS_MeshElement * face = meshDS->FindFace(node1,node2,node3);
639   if ( !face )
640     return invalidID;
641
642   // geom face the face assigned to
643   SMESH_MeshEditor editor(&mesh);
644   int geomFaceID = editor.FindShape( face );
645   if ( !geomFaceID )
646     return invalidID;
647   TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
648   if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
649     return invalidID;
650   TopoDS_Face geomFace = TopoDS::Face( shape );
651
652   // solids bounded by geom face
653   TopTools_IndexedMapOfShape solids, shells;
654   TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
655   for ( ; ansIt.More(); ansIt.Next() ) {
656     switch ( ansIt.Value().ShapeType() ) {
657     case TopAbs_SOLID:
658       solids.Add( ansIt.Value() ); break;
659     case TopAbs_SHELL:
660       shells.Add( ansIt.Value() ); break;
661     default:;
662     }
663   }
664   // analyse found solids
665   if ( solids.Extent() == 0 || shells.Extent() == 0)
666     return invalidID;
667
668   const TopoDS_Solid& solid1 = TopoDS::Solid( solids(1) );
669   if ( solids.Extent() == 1 )
670   {
671     if ( toMeshHoles )
672       return meshDS->ShapeToIndex( solid1 );
673
674     // - Are we at a hole boundary face?
675     if ( shells(1).IsSame( BRepTools::OuterShell( solid1 )) )
676     { // - No, but maybe a hole is bound by two shapes? Does shells(1) touches another shell?
677       bool touch = false;
678       TopExp_Explorer eExp( shells(1), TopAbs_EDGE );
679       // check if any edge of shells(1) belongs to another shell
680       for ( ; eExp.More() && !touch; eExp.Next() ) {
681         ansIt = mesh.GetAncestors( eExp.Current() );
682         for ( ; ansIt.More() && !touch; ansIt.Next() ) {
683           if ( ansIt.Value().ShapeType() == TopAbs_SHELL )
684             touch = ( !ansIt.Value().IsSame( shells(1) ));
685         }
686       }
687       if (!touch)
688         return meshDS->ShapeToIndex( solid1 );
689     }
690   }
691   // find orientation of geom face within the first solid
692   TopExp_Explorer fExp( solid1, TopAbs_FACE );
693   for ( ; fExp.More(); fExp.Next() )
694     if ( geomFace.IsSame( fExp.Current() )) {
695       geomFace = TopoDS::Face( fExp.Current() );
696       break;
697     }
698   if ( !fExp.More() )
699     return invalidID; // face not found
700
701   // normale to triangle
702   gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
703   gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
704   gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
705   gp_Vec vec12( node1Pnt, node2Pnt );
706   gp_Vec vec13( node1Pnt, node3Pnt );
707   gp_Vec meshNormal = vec12 ^ vec13;
708   if ( meshNormal.SquareMagnitude() < DBL_MIN )
709     return invalidID;
710
711   // find UV of node1 on geomFace
712   SMESH_MesherHelper helper( mesh ); helper.SetSubShape( geomFace );
713   const SMDS_MeshNode* nNotOnSeamEdge = 0;
714   if ( helper.IsSeamShape( node1->GetPosition()->GetShapeId() ))
715     if ( helper.IsSeamShape( node2->GetPosition()->GetShapeId() ))
716       nNotOnSeamEdge = node3;
717     else
718       nNotOnSeamEdge = node2;
719   bool uvOK;
720   gp_XY uv = helper.GetNodeUV( geomFace, node1, nNotOnSeamEdge, &uvOK );
721   // check that uv is correct
722   double tol = 1e-6;
723   TopoDS_Shape nodeShape = helper.GetSubShapeByNode( node1, meshDS );
724   if ( !nodeShape.IsNull() )
725     switch ( nodeShape.ShapeType() )
726     {
727     case TopAbs_FACE:   tol = BRep_Tool::Tolerance( TopoDS::Face( nodeShape )); break;
728     case TopAbs_EDGE:   tol = BRep_Tool::Tolerance( TopoDS::Edge( nodeShape )); break;
729     case TopAbs_VERTEX: tol = BRep_Tool::Tolerance( TopoDS::Vertex( nodeShape )); break;
730     default:;
731     }
732   BRepAdaptor_Surface surface( geomFace );
733   if ( !uvOK || node1Pnt.Distance( surface.Value( uv.X(), uv.Y() )) > 2 * tol )
734       return invalidID;
735
736   // normale to geomFace at UV
737   gp_Vec du, dv;
738   surface.D1( uv.X(), uv.Y(), node1Pnt, du, dv );
739   gp_Vec geomNormal = du ^ dv;
740   if ( geomNormal.SquareMagnitude() < DBL_MIN )
741     return findShapeID( mesh, node2, node3, node1, toMeshHoles );
742   if ( geomFace.Orientation() == TopAbs_REVERSED )
743     geomNormal.Reverse();
744
745   // compare normals
746   bool isReverse = ( meshNormal * geomNormal ) < 0;
747   if ( !isReverse )
748     return meshDS->ShapeToIndex( solid1 );
749
750   if ( solids.Extent() == 1 )
751     return HOLE_ID; // we are inside a hole
752   else
753     return meshDS->ShapeToIndex( solids(2) );
754 }
755                        
756 //=======================================================================
757 //function : readResultFile
758 //purpose  : 
759 //=======================================================================
760
761 static bool readResultFile(const int                       fileOpen,
762 #ifdef WNT
763                            const char*                     fileName,
764 #endif
765                            SMESH_Mesh&                     theMesh,
766                            TopoDS_Shape                    tabShape[],
767                            double**                        tabBox,
768                            const int                       nbShape,
769                            map <int,const SMDS_MeshNode*>& theGhs3dIdToNodeMap,
770                            bool                            toMeshHoles,
771                            int                             nbEnforcedVertices)
772 {
773   MESSAGE("GHS3DPlugin_GHS3D::readResultFile()");
774   Kernel_Utils::Localizer loc;
775   struct stat status;
776   size_t      length;
777
778   char *ptr, *mapPtr;
779   char *tetraPtr;
780   char *shapePtr;
781
782   SMESHDS_Mesh* theMeshDS = theMesh.GetMeshDS();
783
784   int fileStat;
785   int nbElems, nbNodes, nbInputNodes;
786   int nodeId/*, triangleId*/;
787   int nbTriangle;
788   int ID, shapeID, ghs3dShapeID;
789   int IdShapeRef = 1;
790   int compoundID =
791     nbShape ? theMeshDS->ShapeToIndex( tabShape[0] ) : theMeshDS->ShapeToIndex( theMeshDS->ShapeToMesh() );
792
793   int *tab, *tabID, *nodeID, *nodeAssigne;
794   double *coord;
795   const SMDS_MeshNode **node;
796
797   tab    = new int[3];
798   //tabID  = new int[nbShape];
799   nodeID = new int[4];
800   coord  = new double[3];
801   node   = new const SMDS_MeshNode*[4];
802
803   TopoDS_Shape aSolid;
804   SMDS_MeshNode * aNewNode;
805   map <int,const SMDS_MeshNode*>::iterator itOnNode;
806   SMDS_MeshElement* aTet;
807 #ifdef _DEBUG_
808   set<int> shapeIDs;
809 #endif
810
811   // Read the file state
812   fileStat = fstat(fileOpen, &status);
813   length   = status.st_size;
814
815   // Mapping the result file into memory
816 #ifdef WNT
817   HANDLE fd = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ,
818                          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
819   HANDLE hMapObject = CreateFileMapping(fd, NULL, PAGE_READONLY,
820                                         0, (DWORD)length, NULL);
821   ptr = ( char* ) MapViewOfFile(hMapObject, FILE_MAP_READ, 0, 0, 0 );
822 #else
823   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
824 #endif
825   mapPtr = ptr;
826
827   ptr      = readMapIntLine(ptr, tab);
828   tetraPtr = ptr;
829
830   nbElems      = tab[0];
831   nbNodes      = tab[1];
832   nbInputNodes = tab[2];
833
834   nodeAssigne = new int[ nbNodes+1 ];
835
836   if (nbShape > 0)
837     aSolid = tabShape[0];
838
839   // Reading the nodeId
840   for (int i=0; i < 4*nbElems; i++)
841     nodeId = strtol(ptr, &ptr, 10);
842
843   MESSAGE("nbInputNodes: "<<nbInputNodes);
844   MESSAGE("nbEnforcedVertices: "<<nbEnforcedVertices);
845   // Reading the nodeCoor and update the nodeMap
846   for (int iNode=1; iNode <= nbNodes; iNode++) {
847     for (int iCoor=0; iCoor < 3; iCoor++)
848       coord[ iCoor ] = strtod(ptr, &ptr);
849     nodeAssigne[ iNode ] = 1;
850     if ( iNode > (nbInputNodes-nbEnforcedVertices) ) {
851       // Creating SMESH nodes
852       // - for enforced vertices
853       // - for vertices of forced edges
854       // - for ghs3d nodes
855       nodeAssigne[ iNode ] = 0;
856       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
857       theGhs3dIdToNodeMap.insert(theGhs3dIdToNodeMap.end(), make_pair( iNode, aNewNode ));
858     }
859   }
860
861   // Reading the number of triangles which corresponds to the number of sub-domains
862   nbTriangle = strtol(ptr, &ptr, 10);
863
864   tabID = new int[nbTriangle];
865   for (int i=0; i < nbTriangle; i++) {
866     tabID[i] = 0;
867     // find the solid corresponding to GHS3D sub-domain following
868     // the technique proposed in GHS3D manual in chapter
869     // "B.4 Subdomain (sub-region) assignment"
870     int nodeId1 = strtol(ptr, &ptr, 10);
871     int nodeId2 = strtol(ptr, &ptr, 10);
872     int nodeId3 = strtol(ptr, &ptr, 10);
873     if ( nbTriangle > 1 ) {
874       const SMDS_MeshNode* n1 = theGhs3dIdToNodeMap[ nodeId1 ];
875       const SMDS_MeshNode* n2 = theGhs3dIdToNodeMap[ nodeId2 ];
876       const SMDS_MeshNode* n3 = theGhs3dIdToNodeMap[ nodeId3 ];
877       try {
878         OCC_CATCH_SIGNALS;
879         tabID[i] = findShapeID( theMesh, n1, n2, n3, toMeshHoles );
880         // -- 0020330: Pb with ghs3d as a submesh
881         // check that found shape is to be meshed
882         if ( tabID[i] > 0 ) {
883           const TopoDS_Shape& foundShape = theMeshDS->IndexToShape( tabID[i] );
884           bool isToBeMeshed = false;
885           for ( int iS = 0; !isToBeMeshed && iS < nbShape; ++iS )
886             isToBeMeshed = foundShape.IsSame( tabShape[ iS ]);
887           if ( !isToBeMeshed )
888             tabID[i] = HOLE_ID;
889         }
890         // END -- 0020330: Pb with ghs3d as a submesh
891 #ifdef _DEBUG_
892         std::cout << i+1 << " subdomain: findShapeID() returns " << tabID[i] << std::endl;
893 #endif
894       } catch ( Standard_Failure ) {
895       } catch (...) {}
896     }
897   }
898
899   shapePtr = ptr;
900
901   if ( nbTriangle <= nbShape ) // no holes
902     toMeshHoles = true; // not avoid creating tetras in holes
903
904   // Associating the tetrahedrons to the shapes
905   shapeID = compoundID;
906   for (int iElem = 0; iElem < nbElems; iElem++) {
907     for (int iNode = 0; iNode < 4; iNode++) {
908       ID = strtol(tetraPtr, &tetraPtr, 10);
909       itOnNode = theGhs3dIdToNodeMap.find(ID);
910       node[ iNode ] = itOnNode->second;
911       nodeID[ iNode ] = ID;
912     }
913     // We always run GHS3D with "to mesh holes'==TRUE but we must not create
914     // tetras within holes depending on hypo option,
915     // so we first check if aTet is inside a hole and then create it 
916     //aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
917     if ( nbTriangle > 1 ) {
918       shapeID = HOLE_ID; // negative shapeID means not to create tetras if !toMeshHoles
919       ghs3dShapeID = strtol(shapePtr, &shapePtr, 10) - IdShapeRef;
920       if ( tabID[ ghs3dShapeID ] == 0 ) {
921         TopAbs_State state;
922         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape, &state);
923         if ( toMeshHoles || state == TopAbs_IN )
924           shapeID = theMeshDS->ShapeToIndex( aSolid );
925         tabID[ ghs3dShapeID ] = shapeID;
926       }
927       else
928         shapeID = tabID[ ghs3dShapeID ];
929     }
930     else if ( nbShape > 1 ) {
931       // Case where nbTriangle == 1 while nbShape == 2 encountered
932       // with compound of 2 boxes and "To mesh holes"==False,
933       // so there are no subdomains specified for each tetrahedron.
934       // Try to guess a solid by a node already bound to shape
935       shapeID = 0;
936       for ( int i=0; i<4 && shapeID==0; i++ ) {
937         if ( nodeAssigne[ nodeID[i] ] == 1 &&
938              node[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE &&
939              node[i]->GetPosition()->GetShapeId() > 1 )
940         {
941           shapeID = node[i]->GetPosition()->GetShapeId();
942         }
943       }
944       if ( shapeID==0 ) {
945         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape);
946         shapeID = theMeshDS->ShapeToIndex( aSolid );
947       }
948     }
949     // set new nodes and tetrahedron onto the shape
950     for ( int i=0; i<4; i++ ) {
951       if ( nodeAssigne[ nodeID[i] ] == 0 ) {
952         if ( shapeID != HOLE_ID )
953           theMeshDS->SetNodeInVolume( node[i], shapeID );
954         nodeAssigne[ nodeID[i] ] = shapeID;
955       }
956     }
957     if ( toMeshHoles || shapeID != HOLE_ID ) {
958       aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
959       theMeshDS->SetMeshElementOnShape( aTet, shapeID );
960     }
961 #ifdef _DEBUG_
962     shapeIDs.insert( shapeID );
963 #endif
964   }
965   // Remove nodes of tetras inside holes if !toMeshHoles
966   if ( !toMeshHoles ) {
967     itOnNode = theGhs3dIdToNodeMap.find( nbInputNodes );
968     for ( ; itOnNode != theGhs3dIdToNodeMap.end(); ++itOnNode) {
969       ID = itOnNode->first;
970       if ( nodeAssigne[ ID ] == HOLE_ID )
971         theMeshDS->RemoveFreeNode( itOnNode->second, 0 );
972     }
973   }
974
975   if ( nbElems )
976     cout << nbElems << " tetrahedrons have been associated to " << nbShape << " shapes" << endl;
977 #ifdef WNT
978   UnmapViewOfFile(mapPtr);
979   CloseHandle(hMapObject);
980   CloseHandle(fd);
981 #else
982   munmap(mapPtr, length);
983 #endif
984   close(fileOpen);
985
986   delete [] tab;
987   delete [] tabID;
988   delete [] nodeID;
989   delete [] coord;
990   delete [] node;
991   delete [] nodeAssigne;
992
993 #ifdef _DEBUG_
994   if ( shapeIDs.size() != nbShape ) {
995     std::cout << "Only " << shapeIDs.size() << " solids of " << nbShape << " found" << std::endl;
996     for (int i=0; i<nbShape; i++) {
997       shapeID = theMeshDS->ShapeToIndex( tabShape[i] );
998       if ( shapeIDs.find( shapeID ) == shapeIDs.end() )
999         std::cout << "  Solid #" << shapeID << " not found" << std::endl;
1000     }
1001   }
1002 #endif
1003
1004   return true;
1005 }
1006
1007 //=======================================================================
1008 //function : readResultFile
1009 //purpose  : 
1010 //=======================================================================
1011
1012 static bool readResultFile(const int                      fileOpen,
1013 #ifdef WNT
1014                            const char*                    fileName,
1015 #endif
1016                            SMESH_Mesh&                    theMesh,
1017                            TopoDS_Shape                   aSolid,
1018                            vector <const SMDS_MeshNode*>& theNodeByGhs3dId,
1019                            int                            nbEnforcedVertices)
1020 {
1021   SMESHDS_Mesh* theMeshDS = theMesh.GetMeshDS();
1022
1023   Kernel_Utils::Localizer loc;
1024   struct stat  status;
1025   size_t       length;
1026
1027   char *ptr, *mapPtr;
1028   char *tetraPtr;
1029   char *shapePtr;
1030
1031   int fileStat;
1032   int nbElems, nbNodes, nbInputNodes;
1033   int nodeId, triangleId;
1034   int nbTriangle;
1035   int ID, shapeID;
1036
1037   int *tab;
1038   double *coord;
1039   const SMDS_MeshNode **node;
1040
1041   tab   = new int[3];
1042   coord = new double[3];
1043   node  = new const SMDS_MeshNode*[4];
1044
1045   SMDS_MeshNode * aNewNode;
1046   map <int,const SMDS_MeshNode*>::iterator IdNode;
1047   SMDS_MeshElement* aTet;
1048
1049   // Read the file state
1050   fileStat = fstat(fileOpen, &status);
1051   length   = status.st_size;
1052
1053   // Mapping the result file into memory
1054 #ifdef WNT
1055   HANDLE fd = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ,
1056                          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1057   HANDLE hMapObject = CreateFileMapping(fd, NULL, PAGE_READONLY,
1058                                         0, (DWORD)length, NULL);
1059   ptr = ( char* ) MapViewOfFile(hMapObject, FILE_MAP_READ, 0, 0, 0 );
1060 #else
1061   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
1062 #endif
1063   mapPtr = ptr;
1064
1065   ptr      = readMapIntLine(ptr, tab);
1066   tetraPtr = ptr;
1067
1068   nbElems      = tab[0];
1069   nbNodes      = tab[1];
1070   nbInputNodes = tab[2];
1071
1072   theNodeByGhs3dId.resize( nbNodes );
1073
1074   // Reading the nodeId
1075   for (int i=0; i < 4*nbElems; i++)
1076     nodeId = strtol(ptr, &ptr, 10);
1077
1078   // Issue 0020682. Avoid creating nodes and tetras at place where
1079   // volumic elements already exist
1080   SMESH_ElementSearcher* elemSearcher = 0;
1081   vector< const SMDS_MeshElement* > foundVolumes;
1082   if ( theMesh.NbVolumes() > 0 )
1083     elemSearcher = SMESH_MeshEditor( &theMesh ).GetElementSearcher();
1084
1085   // Reading the nodeCoor and update the nodeMap
1086   shapeID = theMeshDS->ShapeToIndex( aSolid );
1087   for (int iNode=0; iNode < nbNodes; iNode++) {
1088     for (int iCoor=0; iCoor < 3; iCoor++)
1089       coord[ iCoor ] = strtod(ptr, &ptr);
1090     if ((iNode+1) > (nbInputNodes-nbEnforcedVertices)) {
1091       // Issue 0020682. Avoid creating nodes and tetras at place where
1092       // volumic elements already exist
1093       if ( elemSearcher &&
1094            elemSearcher->FindElementsByPoint( gp_Pnt(coord[0],coord[1],coord[2]),
1095                                               SMDSAbs_Volume, foundVolumes ))
1096       {
1097         theNodeByGhs3dId[ iNode ] = 0;
1098       }
1099       else
1100       {
1101         aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
1102         theMeshDS->SetNodeInVolume( aNewNode, shapeID );
1103         theNodeByGhs3dId[ iNode ] = aNewNode;
1104       }
1105     }
1106   }
1107
1108   // Reading the triangles
1109   nbTriangle = strtol(ptr, &ptr, 10);
1110
1111   for (int i=0; i < 3*nbTriangle; i++)
1112     triangleId = strtol(ptr, &ptr, 10);
1113
1114   shapePtr = ptr;
1115
1116   // Associating the tetrahedrons to the shapes
1117   for (int iElem = 0; iElem < nbElems; iElem++) {
1118     for (int iNode = 0; iNode < 4; iNode++) {
1119       ID = strtol(tetraPtr, &tetraPtr, 10);
1120       node[ iNode ] = theNodeByGhs3dId[ ID-1 ];
1121     }
1122     if ( elemSearcher )
1123     {
1124       // Issue 0020682. Avoid creating nodes and tetras at place where
1125       // volumic elements already exist
1126       if ( !node[1] || !node[0] || !node[2] || !node[3] )
1127         continue;
1128       if ( elemSearcher->FindElementsByPoint(( SMESH_MeshEditor::TNodeXYZ(node[0]) +
1129                                                SMESH_MeshEditor::TNodeXYZ(node[1]) +
1130                                                SMESH_MeshEditor::TNodeXYZ(node[2]) +
1131                                                SMESH_MeshEditor::TNodeXYZ(node[3]) ) / 4.,
1132                                              SMDSAbs_Volume, foundVolumes ))
1133         continue;
1134     }
1135     aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
1136     shapeID = theMeshDS->ShapeToIndex( aSolid );
1137     theMeshDS->SetMeshElementOnShape( aTet, shapeID );
1138   }
1139   if ( nbElems )
1140     cout << nbElems << " tetrahedrons have been associated to " << nbTriangle << " shapes" << endl;
1141 #ifdef WNT
1142   UnmapViewOfFile(mapPtr);
1143   CloseHandle(hMapObject);
1144   CloseHandle(fd);
1145 #else
1146   munmap(mapPtr, length);
1147 #endif
1148   close(fileOpen);
1149
1150   delete [] tab;
1151   delete [] coord;
1152   delete [] node;
1153
1154   return true;
1155 }
1156
1157 //=============================================================================
1158 /*!
1159  *Here we are going to use the GHS3D mesher
1160  */
1161 //=============================================================================
1162
1163 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1164                                 const TopoDS_Shape& theShape)
1165 {
1166   bool Ok(false);
1167   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1168
1169   // we count the number of shapes
1170   // _nbShape = countShape( meshDS, TopAbs_SOLID ); -- 0020330: Pb with ghs3d as a submesh
1171   _nbShape = 0;
1172   TopExp_Explorer expBox ( theShape, TopAbs_SOLID );
1173   for ( ; expBox.More(); expBox.Next() )
1174     _nbShape++;
1175
1176   // create bounding box for every shape inside the compound
1177
1178   int iShape = 0;
1179   TopoDS_Shape* tabShape;
1180   double**      tabBox;
1181   tabShape = new TopoDS_Shape[_nbShape];
1182   tabBox   = new double*[_nbShape];
1183   for (int i=0; i<_nbShape; i++)
1184     tabBox[i] = new double[6];
1185   Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
1186
1187   // TopExp_Explorer expBox (meshDS->ShapeToMesh(), TopAbs_SOLID); -- 0020330:...ghs3d as a submesh
1188   for (expBox.ReInit(); expBox.More(); expBox.Next()) {
1189     tabShape[iShape] = expBox.Current();
1190     Bnd_Box BoundingBox;
1191     BRepBndLib::Add(expBox.Current(), BoundingBox);
1192     BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
1193     tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
1194     tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
1195     tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
1196     iShape++;
1197   }
1198
1199   // a unique working file name
1200   // to avoid access to the same files by eg different users
1201   TCollection_AsciiString aGenericName
1202     = (char*) GHS3DPlugin_Hypothesis::GetFileName(_hyp).c_str();
1203
1204   TCollection_AsciiString aFacesFileName, aPointsFileName, aResultFileName;
1205   TCollection_AsciiString aBadResFileName, aBbResFileName, aLogFileName;
1206   aFacesFileName  = aGenericName + ".faces";  // in faces
1207   aPointsFileName = aGenericName + ".points"; // in points
1208   aResultFileName = aGenericName + ".noboite";// out points and volumes
1209   aBadResFileName = aGenericName + ".boite";  // out bad result
1210   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
1211   aLogFileName    = aGenericName + ".log";    // log
1212
1213   // -----------------
1214   // make input files
1215   // -----------------
1216
1217   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
1218   ofstream aPointsFile ( aPointsFileName.ToCString() , ios::out);
1219
1220   Ok =
1221     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
1222   if (!Ok) {
1223     INFOS( "Can't write into " << aFacesFileName);
1224     return error(SMESH_Comment("Can't write into ") << aFacesFileName);
1225   }
1226   map <int,int> aSmdsToGhs3dIdMap;
1227   map <int,const SMDS_MeshNode*> aGhs3dIdToNodeMap;
1228   map<vector<double>,double> enforcedVertices;
1229   int nbEnforcedVertices = 0;
1230   try {
1231     enforcedVertices = GHS3DPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1232     nbEnforcedVertices = enforcedVertices.size();
1233   }
1234   catch(...) {
1235   }
1236   
1237   SMESH_MesherHelper helper( theMesh );
1238   helper.SetSubShape( theShape );
1239
1240   Ok = writePoints( aPointsFile, helper, aSmdsToGhs3dIdMap, aGhs3dIdToNodeMap, enforcedVertices) &&
1241        writeFaces ( aFacesFile,  meshDS, aSmdsToGhs3dIdMap );
1242
1243   // Write aSmdsToGhs3dIdMap to temp file
1244   TCollection_AsciiString aSmdsToGhs3dIdMapFileName;
1245   aSmdsToGhs3dIdMapFileName = aGenericName + ".ids";  // ids relation
1246   ofstream aIdsFile  ( aSmdsToGhs3dIdMapFileName.ToCString()  , ios::out);
1247   Ok =
1248     aIdsFile.rdbuf()->is_open();
1249   if (!Ok) {
1250     INFOS( "Can't write into " << aSmdsToGhs3dIdMapFileName);
1251     return error(SMESH_Comment("Can't write into ") << aSmdsToGhs3dIdMapFileName);
1252   }
1253   aIdsFile << "Smds Ghs3d" << std::endl;
1254   map <int,int>::const_iterator myit;
1255   for (myit=aSmdsToGhs3dIdMap.begin() ; myit != aSmdsToGhs3dIdMap.end() ; ++myit) {
1256     aIdsFile << myit->first << " " << myit->second << std::endl;
1257   }
1258
1259   aFacesFile.close();
1260   aPointsFile.close();
1261   aIdsFile.close();
1262   
1263   if ( ! Ok ) {
1264     if ( !_keepFiles ) {
1265       removeFile( aFacesFileName );
1266       removeFile( aPointsFileName );
1267       removeFile( aSmdsToGhs3dIdMapFileName );
1268     }
1269     return error(COMPERR_BAD_INPUT_MESH);
1270   }
1271   removeFile( aResultFileName ); // needed for boundary recovery module usage
1272
1273   // -----------------
1274   // run ghs3d mesher
1275   // -----------------
1276
1277   TCollection_AsciiString cmd( (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp ).c_str() );
1278   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
1279   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1280
1281   std::cout << std::endl;
1282   std::cout << "Ghs3d execution..." << std::endl;
1283   std::cout << cmd << std::endl;
1284
1285   system( cmd.ToCString() ); // run
1286
1287   std::cout << std::endl;
1288   std::cout << "End of Ghs3d execution !" << std::endl;
1289
1290   // --------------
1291   // read a result
1292   // --------------
1293
1294   // Mapping the result file
1295
1296   int fileOpen;
1297   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
1298   if ( fileOpen < 0 ) {
1299     std::cout << std::endl;
1300     std::cout << "Can't open the " << aResultFileName.ToCString() << " GHS3D output file" << std::endl;
1301     std::cout << "Log: " << aLogFileName << std::endl;
1302     Ok = false;
1303   }
1304   else {
1305     bool toMeshHoles =
1306       _hyp ? _hyp->GetToMeshHoles(true) : GHS3DPlugin_Hypothesis::DefaultMeshHoles();
1307     Ok = readResultFile( fileOpen,
1308 #ifdef WNT
1309                          aResultFileName.ToCString(),
1310 #endif
1311                          theMesh, tabShape, tabBox, _nbShape, aGhs3dIdToNodeMap,
1312                          toMeshHoles, nbEnforcedVertices );
1313   }
1314
1315   // ---------------------
1316   // remove working files
1317   // ---------------------
1318
1319   if ( Ok )
1320   {
1321     if ( !_keepFiles )
1322       removeFile( aLogFileName );
1323   }
1324   else if ( OSD_File( aLogFileName ).Size() > 0 )
1325   {
1326     // get problem description from the log file
1327     _Ghs2smdsConvertor conv( aGhs3dIdToNodeMap );
1328     storeErrorDescription( aLogFileName, conv );
1329   }
1330   else
1331   {
1332     // the log file is empty
1333     removeFile( aLogFileName );
1334     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
1335     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
1336   }
1337
1338   if ( !_keepFiles ) {
1339     removeFile( aFacesFileName );
1340     removeFile( aPointsFileName );
1341     removeFile( aResultFileName );
1342     removeFile( aBadResFileName );
1343     removeFile( aBbResFileName );
1344     removeFile( aSmdsToGhs3dIdMapFileName );
1345   }
1346   std::cout << "<" << aResultFileName.ToCString() << "> GHS3D output file ";
1347   if ( !Ok )
1348     std::cout << "not ";
1349   std::cout << "treated !" << std::endl;
1350   std::cout << std::endl;
1351
1352   _nbShape = 0;    // re-initializing _nbShape for the next Compute() method call
1353   delete [] tabShape;
1354   delete [] tabBox;
1355
1356   return Ok;
1357 }
1358
1359 //=============================================================================
1360 /*!
1361  *Here we are going to use the GHS3D mesher w/o geometry
1362  */
1363 //=============================================================================
1364 bool GHS3DPlugin_GHS3D::Compute(SMESH_Mesh&         theMesh,
1365                                 SMESH_MesherHelper* aHelper)
1366 {
1367   MESSAGE("GHS3DPlugin_GHS3D::Compute()");
1368
1369   SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
1370   TopoDS_Shape theShape = aHelper->GetSubShape();
1371
1372   // a unique working file name
1373   // to avoid access to the same files by eg different users
1374   TCollection_AsciiString aGenericName
1375     = (char*) GHS3DPlugin_Hypothesis::GetFileName(_hyp).c_str();
1376
1377   TCollection_AsciiString aFacesFileName, aPointsFileName, aResultFileName;
1378   TCollection_AsciiString aBadResFileName, aBbResFileName, aLogFileName;
1379   aFacesFileName  = aGenericName + ".faces";  // in faces
1380   aPointsFileName = aGenericName + ".points"; // in points
1381   aResultFileName = aGenericName + ".noboite";// out points and volumes
1382   aBadResFileName = aGenericName + ".boite";  // out bad result
1383   aBbResFileName  = aGenericName + ".bb";     // out vertex stepsize
1384   aLogFileName    = aGenericName + ".log";    // log
1385
1386   // -----------------
1387   // make input files
1388   // -----------------
1389
1390   ofstream aFacesFile  ( aFacesFileName.ToCString()  , ios::out);
1391   ofstream aPointsFile  ( aPointsFileName.ToCString()  , ios::out);
1392   bool Ok =
1393     aFacesFile.rdbuf()->is_open() && aPointsFile.rdbuf()->is_open();
1394
1395   if (!Ok)
1396     return error( SMESH_Comment("Can't write into ") << aPointsFileName);
1397   
1398   GHS3DPlugin_Hypothesis::TEnforcedVertexValues enforcedVertices;
1399   int nbEnforcedVertices = 0;
1400   try {
1401     enforcedVertices = GHS3DPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1402     nbEnforcedVertices = enforcedVertices.size();
1403   }
1404   catch(...) {
1405   }
1406
1407   vector <const SMDS_MeshNode*> aNodeByGhs3dId;
1408
1409   Ok = (writeFaces ( aFacesFile, meshDS, aNodeByGhs3dId ) &&
1410         writePoints( aPointsFile, meshDS, aNodeByGhs3dId,enforcedVertices));
1411   
1412   aFacesFile.close();
1413   aPointsFile.close();
1414   
1415   if ( ! Ok ) {
1416     if ( !_keepFiles ) {
1417       removeFile( aFacesFileName );
1418       removeFile( aPointsFileName );
1419     }
1420     return error(COMPERR_BAD_INPUT_MESH);
1421   }
1422   removeFile( aResultFileName ); // needed for boundary recovery module usage
1423
1424   // -----------------
1425   // run ghs3d mesher
1426   // -----------------
1427
1428   TCollection_AsciiString cmd =
1429     (char*)GHS3DPlugin_Hypothesis::CommandToRun( _hyp, false ).c_str();
1430   cmd += TCollection_AsciiString(" -f ") + aGenericName;  // file to read
1431   cmd += TCollection_AsciiString(" 1>" ) + aLogFileName;  // dump into file
1432   
1433   system( cmd.ToCString() ); // run
1434
1435   // --------------
1436   // read a result
1437   // --------------
1438   int fileOpen;
1439   fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
1440   if ( fileOpen < 0 ) {
1441     std::cout << std::endl;
1442     std::cout << "Error when opening the " << aResultFileName.ToCString() << " file" << std::endl;
1443     std::cout << "Log: " << aLogFileName << std::endl;
1444     std::cout << std::endl;
1445     Ok = false;
1446   }
1447   else {
1448     Ok = readResultFile( fileOpen,
1449 #ifdef WNT
1450                          aResultFileName.ToCString(),
1451 #endif
1452                          theMesh, theShape ,aNodeByGhs3dId, nbEnforcedVertices );
1453   }
1454   
1455   // ---------------------
1456   // remove working files
1457   // ---------------------
1458
1459   if ( Ok )
1460   {
1461     if ( !_keepFiles )
1462       removeFile( aLogFileName );
1463   }
1464   else if ( OSD_File( aLogFileName ).Size() > 0 )
1465   {
1466     // get problem description from the log file
1467     _Ghs2smdsConvertor conv( aNodeByGhs3dId );
1468     storeErrorDescription( aLogFileName, conv );
1469   }
1470   else {
1471     // the log file is empty
1472     removeFile( aLogFileName );
1473     INFOS( "GHS3D Error, command '" << cmd.ToCString() << "' failed" );
1474     error(COMPERR_ALGO_FAILED, "ghs3d: command not found" );
1475   }
1476
1477   if ( !_keepFiles )
1478   {
1479     removeFile( aFacesFileName );
1480     removeFile( aPointsFileName );
1481     removeFile( aResultFileName );
1482     removeFile( aBadResFileName );
1483     removeFile( aBbResFileName );
1484   }
1485   
1486   return Ok;
1487 }
1488
1489 //================================================================================
1490 /*!
1491  * \brief Provide human readable text by error code reported by ghs3d
1492  */
1493 //================================================================================
1494
1495 static string translateError(const int errNum)
1496 {
1497   switch ( errNum ) {
1498   case 0:
1499     return "The surface mesh includes a face of type other than edge, "
1500       "triangle or quadrilateral. This face type is not supported.";
1501   case 1:
1502     return "Not enough memory for the face table.";
1503   case 2:
1504     return "Not enough memory.";
1505   case 3:
1506     return "Not enough memory.";
1507   case 4:
1508     return "Face is ignored.";
1509   case 5:
1510     return "End of file. Some data are missing in the file.";
1511   case 6:
1512     return "Read error on the file. There are wrong data in the file.";
1513   case 7:
1514     return "the metric file is inadequate (dimension other than 3).";
1515   case 8:
1516     return "the metric file is inadequate (values not per vertices).";
1517   case 9:
1518     return "the metric file contains more than one field.";
1519   case 10:
1520     return "the number of values in the \".bb\" (metric file) is incompatible with the expected"
1521       "value of number of mesh vertices in the \".noboite\" file.";
1522   case 12:
1523     return "Too many sub-domains.";
1524   case 13:
1525     return "the number of vertices is negative or null.";
1526   case 14:
1527     return "the number of faces is negative or null.";
1528   case 15:
1529     return "A face has a null vertex.";
1530   case 22:
1531     return "incompatible data.";
1532   case 131:
1533     return "the number of vertices is negative or null.";
1534   case 132:
1535     return "the number of vertices is negative or null (in the \".mesh\" file).";
1536   case 133:
1537     return "the number of faces is negative or null.";
1538   case 1000:
1539     return "A face appears more than once in the input surface mesh.";
1540   case 1001:
1541     return "An edge appears more than once in the input surface mesh.";
1542   case 1002:
1543     return "A face has a vertex negative or null.";
1544   case 1003:
1545     return "NOT ENOUGH MEMORY.";
1546   case 2000:
1547     return "Not enough available memory.";
1548   case 2002:
1549     return "Some initial points cannot be inserted. The surface mesh is probably very bad "
1550       "in terms of quality or the input list of points is wrong.";
1551   case 2003:
1552     return "Some vertices are too close to one another or coincident.";
1553   case 2004:
1554     return "Some vertices are too close to one another or coincident.";
1555   case 2012:
1556     return "A vertex cannot be inserted.";
1557   case 2014:
1558     return "There are at least two points considered as coincident.";
1559   case 2103:
1560     return "Some vertices are too close to one another or coincident.";
1561   case 3000:
1562     return "The surface mesh regeneration step has failed.";
1563   case 3009:
1564     return "Constrained edge cannot be enforced.";
1565   case 3019:
1566     return "Constrained face cannot be enforced.";
1567   case 3029:
1568     return "Missing faces.";
1569   case 3100:
1570     return "No guess to start the definition of the connected component(s).";
1571   case 3101:
1572     return "The surface mesh includes at least one hole. The domain is not well defined.";
1573   case 3102:
1574     return "Impossible to define a component.";
1575   case 3103:
1576     return "The surface edge intersects another surface edge.";
1577   case 3104:
1578     return "The surface edge intersects the surface face.";
1579   case 3105:
1580     return "One boundary point lies within a surface face.";
1581   case 3106:
1582     return "One surface edge intersects a surface face.";
1583   case 3107:
1584     return "One boundary point lies within a surface edge.";
1585   case 3108:
1586     return "Insufficient memory ressources detected due to a bad quality surface mesh leading "
1587       "to too many swaps.";
1588   case 3109:
1589     return "Edge is unique (i.e., bounds a hole in the surface).";
1590   case 3122:
1591     return "Presumably, the surface mesh is not compatible with the domain being processed.";
1592   case 3123:
1593     return "Too many components, too many sub-domain.";
1594   case 3209:
1595     return "The surface mesh includes at least one hole. "
1596       "Therefore there is no domain properly defined.";
1597   case 3300:
1598     return "Statistics.";
1599   case 3400:
1600     return "Statistics.";
1601   case 3500:
1602     return "Warning, it is dramatically tedious to enforce the boundary items.";
1603   case 4000:
1604     return "Not enough memory at this time, nevertheless, the program continues. "
1605       "The expected mesh will be correct but not really as large as required.";
1606   case 4002:
1607     return "see above error code, resulting quality may be poor.";
1608   case 4003:
1609     return "Not enough memory at this time, nevertheless, the program continues (warning).";
1610   case 8000:
1611     return "Unknown face type.";
1612   case 8005:
1613   case 8006:
1614     return "End of file. Some data are missing in the file.";
1615   case 9000:
1616     return "A too small volume element is detected.";
1617   case 9001:
1618     return "There exists at least a null or negative volume element.";
1619   case 9002:
1620     return "There exist null or negative volume elements.";
1621   case 9003:
1622     return "A too small volume element is detected. A face is considered being degenerated.";
1623   case 9100:
1624     return "Some element is suspected to be very bad shaped or wrong.";
1625   case 9102:
1626     return "A too bad quality face is detected. This face is considered degenerated.";
1627   case 9112:
1628     return "A too bad quality face is detected. This face is degenerated.";
1629   case 9122:
1630     return "Presumably, the surface mesh is not compatible with the domain being processed.";
1631   case 9999:
1632     return "Abnormal error occured, contact hotline.";
1633   case 23600:
1634     return "Not enough memory for the face table.";
1635   case 23601:
1636     return "The algorithm cannot run further. "
1637       "The surface mesh is probably very bad in terms of quality.";
1638   case 23602:
1639     return "Bad vertex number.";
1640   }
1641   return "";
1642 }
1643
1644 //================================================================================
1645 /*!
1646  * \brief Retrieve from a string given number of integers
1647  */
1648 //================================================================================
1649
1650 static char* getIds( char* ptr, int nbIds, vector<int>& ids )
1651 {
1652   ids.clear();
1653   ids.reserve( nbIds );
1654   while ( nbIds )
1655   {
1656     while ( !isdigit( *ptr )) ++ptr;
1657     if ( ptr[-1] == '-' ) --ptr;
1658     ids.push_back( strtol( ptr, &ptr, 10 ));
1659     --nbIds;
1660   }
1661   return ptr;
1662 }
1663
1664 //================================================================================
1665 /*!
1666  * \brief Retrieve problem description form a log file
1667  *  \retval bool - always false
1668  */
1669 //================================================================================
1670
1671 bool GHS3DPlugin_GHS3D::storeErrorDescription(const TCollection_AsciiString& logFile,
1672                                               const _Ghs2smdsConvertor &     toSmdsConvertor )
1673 {
1674   // open file
1675 #ifdef WNT
1676   int file = ::_open (logFile.ToCString(), _O_RDONLY|_O_BINARY);
1677 #else
1678   int file = ::open (logFile.ToCString(), O_RDONLY);
1679 #endif
1680   if ( file < 0 )
1681     return error( SMESH_Comment("See ") << logFile << " for problem description");
1682
1683   // get file size
1684 //   struct stat status;
1685 //   fstat(file, &status);
1686 //   size_t length = status.st_size;
1687   off_t length = lseek( file, 0, SEEK_END);
1688   lseek( file, 0, SEEK_SET);
1689
1690   // read file
1691   vector< char > buf( length );
1692   int nBytesRead = ::read (file, & buf[0], length);
1693   ::close (file);
1694   char* ptr = & buf[0];
1695   char* bufEnd = ptr + nBytesRead;
1696
1697   SMESH_Comment errDescription;
1698
1699   enum { NODE = 1, EDGE, TRIA, VOL, ID = 1 };
1700
1701   // look for errors "ERR #"
1702
1703   set<string> foundErrorStr; // to avoid reporting same error several times
1704   set<int>    elemErrorNums; // not to report different types of errors with bad elements
1705   while ( ++ptr < bufEnd )
1706   {
1707     if ( strncmp( ptr, "ERR ", 4 ) != 0 )
1708       continue;
1709
1710     list<const SMDS_MeshElement*> badElems;
1711     vector<int> nodeIds;
1712
1713     ptr += 4;
1714     char* errBeg = ptr;
1715     int   errNum = strtol(ptr, &ptr, 10);
1716     switch ( errNum ) { // we treat errors enumerated in [SALOME platform 0019316] issue
1717     case 0015:
1718       // The face number (numfac) with vertices (f 1, f 2, f 3) has a null vertex.
1719       ptr = getIds(ptr, NODE, nodeIds);
1720       ptr = getIds(ptr, TRIA, nodeIds);
1721       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1722       break;
1723     case 1000: // ERR  1000 :  1 3 2
1724       // Face (f 1, f 2, f 3) appears more than once in the input surface mesh.
1725       ptr = getIds(ptr, TRIA, nodeIds);
1726       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1727       break;
1728     case 1001:
1729       // Edge (e1, e2) appears more than once in the input surface mesh
1730       ptr = getIds(ptr, EDGE, nodeIds);
1731       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1732       break;
1733     case 1002:
1734       // Face (f 1, f 2, f 3) has a vertex negative or null
1735       ptr = getIds(ptr, TRIA, nodeIds);
1736       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1737       break;
1738     case 2004:
1739       // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
1740       ptr = getIds(ptr, NODE, nodeIds);
1741       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1742       ptr = getIds(ptr, NODE, nodeIds);
1743       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1744       break;
1745     case 2012:
1746       // Vertex v1 cannot be inserted (warning).
1747       ptr = getIds(ptr, NODE, nodeIds);
1748       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1749       break;
1750     case 2014:
1751       // There are at least two points whose distance is dist, i.e., considered as coincident
1752     case 2103: // ERR  2103 :  16 WITH  3
1753       // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
1754       ptr = getIds(ptr, NODE, nodeIds);
1755       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1756       ptr = getIds(ptr, NODE, nodeIds);
1757       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1758       break;
1759     case 3009:
1760       // Constrained edge (e1, e2) cannot be enforced (warning).
1761       ptr = getIds(ptr, EDGE, nodeIds);
1762       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1763       break;
1764     case 3019:
1765       // Constrained face (f 1, f 2, f 3) cannot be enforced
1766       ptr = getIds(ptr, TRIA, nodeIds);
1767       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1768       break;
1769     case 3103: // ERR  3103 :  1 2 WITH  7 3
1770       // The surface edge (e1, e2) intersects another surface edge (e3, e4)
1771       ptr = getIds(ptr, EDGE, nodeIds);
1772       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1773       ptr = getIds(ptr, EDGE, nodeIds);
1774       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1775       break;
1776     case 3104: // ERR  3104 :  9 10 WITH  1 2 3
1777       // The surface edge (e1, e2) intersects the surface face (f 1, f 2, f 3)
1778       ptr = getIds(ptr, EDGE, nodeIds);
1779       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1780       ptr = getIds(ptr, TRIA, nodeIds);
1781       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1782       break;
1783     case 3105: // ERR  3105 :  8 IN  2 3 5
1784       // One boundary point (say p1) lies within a surface face (f 1, f 2, f 3)
1785       ptr = getIds(ptr, NODE, nodeIds);
1786       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1787       ptr = getIds(ptr, TRIA, nodeIds);
1788       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1789       break;
1790     case 3106:
1791       // One surface edge (say e1, e2) intersects a surface face (f 1, f 2, f 3)
1792       ptr = getIds(ptr, EDGE, nodeIds);
1793       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1794       ptr = getIds(ptr, TRIA, nodeIds);
1795       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1796       break;
1797     case 3107: // ERR  3107 :  2 IN  4 1
1798       // One boundary point (say p1) lies within a surface edge (e1, e2) (stop).
1799       ptr = getIds(ptr, NODE, nodeIds);
1800       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1801       ptr = getIds(ptr, EDGE, nodeIds);
1802       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1803       break;
1804     case 3109: // ERR  3109 :  EDGE  5 6 UNIQUE
1805       // Edge (e1, e2) is unique (i.e., bounds a hole in the surface)
1806       ptr = getIds(ptr, EDGE, nodeIds);
1807       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1808       break;
1809     case 9000: // ERR  9000 
1810       //  ELEMENT  261 WITH VERTICES :  7 396 -8 242 
1811       //  VOLUME   : -1.11325045E+11 W.R.T. EPSILON   0.
1812       // A too small volume element is detected. Are reported the index of the element,
1813       // its four vertex indices, its volume and the tolerance threshold value
1814       ptr = getIds(ptr, ID, nodeIds);
1815       ptr = getIds(ptr, VOL, nodeIds);
1816       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1817       // even if all nodes found, volume it most probably invisible,
1818       // add its faces to demenstrate it anyhow
1819       {
1820         vector<int> faceNodes( nodeIds.begin(), --nodeIds.end() ); // 012
1821         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1822         faceNodes[2] = nodeIds[3]; // 013
1823         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1824         faceNodes[1] = nodeIds[2]; // 023
1825         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1826         faceNodes[0] = nodeIds[1]; // 123
1827         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
1828       }
1829       break;
1830     case 9001: // ERR  9001
1831       //  %% NUMBER OF NEGATIVE VOLUME TETS  :  1 
1832       //  %% THE LARGEST NEGATIVE TET        :   1.75376581E+11 
1833       //  %%  NUMBER OF NULL VOLUME TETS     :  0
1834       // There exists at least a null or negative volume element
1835       break;
1836     case 9002:
1837       // There exist n null or negative volume elements
1838       break;
1839     case 9003:
1840       // A too small volume element is detected
1841       break;
1842     case 9102:
1843       // A too bad quality face is detected. This face is considered degenerated,
1844       // its index, its three vertex indices together with its quality value are reported
1845       break; // same as next
1846     case 9112: // ERR  9112 
1847       //  FACE   2 WITH VERTICES :  4 2 5 
1848       //  SMALL INRADIUS :   0.
1849       // A too bad quality face is detected. This face is degenerated,
1850       // its index, its three vertex indices together with its inradius are reported
1851       ptr = getIds(ptr, ID, nodeIds);
1852       ptr = getIds(ptr, TRIA, nodeIds);
1853       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1854       // add triangle edges as it most probably has zero area and hence invisible
1855       {
1856         vector<int> edgeNodes(2);
1857         edgeNodes[0] = nodeIds[0]; edgeNodes[1] = nodeIds[1]; // 0-1
1858         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1859         edgeNodes[1] = nodeIds[2]; // 0-2
1860         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1861         edgeNodes[0] = nodeIds[1]; // 1-2
1862         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1863       }
1864       break;
1865     }
1866
1867     bool isNewError = foundErrorStr.insert( string( errBeg, ptr )).second;
1868     if ( !isNewError )
1869       continue; // not to report same error several times
1870
1871 //     const SMDS_MeshElement* nullElem = 0;
1872 //     bool allElemsOk = ( find( badElems.begin(), badElems.end(), nullElem) == badElems.end());
1873
1874 //     if ( allElemsOk && !badElems.empty() && !elemErrorNums.empty() ) {
1875 //       bool oneMoreErrorType = elemErrorNums.insert( errNum ).second;
1876 //       if ( oneMoreErrorType )
1877 //         continue; // not to report different types of errors with bad elements
1878 //     }
1879
1880     // store bad elements
1881     //if ( allElemsOk ) {
1882       list<const SMDS_MeshElement*>::iterator elem = badElems.begin();
1883       for ( ; elem != badElems.end(); ++elem )
1884         addBadInputElement( *elem );
1885       //}
1886
1887     // make error text
1888     string text = translateError( errNum );
1889     if ( errDescription.find( text ) == text.npos ) {
1890       if ( !errDescription.empty() )
1891         errDescription << "\n";
1892       errDescription << text;
1893     }
1894
1895   } // end while
1896
1897   if ( errDescription.empty() ) { // no errors found
1898     char msg[] = "connection to server failed";
1899     if ( search( &buf[0], bufEnd, msg, msg + strlen(msg)) != bufEnd )
1900       errDescription << "Licence problems.";
1901   }
1902
1903   if ( errDescription.empty() )
1904     errDescription << "See " << logFile << " for problem description";
1905   else
1906     errDescription << "\nSee " << logFile << " for more information";
1907
1908   return error( errDescription );
1909 }
1910
1911 //================================================================================
1912 /*!
1913  * \brief Creates _Ghs2smdsConvertor
1914  */
1915 //================================================================================
1916
1917 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const map <int,const SMDS_MeshNode*> & ghs2NodeMap)
1918   :_ghs2NodeMap( & ghs2NodeMap ), _nodeByGhsId( 0 )
1919 {
1920 }
1921
1922 //================================================================================
1923 /*!
1924  * \brief Creates _Ghs2smdsConvertor
1925  */
1926 //================================================================================
1927
1928 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const vector <const SMDS_MeshNode*> &  nodeByGhsId)
1929   : _ghs2NodeMap( 0 ), _nodeByGhsId( &nodeByGhsId )
1930 {
1931 }
1932
1933 //================================================================================
1934 /*!
1935  * \brief Return SMDS element by ids of GHS3D nodes
1936  */
1937 //================================================================================
1938
1939 const SMDS_MeshElement* _Ghs2smdsConvertor::getElement(const vector<int>& ghsNodes) const
1940 {
1941   size_t nbNodes = ghsNodes.size();
1942   vector<const SMDS_MeshNode*> nodes( nbNodes, 0 );
1943   for ( size_t i = 0; i < nbNodes; ++i ) {
1944     int ghsNode = ghsNodes[ i ];
1945     if ( _ghs2NodeMap ) {
1946       map <int,const SMDS_MeshNode*>::const_iterator in = _ghs2NodeMap->find( ghsNode);
1947       if ( in == _ghs2NodeMap->end() )
1948         return 0;
1949       nodes[ i ] = in->second;
1950     }
1951     else {
1952       if ( ghsNode < 1 || ghsNode > _nodeByGhsId->size() )
1953         return 0;
1954       nodes[ i ] = (*_nodeByGhsId)[ ghsNode-1 ];
1955     }
1956   }
1957   if ( nbNodes == 1 )
1958     return nodes[0];
1959
1960   if ( nbNodes == 2 ) {
1961     const SMDS_MeshElement* edge= SMDS_Mesh::FindEdge( nodes[0], nodes[1] );
1962     if ( !edge )
1963       edge = new SMDS_MeshEdge( nodes[0], nodes[1] );
1964     return edge;
1965   }
1966   if ( nbNodes == 3 ) {
1967     const SMDS_MeshElement* face = SMDS_Mesh::FindFace( nodes );
1968     if ( !face )
1969       face = new SMDS_FaceOfNodes( nodes[0], nodes[1], nodes[2] );
1970     return face;
1971   }
1972   if ( nbNodes == 4 )
1973     return new SMDS_VolumeOfNodes( nodes[0], nodes[1], nodes[2], nodes[3] );
1974
1975   return 0;
1976 }
1977
1978
1979 //=============================================================================
1980 /*!
1981  *  
1982  */
1983 //=============================================================================
1984 bool GHS3DPlugin_GHS3D::Evaluate(SMESH_Mesh& aMesh,
1985                                  const TopoDS_Shape& aShape,
1986                                  MapShapeNbElems& aResMap)
1987 {
1988   int nbtri = 0, nbqua = 0;
1989   double fullArea = 0.0;
1990   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
1991     TopoDS_Face F = TopoDS::Face( exp.Current() );
1992     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
1993     MapShapeNbElemsItr anIt = aResMap.find(sm);
1994     if( anIt==aResMap.end() ) {
1995       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1996       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
1997                                             "Submesh can not be evaluated",this));
1998       return false;
1999     }
2000     std::vector<int> aVec = (*anIt).second;
2001     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
2002     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2003     GProp_GProps G;
2004     BRepGProp::SurfaceProperties(F,G);
2005     double anArea = G.Mass();
2006     fullArea += anArea;
2007   }
2008
2009   // collect info from edges
2010   int nb0d_e = 0, nb1d_e = 0;
2011   bool IsQuadratic = false;
2012   bool IsFirst = true;
2013   TopTools_MapOfShape tmpMap;
2014   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2015     TopoDS_Edge E = TopoDS::Edge(exp.Current());
2016     if( tmpMap.Contains(E) )
2017       continue;
2018     tmpMap.Add(E);
2019     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
2020     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
2021     std::vector<int> aVec = (*anIt).second;
2022     nb0d_e += aVec[SMDSEntity_Node];
2023     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
2024     if(IsFirst) {
2025       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
2026       IsFirst = false;
2027     }
2028   }
2029   tmpMap.Clear();
2030
2031   double ELen = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
2032
2033   GProp_GProps G;
2034   BRepGProp::VolumeProperties(aShape,G);
2035   double aVolume = G.Mass();
2036   double tetrVol = 0.1179*ELen*ELen*ELen;
2037   double CoeffQuality = 0.9;
2038   int nbVols = int(aVolume/tetrVol/CoeffQuality);
2039   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
2040   int nb1d_in = (int) ( nbVols*6 - nb1d_e - nb1d_f ) / 5;
2041   std::vector<int> aVec(SMDSEntity_Last);
2042   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2043   if( IsQuadratic ) {
2044     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
2045     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
2046     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
2047   }
2048   else {
2049     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
2050     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
2051     aVec[SMDSEntity_Pyramid] = nbqua;
2052   }
2053   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
2054   aResMap.insert(std::make_pair(sm,aVec));
2055
2056   return true;
2057 }
2058