Salome HOME
0023460: EDF - problem with return of MG-HYBRID
[plugins/hybridplugin.git] / src / HYBRIDPlugin / HYBRIDPlugin_HYBRID.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // ---
21 // File   : HYBRIDPlugin_HYBRID.cxx
22 // Author : Christian VAN WAMBEKE (CEA) (from GHS3D plugin V730)
23 // ---
24 //
25 #include "HYBRIDPlugin_HYBRID.hxx"
26 #include "HYBRIDPlugin_Hypothesis.hxx"
27 #include "MG_HYBRID_API.hxx"
28
29 #include <SMDS_FaceOfNodes.hxx>
30 #include <SMDS_LinearEdge.hxx>
31 #include <SMDS_VolumeOfNodes.hxx>
32 #include <SMESHDS_Group.hxx>
33 #include <SMESHDS_Mesh.hxx>
34 #include <SMESH_Comment.hxx>
35 #include <SMESH_File.hxx>
36 #include <SMESH_Group.hxx>
37 #include <SMESH_HypoFilter.hxx>
38 #include <SMESH_Mesh.hxx>
39 #include <SMESH_MeshAlgos.hxx>
40 #include <SMESH_MeshEditor.hxx>
41 #include <SMESH_MesherHelper.hxx>
42 #include <SMESH_ProxyMesh.hxx>
43 #include <SMESH_subMeshEventListener.hxx>
44
45 #include <BRepAdaptor_Surface.hxx>
46 #include <BRepBndLib.hxx>
47 #include <BRepBuilderAPI_MakeVertex.hxx>
48 #include <BRepClass3d.hxx>
49 #include <BRepClass3d_SolidClassifier.hxx>
50 #include <BRepExtrema_DistShapeShape.hxx>
51 #include <BRepGProp.hxx>
52 #include <BRepTools.hxx>
53 #include <BRep_Tool.hxx>
54 #include <Bnd_Box.hxx>
55 #include <GProp_GProps.hxx>
56 #include <GeomAPI_ProjectPointOnSurf.hxx>
57 #include <Precision.hxx>
58 #include <Standard_ErrorHandler.hxx>
59 #include <Standard_Failure.hxx>
60 #include <Standard_ProgramError.hxx>
61 #include <TopExp.hxx>
62 #include <TopExp_Explorer.hxx>
63 #include <TopTools_IndexedMapOfShape.hxx>
64 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
66 #include <TopoDS.hxx>
67 #include <TopoDS_Shell.hxx>
68 #include <TopoDS_Solid.hxx>
69
70 #include <Basics_Utils.hxx>
71 #include <utilities.h>
72
73 #include <algorithm>
74
75 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
76
77 #ifndef GMFVERSION
78 #define GMFVERSION GmfDouble
79 #endif
80 #define GMFDIMENSION 3
81
82 #define HOLE_ID -1
83
84 typedef const std::list<const SMDS_MeshFace*> TTriaList;
85
86 static const char theDomainGroupNamePrefix[] = "Domain_";
87
88 static void removeFile( const std::string& fileName )
89 {
90   try {
91     SMESH_File( fileName ).remove();
92   }
93   catch ( ... ) {
94     MESSAGE("Can't remove file: " << fileName << " ; file does not exist or permission denied");
95   }
96 }
97
98 //=============================================================================
99 /*!
100  *  
101  */
102 //=============================================================================
103
104 HYBRIDPlugin_HYBRID::HYBRIDPlugin_HYBRID(int hypId, int studyId, SMESH_Gen* gen)
105   : SMESH_3D_Algo(hypId, studyId, gen)
106 {
107   _name = Name();
108   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
109   _onlyUnaryInput = true; // Compute() will be called on each solid
110   _iShape=0;
111   _nbShape=0;
112   _compatibleHypothesis.push_back( HYBRIDPlugin_Hypothesis::GetHypType());
113   _requireShape = false; // can work without shape_studyId
114
115   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
116   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
117   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
118
119   myStudy = NULL;
120   myStudy = aStudyMgr->GetStudyByID(_studyId);
121   
122   _computeCanceled = false;
123 }
124
125 //=============================================================================
126 /*!
127  *  
128  */
129 //=============================================================================
130
131 HYBRIDPlugin_HYBRID::~HYBRIDPlugin_HYBRID()
132 {
133 }
134
135 //=============================================================================
136 /*!
137  *  
138  */
139 //=============================================================================
140
141 bool HYBRIDPlugin_HYBRID::CheckHypothesis ( SMESH_Mesh&         aMesh,
142                                           const TopoDS_Shape& aShape,
143                                           Hypothesis_Status&  aStatus )
144 {
145   aStatus = SMESH_Hypothesis::HYP_OK;
146
147   _hyp = 0;
148   _keepFiles = false;
149   _removeLogOnSuccess = true;
150   _logInStandardOutput = false;
151
152   const std::list <const SMESHDS_Hypothesis * >& hyps =
153     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
154   std::list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
155   for ( ; h != hyps.end(); ++h )
156   {
157     if ( !_hyp )
158       _hyp = dynamic_cast< const HYBRIDPlugin_Hypothesis*> ( *h );
159   }
160   if ( _hyp )
161   {
162     _keepFiles = _hyp->GetKeepFiles();
163     _removeLogOnSuccess = _hyp->GetRemoveLogOnSuccess();
164     _logInStandardOutput = _hyp->GetStandardOutputLog();
165   }
166
167   return true;
168 }
169
170
171 //=======================================================================
172 //function : entryToShape
173 //purpose  : 
174 //=======================================================================
175
176 TopoDS_Shape HYBRIDPlugin_HYBRID::entryToShape(std::string entry)
177 {
178   if ( myStudy->_is_nil() )
179     throw SALOME_Exception("MG-HYBRID plugin can't work w/o publishing in the study");
180   GEOM::GEOM_Object_var aGeomObj;
181   TopoDS_Shape S = TopoDS_Shape();
182   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
183   if (!aSObj->_is_nil() ) {
184     CORBA::Object_var obj = aSObj->GetObject();
185     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
186     aSObj->UnRegister();
187   }
188   if ( !aGeomObj->_is_nil() )
189     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
190   return S;
191 }
192
193 //=======================================================================
194 //function : addElemInMeshGroup
195 //purpose  : Update or create groups in mesh
196 //=======================================================================
197
198 static void addElemInMeshGroup(SMESH_Mesh*             theMesh,
199                                const SMDS_MeshElement* anElem,
200                                std::string&            groupName,
201                                std::set<std::string>&  groupsToRemove)
202 {
203   if ( !anElem ) return; // issue 0021776
204
205   bool groupDone = false;
206   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
207   while (grIt->more()) {
208     SMESH_Group * group = grIt->next();
209     if ( !group ) continue;
210     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
211     if ( !groupDS ) continue;
212     if ( groupDS->GetType()==anElem->GetType() &&groupName.compare(group->GetName())==0) {
213       SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
214       aGroupDS->SMDSGroup().Add(anElem);
215       groupDone = true;
216       break;
217     }
218   }
219   
220   if (!groupDone)
221   {
222     int groupId;
223     SMESH_Group* aGroup = theMesh->AddGroup(anElem->GetType(), groupName.c_str(), groupId);
224     aGroup->SetName( groupName.c_str() );
225     SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
226     aGroupDS->SMDSGroup().Add(anElem);
227     groupDone = true;
228   }
229   if (!groupDone)
230     throw SALOME_Exception(LOCALIZED("A given element was not added to a group"));
231 }
232
233
234 //=======================================================================
235 //function : updateMeshGroups
236 //purpose  : Update or create groups in mesh
237 //=======================================================================
238
239 static void updateMeshGroups(SMESH_Mesh* theMesh, std::set<std::string> groupsToRemove)
240 {
241   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
242   while (grIt->more()) {
243     SMESH_Group * group = grIt->next();
244     if ( !group ) continue;
245     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
246     if ( !groupDS ) continue;
247     std::string currentGroupName = (std::string)group->GetName();
248     if (groupDS->IsEmpty() && groupsToRemove.find(currentGroupName) != groupsToRemove.end()) {
249       // Previous group created by enforced elements
250       theMesh->RemoveGroup(groupDS->GetID());
251     }
252   }
253 }
254
255 //=======================================================================
256 //function : removeEmptyGroupsOfDomains
257 //purpose  : remove empty groups named "Domain_nb" created due to
258 //           "To make groups of domains" option.
259 //=======================================================================
260
261 static void removeEmptyGroupsOfDomains(SMESH_Mesh* mesh,
262                                        bool        notEmptyAsWell = false)
263 {
264   const char* refName = theDomainGroupNamePrefix;
265   const size_t refLen = strlen( theDomainGroupNamePrefix );
266
267   std::list<int> groupIDs = mesh->GetGroupIds();
268   std::list<int>::const_iterator id = groupIDs.begin();
269   for ( ; id != groupIDs.end(); ++id )
270   {
271     SMESH_Group* group = mesh->GetGroup( *id );
272     if ( !group || ( !group->GetGroupDS()->IsEmpty() && !notEmptyAsWell ))
273       continue;
274     const char* name = group->GetName();
275     char* end;
276     // check the name
277     if ( strncmp( name, refName, refLen ) == 0 && // starts from refName;
278          isdigit( *( name + refLen )) &&          // refName is followed by a digit;
279          strtol( name + refLen, &end, 10) >= 0 && // there are only digits ...
280          *end == '\0')                            // ... till a string end.
281     {
282       mesh->RemoveGroup( *id );
283     }
284   }
285 }
286
287 //================================================================================
288 /*!
289  * \brief Create the groups corresponding to domains
290  */
291 //================================================================================
292
293 static void makeDomainGroups( std::vector< std::vector< const SMDS_MeshElement* > >& elemsOfDomain,
294                               SMESH_MesherHelper*                                    theHelper)
295 {
296   for ( size_t iDomain = 0; iDomain < elemsOfDomain.size(); ++iDomain )
297   {
298     std::vector< const SMDS_MeshElement* > & elems = elemsOfDomain[ iDomain ];
299     if ( elems.empty() ) continue;
300
301     // find existing groups
302     std::vector< SMESH_Group* > groupOfType( SMDSAbs_NbElementTypes, (SMESH_Group*)NULL );
303     const std::string domainName = ( SMESH_Comment( theDomainGroupNamePrefix ) << iDomain );
304     SMESH_Mesh::GroupIteratorPtr groupIt = theHelper->GetMesh()->GetGroups();
305     while ( groupIt->more() )
306     {
307       SMESH_Group* group = groupIt->next();
308       if ( domainName == group->GetName() &&
309            dynamic_cast< SMESHDS_Group* >( group->GetGroupDS()) )
310         groupOfType[ group->GetGroupDS()->GetType() ] = group;
311     }
312     // create and fill the groups
313     size_t iElem = 0;
314     int groupID;
315     do
316     {
317       SMESH_Group* group = groupOfType[ elems[ iElem ]->GetType() ];
318       if ( !group )
319         group = theHelper->GetMesh()->AddGroup( elems[ iElem ]->GetType(),
320                                                 domainName.c_str(), groupID );
321       SMDS_MeshGroup& groupDS =
322         static_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
323
324       while ( iElem < elems.size() && groupDS.Add( elems[iElem] ))
325         ++iElem;
326
327     } while ( iElem < elems.size() );
328   }
329 }
330
331 //=======================================================================
332 //function : readGMFFile
333 //purpose  : read GMF file w/o geometry associated to mesh
334 //=======================================================================
335
336 static bool readGMFFile(MG_HYBRID_API*                          MGOutput,
337                         const char*                             theFile,
338                         HYBRIDPlugin_HYBRID*                    theAlgo,
339                         SMESH_MesherHelper*                     theHelper,
340                         std::vector <const SMDS_MeshNode*> &    theNodeByHybridId,
341                         std::vector <const SMDS_MeshElement*> & theFaceByHybridId,
342                         std::map<const SMDS_MeshNode*,int> &    theNodeToHybridIdMap,
343                         std::vector<std::string> &              aNodeGroupByHybridId,
344                         std::vector<std::string> &              anEdgeGroupByHybridId,
345                         std::vector<std::string> &              aFaceGroupByHybridId,
346                         std::set<std::string> &                 groupsToRemove,
347                         bool                                    toMakeGroupsOfDomains=false,
348                         bool                                    toMeshHoles=true)
349 {
350   std::string tmpStr;
351   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
352   const bool hasGeom = ( theHelper->GetMesh()->HasShapeToMesh() );
353
354   // if imprinting, the original mesh faces are modified
355   // => we clear all the faces to retrieve them from Hybrid output mesh.
356   std::vector<int> facesWithImprinting;
357   if (theAlgo->getHyp()) 
358     facesWithImprinting = theAlgo->getHyp()->GetFacesWithImprinting();
359
360   if ( ! facesWithImprinting.empty() ) {
361 #ifdef _DEBUG_
362       std::cout << "Imprinting => Clear original mesh" << std::endl;
363 #endif
364       SMDS_ElemIteratorPtr eIt = theMeshDS->elementsIterator();
365       while( eIt->more() )
366         theMeshDS->RemoveFreeElement( eIt->next(), /*sm=*/0 );
367       SMDS_NodeIteratorPtr nIt = theMeshDS->nodesIterator();
368       while ( nIt->more() )
369         theMeshDS->RemoveFreeNode( nIt->next(), /*sm=*/0 );
370
371       theNodeByHybridId.clear();
372       theFaceByHybridId.clear();
373   }
374
375   int nbMeshNodes = theMeshDS->NbNodes();
376   int nbInitialNodes = theNodeByHybridId.size();
377
378   const bool isQuadMesh = 
379     theHelper->GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
380     theHelper->GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
381     theHelper->GetMesh()->NbVolumes( ORDER_QUADRATIC );
382     
383 #ifdef _DEBUG_
384   std::cout << "theNodeByHybridId.size(): " << nbInitialNodes << std::endl;
385   std::cout << "theHelper->GetMesh()->NbNodes(): " << nbMeshNodes << std::endl;
386   std::cout << "isQuadMesh: " << isQuadMesh << std::endl;
387 #endif
388   
389   // ---------------------------------
390   // Read generated elements and nodes
391   // ---------------------------------
392
393   int nbElem = 0, nbRef = 0;
394   int aGMFNodeID = 0;
395   std::vector< const SMDS_MeshNode* > GMFNode;
396 #ifdef _DEBUG_
397   std::map<int, std::set<int> > subdomainId2tetraId;
398 #endif
399   std::map <GmfKwdCod,int> tabRef;
400   const bool force3d = !hasGeom;
401   const int  noID    = 0;
402
403   tabRef[GmfVertices]       = 3; // for new nodes and enforced nodes
404   tabRef[GmfCorners]        = 1;
405   tabRef[GmfEdges]          = 2; // for enforced edges
406   tabRef[GmfRidges]         = 1;
407   tabRef[GmfTriangles]      = 3; // for enforced faces
408   tabRef[GmfQuadrilaterals] = 4;
409   tabRef[GmfTetrahedra]     = 4; // for new tetras
410   tabRef[GmfPyramids]       = 5; // for new pyramids
411   tabRef[GmfPrisms]         = 6; // for new prisms
412   tabRef[GmfHexahedra]      = 8;
413
414   int ver, dim;
415   int InpMsh = MGOutput->GmfOpenMesh(theFile, GmfRead, &ver, &dim);
416   if (!InpMsh)
417     return false;
418
419   // Hybrid is not multi-domain => We can't (and don't need to) read ids of domains in ouput file like in GHS3DPlugin
420   // We just need to get the id of the one and only solid
421   int solidID = 1;
422   if ( hasGeom )
423   {
424     if ( theHelper->GetSubShape().ShapeType() == TopAbs_SOLID )
425       solidID = theHelper->GetSubShapeID();
426     else
427       solidID = theMeshDS->ShapeToIndex
428         ( TopExp_Explorer( theHelper->GetSubShape(), TopAbs_SOLID ).Current() );
429   }
430
431   // Issue 0020682. Avoid creating nodes and tetras at place where
432   // volumic elements already exist
433   SMESH_ElementSearcher* elemSearcher = 0;
434   std::vector< const SMDS_MeshElement* > foundVolumes;
435   if ( !hasGeom && theHelper->GetMesh()->NbVolumes() > 0 )
436     elemSearcher = SMESH_MeshAlgos::GetElementSearcher( *theMeshDS );
437   SMESHUtils::Deleter< SMESH_ElementSearcher > elemSearcherDeleter( elemSearcher );
438
439   // IMP 0022172: [CEA 790] create the groups corresponding to domains
440   std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain;
441
442   int nbVertices = MGOutput->GmfStatKwd(InpMsh, GmfVertices) - nbInitialNodes;
443   if ( nbVertices < 0 )
444     return false;
445   GMFNode.resize( nbVertices + 1 );
446
447   std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
448   for ( ; it != tabRef.end() ; ++it)
449   {
450     if(theAlgo->computeCanceled()) {
451       MGOutput->GmfCloseMesh(InpMsh);
452       return false;
453     }
454     int dummy;
455     GmfKwdCod token = it->first;
456     nbRef           = it->second;
457
458     nbElem = MGOutput->GmfStatKwd(InpMsh, token);
459     if (nbElem > 0) {
460       MGOutput->GmfGotoKwd(InpMsh, token);
461       std::cout << "Read " << nbElem;
462     }
463     else
464       continue;
465
466     std::vector<int> id (nbElem*tabRef[token]); // node ids
467     std::vector<int> domainID( nbElem ); // domain
468
469     if (token == GmfVertices) {
470       (nbElem <= 1) ? tmpStr = " vertex" : tmpStr = " vertices";
471       
472       int aGMFID;
473       float VerTab_f[3];
474       double x, y, z;
475       const SMDS_MeshNode * aGMFNode;
476
477       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
478         if(theAlgo->computeCanceled()) {
479           MGOutput->GmfCloseMesh(InpMsh);
480           return false;
481         }
482         if (ver == GmfFloat) {
483           MGOutput->GmfGetLin(InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
484           x = VerTab_f[0];
485           y = VerTab_f[1];
486           z = VerTab_f[2];
487         }
488         else {
489           MGOutput->GmfGetLin(InpMsh, token, &x, &y, &z, &dummy);
490         }
491         if (iElem >= nbInitialNodes) {
492           if ( elemSearcher &&
493                 elemSearcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_Volume, foundVolumes))
494             aGMFNode = 0;
495           else
496             aGMFNode = theHelper->AddNode(x, y, z);
497           
498           aGMFID = iElem -nbInitialNodes +1;
499           GMFNode[ aGMFID ] = aGMFNode;
500           if (aGMFID-1 < (int)aNodeGroupByHybridId.size() && !aNodeGroupByHybridId.at(aGMFID-1).empty())
501             addElemInMeshGroup(theHelper->GetMesh(), aGMFNode, aNodeGroupByHybridId.at(aGMFID-1), groupsToRemove);
502         }
503       }
504     }
505     else if (token == GmfCorners && nbElem > 0) {
506       (nbElem <= 1) ? tmpStr = " corner" : tmpStr = " corners";
507       for ( int iElem = 0; iElem < nbElem; iElem++ )
508         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
509     }
510     else if (token == GmfRidges && nbElem > 0) {
511       (nbElem <= 1) ? tmpStr = " ridge" : tmpStr = " ridges";
512       for ( int iElem = 0; iElem < nbElem; iElem++ )
513         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
514     }
515     else if (token == GmfEdges && nbElem > 0) {
516       (nbElem <= 1) ? tmpStr = " edge" : tmpStr = " edges";
517       for ( int iElem = 0; iElem < nbElem; iElem++ )
518         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
519     }
520     else if (token == GmfTriangles && nbElem > 0) {
521       (nbElem <= 1) ? tmpStr = " triangle" : tmpStr = " triangles";
522       for ( int iElem = 0; iElem < nbElem; iElem++ )
523         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
524     }
525     else if (token == GmfQuadrilaterals && nbElem > 0) {
526       (nbElem <= 1) ? tmpStr = " Quadrilateral" : tmpStr = " Quadrilaterals";
527       for ( int iElem = 0; iElem < nbElem; iElem++ )
528         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
529     }
530     else if (token == GmfTetrahedra && nbElem > 0) {
531       (nbElem <= 1) ? tmpStr = " Tetrahedron" : tmpStr = " Tetrahedra";
532       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
533         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
534 #ifdef _DEBUG_
535         subdomainId2tetraId[dummy].insert(iElem+1);
536 #endif
537       }
538     }
539     else if (token == GmfPyramids && nbElem > 0) {
540       (nbElem <= 1) ? tmpStr = " Pyramid" : tmpStr = " Pyramids";
541       for ( int iElem = 0; iElem < nbElem; iElem++ )
542         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
543                   &id[iElem*tabRef[token]+4], &domainID[iElem]);
544     }
545     else if (token == GmfPrisms && nbElem > 0) {
546       (nbElem <= 1) ? tmpStr = " Prism" : tmpStr = " Prisms";
547       for ( int iElem = 0; iElem < nbElem; iElem++ )
548         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
549                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &domainID[iElem]);
550     }
551     else if (token == GmfHexahedra && nbElem > 0) {
552       (nbElem <= 1) ? tmpStr = " Hexahedron" : tmpStr = " Hexahedra";
553       for ( int iElem = 0; iElem < nbElem; iElem++ )
554         MGOutput->GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
555                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &domainID[iElem]);
556     }
557     std::cout << tmpStr << std::endl;
558     //std::cout << std::endl;
559
560     switch (token) {
561     case GmfCorners:
562     case GmfRidges:
563     case GmfEdges:
564     case GmfTriangles:
565     case GmfQuadrilaterals:
566     case GmfTetrahedra:
567     case GmfPyramids:
568     case GmfPrisms:
569     case GmfHexahedra:
570     {
571       std::vector< const SMDS_MeshNode* > node( nbRef );
572       std::vector< int >          nodeID( nbRef );
573       std::vector< SMDS_MeshNode* > enfNode( nbRef );
574       const SMDS_MeshElement* aCreatedElem;
575
576       for ( int iElem = 0; iElem < nbElem; iElem++ )
577       {
578         if(theAlgo->computeCanceled()) {
579           MGOutput->GmfCloseMesh(InpMsh);
580           return false;
581         }
582         // Check if elem is already in input mesh. If yes => skip
583         bool fullyCreatedElement = false; // if at least one of the nodes was created
584         for ( int iRef = 0; iRef < nbRef; iRef++ )
585         {
586           aGMFNodeID = id[iElem*tabRef[token]+iRef]; // read nbRef aGMFNodeID
587           if (aGMFNodeID <= nbInitialNodes) // input nodes
588           {
589             aGMFNodeID--;
590             node[ iRef ] = theNodeByHybridId[aGMFNodeID];
591           }
592           else
593           {
594             fullyCreatedElement = true;
595             aGMFNodeID -= nbInitialNodes;
596             nodeID[ iRef ] = aGMFNodeID ;
597             node  [ iRef ] = GMFNode[ aGMFNodeID ];
598           }
599         }
600         aCreatedElem = 0;
601         switch (token)
602         {
603         case GmfEdges:
604           if (fullyCreatedElement) {
605             aCreatedElem = theHelper->AddEdge( node[0], node[1], noID, force3d );
606             if ( !anEdgeGroupByHybridId.empty() && !anEdgeGroupByHybridId[iElem].empty())
607               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, anEdgeGroupByHybridId[iElem], groupsToRemove);
608           }
609           break;
610         case GmfTriangles:
611           if (fullyCreatedElement) {
612             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], noID, force3d );
613             // add iElem < aFaceGroupByHybridId.size() to avoid crash if imprinting with hexa core with MeshGems <= 2.4-5
614             if ( !aFaceGroupByHybridId.empty() && iElem < aFaceGroupByHybridId.size() && !aFaceGroupByHybridId[iElem].empty() ) {
615               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, aFaceGroupByHybridId[iElem], groupsToRemove);
616             }
617             // add element in shape for groups on geom to work
618             theMeshDS->SetMeshElementOnShape( aCreatedElem, domainID[iElem] );
619             for ( int iN = 0; iN < 3; ++iN )
620               if ( node[iN]->getshapeId() < 1 )
621                 theMeshDS->SetNodeOnFace( node[iN], domainID[iElem] );
622           }
623           break;
624         case GmfQuadrilaterals:
625           if (fullyCreatedElement) {
626             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], node[3], noID, force3d );
627             // add element in shape for groups on geom to work
628             theMeshDS->SetMeshElementOnShape( aCreatedElem, domainID[iElem] );
629             for ( int iN = 0; iN < 3; ++iN )
630               if ( node[iN]->getshapeId() < 1 )
631                 theMeshDS->SetNodeOnFace( node[iN], domainID[iElem] );
632           }
633           break;
634         case GmfTetrahedra:
635           if ( hasGeom )
636           {
637             if ( solidID != HOLE_ID )
638             {
639               aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
640                                                    noID, force3d );
641               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
642               for ( int iN = 0; iN < 4; ++iN )
643                 if ( node[iN]->getshapeId() < 1 )
644                   theMeshDS->SetNodeInVolume( node[iN], solidID );
645             }
646           }
647           else
648           {
649             if ( elemSearcher ) {
650               // Issue 0020682. Avoid creating nodes and tetras at place where
651               // volumic elements already exist
652               if ( !node[1] || !node[0] || !node[2] || !node[3] )
653                 continue;
654               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
655                                                       SMESH_TNodeXYZ(node[1]) +
656                                                       SMESH_TNodeXYZ(node[2]) +
657                                                       SMESH_TNodeXYZ(node[3]) ) / 4.,
658                                                      SMDSAbs_Volume, foundVolumes ))
659                 break;
660             }
661             aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
662                                                  noID, force3d );
663           }
664           break;
665         case GmfPyramids:
666           if ( hasGeom )
667           {
668             if ( solidID != HOLE_ID )
669             {
670               aCreatedElem = theHelper->AddVolume( node[3], node[2], node[1],
671                                                    node[0], node[4],
672                                                    noID, force3d );
673               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
674               for ( int iN = 0; iN < 5; ++iN )
675                 if ( node[iN]->getshapeId() < 1 )
676                   theMeshDS->SetNodeInVolume( node[iN], solidID );
677             }
678           }
679           else
680           {
681             if ( elemSearcher ) {
682               // Issue 0020682. Avoid creating nodes and tetras at place where
683               // volumic elements already exist
684               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] )
685                 continue;
686               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
687                                                       SMESH_TNodeXYZ(node[1]) +
688                                                       SMESH_TNodeXYZ(node[2]) +
689                                                       SMESH_TNodeXYZ(node[3]) +
690                                                       SMESH_TNodeXYZ(node[4])) / 5.,
691                                                      SMDSAbs_Volume, foundVolumes ))
692                 break;
693             }
694             aCreatedElem = theHelper->AddVolume( node[3], node[2], node[1],
695                                                    node[0], node[4],
696                                                    noID, force3d );
697           }
698           break;
699         case GmfPrisms:
700           if ( hasGeom )
701           {
702             if ( solidID != HOLE_ID )
703             {
704               aCreatedElem = theHelper->AddVolume( node[0], node[2], node[1],
705                                                    node[3], node[5], node[4],
706                                                    noID, force3d );
707               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
708               for ( int iN = 0; iN < 6; ++iN )
709                 if ( node[iN]->getshapeId() < 1 )
710                   theMeshDS->SetNodeInVolume( node[iN], solidID );
711             }
712           }
713           else
714           {
715             if ( elemSearcher ) {
716               // Issue 0020682. Avoid creating nodes and tetras at place where
717               // volumic elements already exist
718               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] )
719                 continue;
720               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
721                                                       SMESH_TNodeXYZ(node[1]) +
722                                                       SMESH_TNodeXYZ(node[2]) +
723                                                       SMESH_TNodeXYZ(node[3]) +
724                                                       SMESH_TNodeXYZ(node[4]) +
725                                                       SMESH_TNodeXYZ(node[5])) / 6.,
726                                                      SMDSAbs_Volume, foundVolumes ))
727                 break;
728             }
729             aCreatedElem = theHelper->AddVolume( node[0], node[2], node[1],
730                                                  node[3], node[5], node[4],
731                                                  noID, force3d );
732           }
733           break;
734         case GmfHexahedra:
735           if ( hasGeom )
736           {
737             if ( solidID != HOLE_ID )
738             {
739               aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
740                                                    node[4], node[7], node[6], node[5],
741                                                    noID, force3d );
742               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
743               for ( int iN = 0; iN < 8; ++iN )
744                 if ( node[iN]->getshapeId() < 1 )
745                   theMeshDS->SetNodeInVolume( node[iN], solidID );
746             }
747           }
748           else
749           {
750             if ( elemSearcher ) {
751               // Issue 0020682. Avoid creating nodes and tetras at place where
752               // volumic elements already exist
753               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] || !node[6] || !node[7])
754                 continue;
755               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
756                                                       SMESH_TNodeXYZ(node[1]) +
757                                                       SMESH_TNodeXYZ(node[2]) +
758                                                       SMESH_TNodeXYZ(node[3]) +
759                                                       SMESH_TNodeXYZ(node[4]) +
760                                                       SMESH_TNodeXYZ(node[5]) +
761                                                       SMESH_TNodeXYZ(node[6]) +
762                                                       SMESH_TNodeXYZ(node[7])) / 8.,
763                                                      SMDSAbs_Volume, foundVolumes ))
764                 break;
765             }
766             aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
767                                                  node[4], node[7], node[6], node[5],
768                                                  noID, force3d );
769           }
770           break;
771         default: continue;
772         } // switch (token)
773
774         if ( aCreatedElem && toMakeGroupsOfDomains )
775         {
776           if ( domainID[iElem] >= (int) elemsOfDomain.size() )
777             elemsOfDomain.resize( domainID[iElem] + 1 );
778           elemsOfDomain[ domainID[iElem] ].push_back( aCreatedElem );
779         }
780       } // loop on elements of one type
781       break;
782     } // case ...
783
784     default:;
785     } // switch (token)
786   } // loop on tabRef
787
788   // remove nodes in holes
789   if ( hasGeom )
790   {
791     for ( int i = 1; i <= nbVertices; ++i )
792       if ( GMFNode[i]->NbInverseElements() == 0 )
793         theMeshDS->RemoveFreeNode( GMFNode[i], /*sm=*/0, /*fromGroups=*/false );
794   }
795
796   MGOutput->GmfCloseMesh(InpMsh);
797
798   // 0022172: [CEA 790] create the groups corresponding to domains
799   if ( toMakeGroupsOfDomains )
800     makeDomainGroups( elemsOfDomain, theHelper );
801
802 #ifdef _DEBUG_
803   std::map<int, std::set<int> >::const_iterator subdomainIt = subdomainId2tetraId.begin();
804   std::string aSubdomainFileName = theFile;
805   aSubdomainFileName = aSubdomainFileName + ".subdomain";
806   ofstream aSubdomainFile  ( aSubdomainFileName  , ios::out);
807
808   aSubdomainFile << "Nb subdomains " << subdomainId2tetraId.size() << std::endl;
809   for(;subdomainIt != subdomainId2tetraId.end() ; ++subdomainIt) {
810     int subdomainId = subdomainIt->first;
811     std::set<int> tetraIds = subdomainIt->second;
812     std::set<int>::const_iterator tetraIdsIt = tetraIds.begin();
813     aSubdomainFile << subdomainId << std::endl;
814     for(;tetraIdsIt != tetraIds.end() ; ++tetraIdsIt) {
815       aSubdomainFile << (*tetraIdsIt) << " ";
816     }
817     aSubdomainFile << std::endl;
818   }
819   aSubdomainFile.close();
820 #endif  
821   
822   return true;
823 }
824
825
826 static bool writeGMFFile(MG_HYBRID_API*                                  MGInput,
827                          const char*                                     theMeshFileName,
828                          const char*                                     theRequiredFileName,
829                          const char*                                     theSolFileName,
830                          const SMESH_ProxyMesh&                          theProxyMesh,
831                          SMESH_MesherHelper&                             theHelper,
832                          std::vector <const SMDS_MeshNode*> &            theNodeByHybridId,
833                          std::vector <const SMDS_MeshElement*> &         theFaceByHybridId,
834                          std::map<const SMDS_MeshNode*,int> &            aNodeToHybridIdMap,
835                          std::vector<std::string> &                      aNodeGroupByHybridId,
836                          std::vector<std::string> &                      anEdgeGroupByHybridId,
837                          std::vector<std::string> &                      aFaceGroupByHybridId,
838                          HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
839                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
840                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles,
841                          std::map<std::vector<double>, std::string> &    enfVerticesWithGroup,
842                          HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues & theEnforcedVertices)
843 {
844   std::string tmpStr;
845   int idx, idxRequired = 0, idxSol = 0;
846   //tabg each dummyint
847   //const int dummyint = 0;
848   const int dummyint1 = 1;
849   const int dummyint2 = 2;
850   const int dummyint3 = 3;
851   const int dummyint4 = 4;
852   const int enforcedTag = HYBRIDPlugin_Hypothesis::EnforcedTag();
853   //const int dummyint6 = 6; //are interesting for layers
854   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues::const_iterator vertexIt;
855   std::vector<double> enfVertexSizes;
856   const SMDS_MeshElement* elem;
857   TIDSortedElemSet anElemSetTri, anElemSetQuad, theKeptEnforcedEdges, theKeptEnforcedTriangles;
858   SMDS_ElemIteratorPtr nodeIt;
859   std::vector <const SMDS_MeshNode*> theEnforcedNodeByHybridId;
860   std::map<const SMDS_MeshNode*,int> anEnforcedNodeToHybridIdMap, anExistingEnforcedNodeToHybridIdMap;
861   std::vector< const SMDS_MeshElement* > foundElems;
862   std::map<const SMDS_MeshNode*,TopAbs_State> aNodeToTopAbs_StateMap;
863   int nbFoundElems;
864   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap::iterator elemIt;
865   TIDSortedElemSet::iterator elemSetIt;
866   bool isOK;
867   SMESH_Mesh* theMesh = theHelper.GetMesh();
868   const bool hasGeom = theMesh->HasShapeToMesh();
869   SMESHUtils::Deleter< SMESH_ElementSearcher > pntCls
870     ( SMESH_MeshAlgos::GetElementSearcher(*theMesh->GetMeshDS()));
871   
872   int nbEnforcedVertices = theEnforcedVertices.size();
873   
874   // count faces
875   int nbFaces = theProxyMesh.NbFaces();
876   int nbNodes;
877   theFaceByHybridId.reserve( nbFaces );
878   
879   // groups management
880   int usedEnforcedNodes = 0;
881   std::string gn = "";
882
883   if ( nbFaces == 0 )
884     return false;
885   
886   idx = MGInput->GmfOpenMesh(theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
887   if (!idx)
888     return false;
889   
890   // ========================== FACES ==========================
891   // TRIANGLES ==========================
892   SMDS_ElemIteratorPtr eIt =
893     hasGeom ? theProxyMesh.GetFaces( theHelper.GetSubShape()) : theProxyMesh.GetFaces();
894   while ( eIt->more() )
895   {
896     elem = eIt->next();
897     nodeIt = elem->nodesIterator();
898     nbNodes = elem->NbCornerNodes();
899     if (nbNodes == 3)
900       anElemSetTri.insert(elem);
901     else if (nbNodes == 4)
902       anElemSetQuad.insert(elem);
903     else
904     {
905       std::cout << "Unexpected number of nodes: " << nbNodes << std::endl;
906       throw ("Unexpected number of nodes" );
907     }
908     while ( nodeIt->more() && nbNodes--)
909     {
910       // find HYBRID ID
911       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
912       int newId = aNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
913       aNodeToHybridIdMap.insert( std::make_pair( node, newId ));
914     }
915   }
916   
917   //EDGES ==========================
918   
919   // Iterate over the enforced edges
920   for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
921     elem = elemIt->first;
922     isOK = true;
923     nodeIt = elem->nodesIterator();
924     nbNodes = 2;
925     while ( nodeIt->more() && nbNodes-- ) {
926       // find HYBRID ID
927       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
928       // Test if point is inside shape to mesh
929       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
930       TopAbs_State result = pntCls->GetPointState( myPoint );
931       if ( result == TopAbs_OUT ) {
932         isOK = false;
933         break;
934       }
935       aNodeToTopAbs_StateMap.insert( std::make_pair( node, result ));
936     }
937     if (isOK) {
938       nodeIt = elem->nodesIterator();
939       nbNodes = 2;
940       int newId = -1;
941       while ( nodeIt->more() && nbNodes-- ) {
942         // find HYBRID ID
943         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
944         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
945         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
946 #ifdef _DEBUG_
947         std::cout << "Node at "<<node->X()<<", "<<node->Y()<<", "<<node->Z()<<std::endl;
948         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
949 #endif
950         if (nbFoundElems ==0) {
951           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
952             newId = aNodeToHybridIdMap.size() + anEnforcedNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
953             anEnforcedNodeToHybridIdMap.insert( std::make_pair( node, newId ));
954           }
955         }
956         else if (nbFoundElems ==1) {
957           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
958           newId = (*aNodeToHybridIdMap.find(existingNode)).second;
959           anExistingEnforcedNodeToHybridIdMap.insert( std::make_pair( node, newId ));
960         }
961         else
962           isOK = false;
963 #ifdef _DEBUG_
964         std::cout << "HYBRID node ID: "<<newId<<std::endl;
965 #endif
966       }
967       if (isOK)
968         theKeptEnforcedEdges.insert(elem);
969     }
970   }
971   
972   //ENFORCED TRIANGLES ==========================
973   
974   // Iterate over the enforced triangles
975   for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
976     elem = elemIt->first;
977     isOK = true;
978     nodeIt = elem->nodesIterator();
979     nbNodes = 3;
980     while ( nodeIt->more() && nbNodes--) {
981       // find HYBRID ID
982       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
983       // Test if point is inside shape to mesh
984       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
985       TopAbs_State result = pntCls->GetPointState( myPoint );
986       if ( result == TopAbs_OUT ) {
987         isOK = false;
988         break;
989       }
990       aNodeToTopAbs_StateMap.insert( std::make_pair( node, result ));
991     }
992     if (isOK) {
993       nodeIt = elem->nodesIterator();
994       nbNodes = 3;
995       int newId = -1;
996       while ( nodeIt->more() && nbNodes--) {
997         // find HYBRID ID
998         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
999         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1000         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1001 #ifdef _DEBUG_
1002         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1003 #endif
1004         if (nbFoundElems ==0) {
1005           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1006             newId = aNodeToHybridIdMap.size() + anEnforcedNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
1007             anEnforcedNodeToHybridIdMap.insert( std::make_pair( node, newId ));
1008           }
1009         }
1010         else if (nbFoundElems ==1) {
1011           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1012           newId = (*aNodeToHybridIdMap.find(existingNode)).second;
1013           anExistingEnforcedNodeToHybridIdMap.insert( std::make_pair( node, newId ));
1014         }
1015         else
1016           isOK = false;
1017 #ifdef _DEBUG_
1018         std::cout << "HYBRID node ID: "<<newId<<std::endl;
1019 #endif
1020       }
1021       if (isOK)
1022         theKeptEnforcedTriangles.insert(elem);
1023     }
1024   }
1025   
1026   // put nodes to theNodeByHybridId vector
1027 #ifdef _DEBUG_
1028   std::cout << "aNodeToHybridIdMap.size(): "<<aNodeToHybridIdMap.size()<<std::endl;
1029 #endif
1030   theNodeByHybridId.resize( aNodeToHybridIdMap.size() );
1031   std::map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToHybridIdMap.begin();
1032   for ( ; n2id != aNodeToHybridIdMap.end(); ++ n2id)
1033   {
1034 //     std::cout << "n2id->first: "<<n2id->first<<std::endl;
1035     theNodeByHybridId[ n2id->second - 1 ] = n2id->first; // hybrid ids count from 1
1036   }
1037
1038   // put nodes to anEnforcedNodeToHybridIdMap vector
1039 #ifdef _DEBUG_
1040   std::cout << "anEnforcedNodeToHybridIdMap.size(): "<<anEnforcedNodeToHybridIdMap.size()<<std::endl;
1041 #endif
1042   theEnforcedNodeByHybridId.resize( anEnforcedNodeToHybridIdMap.size());
1043   n2id = anEnforcedNodeToHybridIdMap.begin();
1044   for ( ; n2id != anEnforcedNodeToHybridIdMap.end(); ++ n2id)
1045   {
1046     if (n2id->second > (int)aNodeToHybridIdMap.size()) {
1047       theEnforcedNodeByHybridId[ n2id->second - aNodeToHybridIdMap.size() - 1 ] = n2id->first; // hybrid ids count from 1
1048     }
1049   }
1050   
1051   
1052   //========================== NODES ==========================
1053   std::vector<const SMDS_MeshNode*> theOrderedNodes, theRequiredNodes;
1054   std::set< std::vector<double> > nodesCoords;
1055   std::vector<const SMDS_MeshNode*>::const_iterator hybridNodeIt = theNodeByHybridId.begin();
1056   std::vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByHybridId.end();
1057   
1058   (theNodeByHybridId.size() <= 1) ? tmpStr = " node" : " nodes";
1059   std::cout << theNodeByHybridId.size() << tmpStr << " from mesh ..." << std::endl;
1060   for ( ; hybridNodeIt != after; ++hybridNodeIt )
1061   {
1062     const SMDS_MeshNode* node = *hybridNodeIt;
1063     std::vector<double> coords;
1064     coords.push_back(node->X());
1065     coords.push_back(node->Y());
1066     coords.push_back(node->Z());
1067     nodesCoords.insert(coords);
1068     theOrderedNodes.push_back(node);
1069   }
1070   
1071   // Iterate over the enforced nodes given by enforced elements
1072   hybridNodeIt = theEnforcedNodeByHybridId.begin();
1073   after  = theEnforcedNodeByHybridId.end();
1074   (theEnforcedNodeByHybridId.size() <= 1) ? tmpStr = " node" : " nodes";
1075   std::cout << theEnforcedNodeByHybridId.size() << tmpStr << " from enforced elements ..." << std::endl;
1076   for ( ; hybridNodeIt != after; ++hybridNodeIt )
1077   {
1078     const SMDS_MeshNode* node = *hybridNodeIt;
1079     std::vector<double> coords;
1080     coords.push_back(node->X());
1081     coords.push_back(node->Y());
1082     coords.push_back(node->Z());
1083 #ifdef _DEBUG_
1084     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1085 #endif
1086     
1087     if (nodesCoords.find(coords) != nodesCoords.end()) {
1088       // node already exists in original mesh
1089 #ifdef _DEBUG_
1090       std::cout << " found" << std::endl;
1091 #endif
1092       continue;
1093     }
1094     
1095     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1096       // node already exists in enforced vertices
1097 #ifdef _DEBUG_
1098       std::cout << " found" << std::endl;
1099 #endif
1100       continue;
1101     }
1102     
1103 #ifdef _DEBUG_
1104     std::cout << " not found" << std::endl;
1105 #endif
1106     
1107     nodesCoords.insert(coords);
1108     theOrderedNodes.push_back(node);
1109 //     theRequiredNodes.push_back(node);
1110   }
1111   
1112   
1113   // Iterate over the enforced nodes
1114   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt;
1115   (theEnforcedNodes.size() <= 1) ? tmpStr = " node" : " nodes";
1116   std::cout << theEnforcedNodes.size() << tmpStr << " from enforced nodes ..." << std::endl;
1117   for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt)
1118   {
1119     const SMDS_MeshNode* node = enfNodeIt->first;
1120     std::vector<double> coords;
1121     coords.push_back(node->X());
1122     coords.push_back(node->Y());
1123     coords.push_back(node->Z());
1124 #ifdef _DEBUG_
1125     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1126 #endif
1127     
1128     // Test if point is inside shape to mesh
1129     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1130     TopAbs_State result = pntCls->GetPointState( myPoint );
1131     if ( result == TopAbs_OUT ) {
1132 #ifdef _DEBUG_
1133       std::cout << " out of volume" << std::endl;
1134 #endif
1135       continue;
1136     }
1137     
1138     if (nodesCoords.find(coords) != nodesCoords.end()) {
1139 #ifdef _DEBUG_
1140       std::cout << " found in nodesCoords" << std::endl;
1141 #endif
1142 //       theRequiredNodes.push_back(node);
1143       continue;
1144     }
1145
1146     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1147 #ifdef _DEBUG_
1148       std::cout << " found in theEnforcedVertices" << std::endl;
1149 #endif
1150       continue;
1151     }
1152     
1153 #ifdef _DEBUG_
1154     std::cout << " not found" << std::endl;
1155 #endif
1156     nodesCoords.insert(coords);
1157 //     theOrderedNodes.push_back(node);
1158     theRequiredNodes.push_back(node);
1159   }
1160   int requiredNodes = theRequiredNodes.size();
1161   
1162   int solSize = 0;
1163   std::vector<std::vector<double> > ReqVerTab;
1164   if (nbEnforcedVertices) {
1165     (nbEnforcedVertices <= 1) ? tmpStr = " node" : " nodes";
1166     std::cout << nbEnforcedVertices << tmpStr << " from enforced vertices ..." << std::endl;
1167     // Iterate over the enforced vertices
1168     for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
1169       double x = vertexIt->first[0];
1170       double y = vertexIt->first[1];
1171       double z = vertexIt->first[2];
1172       // Test if point is inside shape to mesh
1173       gp_Pnt myPoint(x,y,z);
1174       TopAbs_State result = pntCls->GetPointState( myPoint );
1175       if ( result == TopAbs_OUT )
1176         continue;
1177       std::vector<double> coords;
1178       coords.push_back(x);
1179       coords.push_back(y);
1180       coords.push_back(z);
1181       ReqVerTab.push_back(coords);
1182       enfVertexSizes.push_back(vertexIt->second);
1183       solSize++;
1184     }
1185   }
1186   
1187   
1188   // GmfVertices
1189   std::cout << "Begin writing required nodes in GmfVertices" << std::endl;
1190   std::cout << "Nb vertices: " << theOrderedNodes.size() << std::endl;
1191   MGInput->GmfSetKwd(idx, GmfVertices, theOrderedNodes.size());
1192   for (hybridNodeIt = theOrderedNodes.begin();hybridNodeIt != theOrderedNodes.end();++hybridNodeIt) {
1193     MGInput->GmfSetLin(idx, GmfVertices, (*hybridNodeIt)->X(), (*hybridNodeIt)->Y(), (*hybridNodeIt)->Z(), dummyint1);
1194   }
1195
1196   std::cout << "End writing required nodes in GmfVertices" << std::endl;
1197
1198   if (requiredNodes + solSize) {
1199     std::cout << "Begin writing in req and sol file" << std::endl;
1200     aNodeGroupByHybridId.resize( requiredNodes + solSize );
1201     idxRequired = MGInput->GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1202     if (!idxRequired) {
1203       MGInput->GmfCloseMesh(idx);
1204       return false;
1205     }
1206     idxSol = MGInput->GmfOpenMesh(theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1207     if (!idxSol) {
1208       MGInput->GmfCloseMesh(idx);
1209       if (idxRequired)
1210         MGInput->GmfCloseMesh(idxRequired);
1211       return false;
1212     }
1213     int TypTab[] = {GmfSca};
1214     double ValTab[] = {0.0};
1215     MGInput->GmfSetKwd(idxRequired, GmfVertices, requiredNodes + solSize);
1216     MGInput->GmfSetKwd(idxSol, GmfSolAtVertices, requiredNodes + solSize, 1, TypTab);
1217     for (hybridNodeIt = theRequiredNodes.begin();hybridNodeIt != theRequiredNodes.end();++hybridNodeIt) {
1218       MGInput->GmfSetLin(idxRequired, GmfVertices, (*hybridNodeIt)->X(), (*hybridNodeIt)->Y(), (*hybridNodeIt)->Z(), dummyint2);
1219       MGInput->GmfSetLin(idxSol, GmfSolAtVertices, ValTab);
1220       if (theEnforcedNodes.find((*hybridNodeIt)) != theEnforcedNodes.end())
1221         gn = theEnforcedNodes.find((*hybridNodeIt))->second;
1222       aNodeGroupByHybridId[usedEnforcedNodes] = gn;
1223       usedEnforcedNodes++;
1224     }
1225
1226     for (int i=0;i<solSize;i++) {
1227       std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
1228 #ifdef _DEBUG_
1229       std::cout << "enfVertexSizes.at("<<i<<"): " << enfVertexSizes.at(i) << std::endl;
1230 #endif
1231       double solTab[] = {enfVertexSizes.at(i)};
1232       MGInput->GmfSetLin(idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint3);
1233       MGInput->GmfSetLin(idxSol, GmfSolAtVertices, solTab);
1234       aNodeGroupByHybridId[usedEnforcedNodes] = enfVerticesWithGroup.find(ReqVerTab[i])->second;
1235 #ifdef _DEBUG_
1236       std::cout << "aNodeGroupByHybridId["<<usedEnforcedNodes<<"] = \""<<aNodeGroupByHybridId[usedEnforcedNodes]<<"\""<<std::endl;
1237 #endif
1238       usedEnforcedNodes++;
1239     }
1240     std::cout << "End writing in req and sol file" << std::endl;
1241   }
1242
1243   int nedge[2], ntri[3], nquad[4];
1244     
1245   // GmfEdges
1246   int usedEnforcedEdges = 0;
1247   if (theKeptEnforcedEdges.size()) {
1248     anEdgeGroupByHybridId.resize( theKeptEnforcedEdges.size() );
1249     MGInput->GmfSetKwd(idx, GmfEdges, theKeptEnforcedEdges.size());
1250     for(elemSetIt = theKeptEnforcedEdges.begin() ; elemSetIt != theKeptEnforcedEdges.end() ; ++elemSetIt) {
1251       elem = (*elemSetIt);
1252       nodeIt = elem->nodesIterator();
1253       int index=0;
1254       while ( nodeIt->more() ) {
1255         // find HYBRID ID
1256         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1257         std::map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToHybridIdMap.find(node);
1258         if (it == anEnforcedNodeToHybridIdMap.end()) {
1259           it = anExistingEnforcedNodeToHybridIdMap.find(node);
1260           if (it == anEnforcedNodeToHybridIdMap.end())
1261             throw "Node not found";
1262         }
1263         nedge[index] = it->second;
1264         index++;
1265       }
1266       MGInput->GmfSetLin(idx, GmfEdges, nedge[0], nedge[1], dummyint4);
1267       anEdgeGroupByHybridId[usedEnforcedEdges] = theEnforcedEdges.find(elem)->second;
1268       usedEnforcedEdges++;
1269     }
1270   }
1271
1272
1273   if (usedEnforcedEdges) {
1274     MGInput->GmfSetKwd(idx, GmfRequiredEdges, usedEnforcedEdges);
1275     for (int enfID=1;enfID<=usedEnforcedEdges;enfID++) {
1276       MGInput->GmfSetLin(idx, GmfRequiredEdges, enfID);
1277     }
1278   }
1279
1280   // GmfTriangles
1281   int usedEnforcedTriangles = 0;
1282   if (anElemSetTri.size()+theKeptEnforcedTriangles.size())
1283   {
1284     aFaceGroupByHybridId.resize( anElemSetTri.size()+theKeptEnforcedTriangles.size() );
1285     MGInput->GmfSetKwd(idx, GmfTriangles, anElemSetTri.size()+theKeptEnforcedTriangles.size());
1286     int k=0;
1287     for(elemSetIt = anElemSetTri.begin() ; elemSetIt != anElemSetTri.end() ; ++elemSetIt,++k)
1288     {
1289       elem = (*elemSetIt);
1290       theFaceByHybridId.push_back( elem );
1291       nodeIt = elem->nodesIterator();
1292       int index=0;
1293       for ( int j = 0; j < 3; ++j )
1294       {
1295         // find HYBRID ID
1296         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1297         std::map< const SMDS_MeshNode*,int >::iterator it = aNodeToHybridIdMap.find(node);
1298         if (it == aNodeToHybridIdMap.end())
1299           throw "Node not found";
1300         ntri[index] = it->second;
1301         index++;
1302       }
1303       MGInput->GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], /*tag=*/elem->getshapeId() );
1304       aFaceGroupByHybridId[k] = "";
1305     }
1306     
1307     if ( !theHelper.GetMesh()->HasShapeToMesh() ) SMESHUtils::FreeVector( theFaceByHybridId ); 
1308     std::cout << "Enforced triangles size " << theKeptEnforcedTriangles.size() << std::endl;
1309     if (theKeptEnforcedTriangles.size())
1310     {
1311       for(elemSetIt = theKeptEnforcedTriangles.begin() ; elemSetIt != theKeptEnforcedTriangles.end() ; ++elemSetIt,++k)
1312       {
1313         elem = (*elemSetIt);
1314         nodeIt = elem->nodesIterator();
1315         int index=0;
1316         for ( int j = 0; j < 3; ++j )
1317         {
1318           // find HYBRID ID
1319           const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1320           std::map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToHybridIdMap.find(node);
1321           if (it == anEnforcedNodeToHybridIdMap.end())
1322           {
1323             it = anExistingEnforcedNodeToHybridIdMap.find(node);
1324             if (it == anEnforcedNodeToHybridIdMap.end())
1325               throw "Node not found";
1326           }
1327           ntri[index] = it->second;
1328           index++;
1329         }
1330         MGInput->GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], enforcedTag);
1331         aFaceGroupByHybridId[k] = theEnforcedTriangles.find(elem)->second;
1332         usedEnforcedTriangles++;
1333       }
1334     }
1335   }
1336
1337   
1338   if (usedEnforcedTriangles)
1339   {
1340     MGInput->GmfSetKwd(idx, GmfRequiredTriangles, usedEnforcedTriangles);
1341     for (int enfID=1;enfID<=usedEnforcedTriangles;enfID++)
1342       MGInput->GmfSetLin(idx, GmfRequiredTriangles, anElemSetTri.size()+enfID);
1343   }
1344   
1345   if (anElemSetQuad.size())
1346   {
1347     MGInput->GmfSetKwd(idx, GmfQuadrilaterals, anElemSetQuad.size());
1348     int k=0;
1349     for(elemSetIt = anElemSetQuad.begin() ; elemSetIt != anElemSetQuad.end() ; ++elemSetIt,++k)
1350     {
1351       elem = (*elemSetIt);
1352       theFaceByHybridId.push_back( elem );
1353       nodeIt = elem->nodesIterator();
1354       int index=0;
1355       for ( int j = 0; j < 4; ++j )
1356       {
1357         // find HYBRID ID
1358         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1359         std::map< const SMDS_MeshNode*,int >::iterator it = aNodeToHybridIdMap.find(node);
1360         if (it == aNodeToHybridIdMap.end())
1361           throw "Node not found";
1362         nquad[index] = it->second;
1363         index++;
1364       }
1365       MGInput->GmfSetLin(idx, GmfQuadrilaterals, nquad[0], nquad[1], nquad[2], nquad[3],
1366                          /*tag=*/elem->getshapeId() );
1367       // _CEA_cbo what is it for???
1368       //aFaceGroupByHybridId[k] = "";
1369     }
1370   }
1371
1372   MGInput->GmfCloseMesh(idx);
1373   if (idxRequired)
1374     MGInput->GmfCloseMesh(idxRequired);
1375   if (idxSol)
1376     MGInput->GmfCloseMesh(idxSol);
1377   
1378   return true;
1379   
1380 }
1381
1382 //=============================================================================
1383 /*!
1384  *Here we are going to use the HYBRID mesher with geometry
1385  */
1386 //=============================================================================
1387
1388 bool HYBRIDPlugin_HYBRID::Compute(SMESH_Mesh&         theMesh,
1389                                   const TopoDS_Shape& theShape)
1390 {
1391   bool Ok = false;
1392
1393   // a unique working file name
1394   // to avoid access to the same files by eg different users
1395   _genericName = HYBRIDPlugin_Hypothesis::GetFileName(_hyp);
1396   std::string aGenericName         = _genericName;
1397   std::string aGenericNameRequired = aGenericName + "_required";
1398
1399   std::string aLogFileName    = aGenericName + ".log";    // log
1400   std::string aResultFileName;
1401
1402   std::string aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
1403   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
1404   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
1405   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
1406   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
1407   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
1408   
1409   std::map <int,int> aNodeId2NodeIndexMap, aSmdsToHybridIdMap, anEnforcedNodeIdToHybridIdMap;
1410   std::map <int, int> nodeID2nodeIndexMap;
1411   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
1412   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues coordsSizeMap = HYBRIDPlugin_Hypothesis::GetEnforcedVerticesCoordsSize(_hyp);
1413   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = HYBRIDPlugin_Hypothesis::GetEnforcedNodes(_hyp);
1414   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = HYBRIDPlugin_Hypothesis::GetEnforcedEdges(_hyp);
1415   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = HYBRIDPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
1416   HYBRIDPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = HYBRIDPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
1417
1418   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList enfVertices = HYBRIDPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1419   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
1420   std::vector<double> coords;
1421
1422   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
1423   {
1424     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertex* enfVertex = (*enfVerIt);
1425     if (enfVertex->coords.size()) {
1426       coordsSizeMap.insert(std::make_pair(enfVertex->coords,enfVertex->size));
1427       enfVerticesWithGroup.insert(std::make_pair(enfVertex->coords,enfVertex->groupName));
1428     }
1429     else {
1430       TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
1431       for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1432         coords.clear();
1433         if (it.Value().ShapeType() == TopAbs_VERTEX){
1434           gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
1435           coords.push_back(aPnt.X());
1436           coords.push_back(aPnt.Y());
1437           coords.push_back(aPnt.Z());
1438           if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
1439             coordsSizeMap.insert(std::make_pair(coords,enfVertex->size));
1440             enfVerticesWithGroup.insert(std::make_pair(coords,enfVertex->groupName));
1441           }
1442         }
1443       }
1444     }
1445   }
1446   int nbEnforcedVertices = coordsSizeMap.size();
1447   int nbEnforcedNodes = enforcedNodes.size();
1448
1449   std::string tmpStr;
1450   (nbEnforcedNodes <= 1) ? tmpStr = "node" : "nodes";
1451   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
1452   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : "vertices";
1453   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
1454
1455   SMESH_MesherHelper helper( theMesh );
1456   helper.SetSubShape( theShape );
1457
1458   std::vector <const SMDS_MeshNode*> aNodeByHybridId, anEnforcedNodeByHybridId;
1459   std::vector <const SMDS_MeshElement*> aFaceByHybridId;
1460   std::map<const SMDS_MeshNode*,int> aNodeToHybridIdMap;
1461   std::vector<std::string> aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId;
1462
1463   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
1464
1465   MG_HYBRID_API mgHybrid( _computeCanceled, _progress );
1466
1467   Ok = writeGMFFile(&mgHybrid,
1468                     aGMFFileName.c_str(),
1469                     aRequiredVerticesFileName.c_str(),
1470                     aSolFileName.c_str(),
1471                     *proxyMesh, helper,
1472                     aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
1473                     aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
1474                     enforcedNodes, enforcedEdges, enforcedTriangles, /*enforcedQuadrangles,*/
1475                     enfVerticesWithGroup, coordsSizeMap);
1476
1477   // Write aSmdsToHybridIdMap to temp file
1478   std::string aSmdsToHybridIdMapFileName;
1479   aSmdsToHybridIdMapFileName = aGenericName + ".ids";  // ids relation
1480   ofstream aIdsFile  ( aSmdsToHybridIdMapFileName  , ios::out);
1481   Ok = aIdsFile.rdbuf()->is_open();
1482   if (!Ok) {
1483     INFOS( "Can't write into " << aSmdsToHybridIdMapFileName);
1484     return error(SMESH_Comment("Can't write into ") << aSmdsToHybridIdMapFileName);
1485   }
1486   INFOS( "Writing ids relation into " << aSmdsToHybridIdMapFileName);
1487   aIdsFile << "Smds Hybrid" << std::endl;
1488   std::map <int,int>::const_iterator myit;
1489   for (myit=aSmdsToHybridIdMap.begin() ; myit != aSmdsToHybridIdMap.end() ; ++myit) {
1490     aIdsFile << myit->first << " " << myit->second << std::endl;
1491   }
1492
1493   aIdsFile.close();
1494
1495   if ( ! Ok ) {
1496     if ( !_keepFiles ) {
1497       removeFile( aGMFFileName );
1498       removeFile( aRequiredVerticesFileName );
1499       removeFile( aSolFileName );
1500       removeFile( aSmdsToHybridIdMapFileName );
1501     }
1502     return error(COMPERR_BAD_INPUT_MESH);
1503   }
1504   removeFile( aResultFileName ); // needed for boundary recovery module usage
1505
1506   // -----------------
1507   // run hybrid mesher
1508   // -----------------
1509
1510   std::string cmd = HYBRIDPlugin_Hypothesis::CommandToRun( _hyp, theMesh );
1511
1512   if ( mgHybrid.IsExecutable() )
1513   {
1514     cmd += " --in "  + aGMFFileName;
1515     cmd += " --out " + aResultFileName;
1516   }
1517   std::cout << std::endl;
1518   std::cout << "Hybrid execution with geometry..." << std::endl;
1519   std::cout << cmd;
1520   if ( !_logInStandardOutput )
1521   {
1522     mgHybrid.SetLogFile( aLogFileName );
1523     if ( mgHybrid.IsExecutable() )
1524       cmd += " 1>" + aLogFileName;  // dump into file
1525     std::cout << " 1> " << aLogFileName;
1526   }
1527   std::cout << std::endl;
1528
1529   _computeCanceled = false;
1530
1531   std::string errStr;
1532   Ok = mgHybrid.Compute( cmd, errStr ); // run
1533
1534   if ( _logInStandardOutput && mgHybrid.IsLibrary() )
1535     std::cout << std::endl << mgHybrid.GetLog() << std::endl;
1536   if ( Ok )
1537     std::cout << "End of Hybrid execution !" << std::endl;
1538
1539   // --------------
1540   // read a result
1541   // --------------
1542
1543   // Mapping the result file
1544
1545   HYBRIDPlugin_Hypothesis::TSetStrings groupsToRemove = HYBRIDPlugin_Hypothesis::GetGroupsToRemove(_hyp);
1546   bool toMeshHoles =
1547     _hyp ? _hyp->GetToMeshHoles(true) : HYBRIDPlugin_Hypothesis::DefaultMeshHoles();
1548   const bool toMakeGroupsOfDomains = HYBRIDPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
1549
1550   helper.IsQuadraticSubMesh( theShape );
1551   helper.SetElementsOnShape( false );
1552
1553   Ok = readGMFFile(&mgHybrid, aResultFileName.c_str(),
1554                    this,
1555                    &helper, aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
1556                    aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
1557                    groupsToRemove, toMakeGroupsOfDomains, toMeshHoles);
1558
1559   removeEmptyGroupsOfDomains( helper.GetMesh(), !toMakeGroupsOfDomains );
1560
1561
1562
1563   // ---------------------
1564   // remove working files
1565   // ---------------------
1566
1567   if ( Ok )
1568   {
1569     if ( _removeLogOnSuccess )
1570       removeFile( aLogFileName );
1571   }
1572   else if ( mgHybrid.HasLog() )
1573   {
1574     // get problem description from the log file
1575     _Ghs2smdsConvertor conv( aNodeByHybridId );
1576     storeErrorDescription( _logInStandardOutput ? 0 : aLogFileName.c_str(),
1577                            mgHybrid.GetLog(), conv );
1578   }
1579   else if ( !errStr.empty() )
1580   {
1581     // the log file is empty
1582     removeFile( aLogFileName );
1583     INFOS( "HYBRID Error, " << errStr );
1584     error(COMPERR_ALGO_FAILED, errStr );
1585   }
1586
1587   if ( !_keepFiles ) {
1588     if (! Ok && _computeCanceled)
1589       removeFile( aLogFileName );
1590     removeFile( aGMFFileName );
1591     removeFile( aRequiredVerticesFileName );
1592     removeFile( aSolFileName );
1593     removeFile( aResSolFileName );
1594     removeFile( aResultFileName );
1595     removeFile( aSmdsToHybridIdMapFileName );
1596   }
1597   if ( mgHybrid.IsExecutable() )
1598   {
1599     std::cout << "<" << aResultFileName << "> HYBRID output file ";
1600     if ( !Ok )
1601       std::cout << "not ";
1602     std::cout << "treated !" << std::endl;
1603     std::cout << std::endl;
1604   }
1605   else
1606   {
1607     std::cout << "MG-HYBRID " << ( Ok ? "succeeded" : "failed") << std::endl;
1608   }
1609
1610   return Ok;
1611 }
1612
1613 //=============================================================================
1614 /*!
1615  *Here we are going to use the HYBRID mesher w/o geometry
1616  */
1617 //=============================================================================
1618 bool HYBRIDPlugin_HYBRID::Compute(SMESH_Mesh&         theMesh,
1619                                   SMESH_MesherHelper* theHelper)
1620 {
1621   theHelper->IsQuadraticSubMesh( theHelper->GetSubShape() );
1622
1623   // a unique working file name
1624   // to avoid access to the same files by eg different users
1625   _genericName = HYBRIDPlugin_Hypothesis::GetFileName(_hyp);
1626   std::string aGenericName((char*) _genericName.c_str() );
1627   std::string aGenericNameRequired = aGenericName + "_required";
1628
1629   std::string aLogFileName    = aGenericName + ".log";    // log
1630   std::string aResultFileName;
1631   bool Ok;
1632
1633   std::string aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
1634   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
1635   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
1636   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
1637   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
1638   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
1639
1640   std::map <int, int> nodeID2nodeIndexMap;
1641   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
1642   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues coordsSizeMap;
1643   TopoDS_Shape GeomShape;
1644   std::vector<double> coords;
1645   gp_Pnt aPnt;
1646   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertex* enfVertex;
1647
1648   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList enfVertices = HYBRIDPlugin_Hypothesis::GetEnforcedVertices(_hyp);
1649   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
1650
1651   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
1652   {
1653     enfVertex = (*enfVerIt);
1654     if (enfVertex->coords.size()) {
1655       coordsSizeMap.insert(std::make_pair(enfVertex->coords,enfVertex->size));
1656       enfVerticesWithGroup.insert(std::make_pair(enfVertex->coords,enfVertex->groupName));
1657     }
1658     else {
1659       GeomShape = entryToShape(enfVertex->geomEntry);
1660       for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1661         coords.clear();
1662         if (it.Value().ShapeType() == TopAbs_VERTEX){
1663           aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
1664           coords.push_back(aPnt.X());
1665           coords.push_back(aPnt.Y());
1666           coords.push_back(aPnt.Z());
1667           if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
1668             coordsSizeMap.insert(std::make_pair(coords,enfVertex->size));
1669             enfVerticesWithGroup.insert(std::make_pair(coords,enfVertex->groupName));
1670           }
1671         }
1672       }
1673     }
1674   }
1675
1676   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = HYBRIDPlugin_Hypothesis::GetEnforcedNodes(_hyp);
1677   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = HYBRIDPlugin_Hypothesis::GetEnforcedEdges(_hyp);
1678   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = HYBRIDPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
1679   HYBRIDPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = HYBRIDPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
1680
1681   std::string tmpStr;
1682
1683   int nbEnforcedVertices = coordsSizeMap.size();
1684   int nbEnforcedNodes = enforcedNodes.size();
1685   (nbEnforcedNodes <= 1) ? tmpStr = "node" : tmpStr = "nodes";
1686   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
1687   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : tmpStr = "vertices";
1688   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
1689
1690   std::vector <const SMDS_MeshNode*> aNodeByHybridId, anEnforcedNodeByHybridId;
1691   std::vector <const SMDS_MeshElement*> aFaceByHybridId;
1692   std::map<const SMDS_MeshNode*,int> aNodeToHybridIdMap;
1693   std::vector<std::string> aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId;
1694
1695   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
1696
1697   MG_HYBRID_API mgHybrid( _computeCanceled, _progress );
1698
1699   Ok = writeGMFFile(&mgHybrid,
1700                     aGMFFileName.c_str(),
1701                     aRequiredVerticesFileName.c_str(), aSolFileName.c_str(),
1702                     *proxyMesh, *theHelper,
1703                     aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
1704                     aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
1705                     enforcedNodes, enforcedEdges, enforcedTriangles,
1706                     enfVerticesWithGroup, coordsSizeMap);
1707
1708   // -----------------
1709   // run hybrid mesher
1710   // -----------------
1711
1712   std::string cmd = HYBRIDPlugin_Hypothesis::CommandToRun( _hyp, theMesh );
1713
1714   if ( mgHybrid.IsExecutable() )
1715   {
1716     cmd += " --in "  + aGMFFileName;
1717     cmd += " --out " + aResultFileName;
1718   }
1719   if ( !_logInStandardOutput )
1720   {
1721     cmd += " 1> " + aLogFileName;  // dump into file
1722     mgHybrid.SetLogFile( aLogFileName );
1723   }
1724   std::cout << std::endl;
1725   std::cout << "Hybrid execution w/o geometry..." << std::endl;
1726   std::cout << cmd << std::endl;
1727
1728   _computeCanceled = false;
1729
1730   std::string errStr;
1731   Ok = mgHybrid.Compute( cmd, errStr ); // run
1732
1733   if ( _logInStandardOutput && mgHybrid.IsLibrary() )
1734     std::cout << std::endl << mgHybrid.GetLog() << std::endl;
1735   if ( Ok )
1736     std::cout << "End of Hybrid execution !" << std::endl;
1737
1738   // --------------
1739   // read a result
1740   // --------------
1741   HYBRIDPlugin_Hypothesis::TSetStrings groupsToRemove = HYBRIDPlugin_Hypothesis::GetGroupsToRemove(_hyp);
1742   const bool toMakeGroupsOfDomains = HYBRIDPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
1743
1744   Ok = Ok && readGMFFile(&mgHybrid,
1745                          aResultFileName.c_str(),
1746                          this,
1747                          theHelper, aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
1748                          aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
1749                          groupsToRemove, toMakeGroupsOfDomains);
1750
1751   updateMeshGroups(theHelper->GetMesh(), groupsToRemove);
1752   removeEmptyGroupsOfDomains( theHelper->GetMesh(), !toMakeGroupsOfDomains );
1753
1754   if ( Ok ) {
1755     HYBRIDPlugin_Hypothesis* that = (HYBRIDPlugin_Hypothesis*)this->_hyp;
1756     if (that)
1757       that->ClearGroupsToRemove();
1758   }
1759   // ---------------------
1760   // remove working files
1761   // ---------------------
1762
1763   if ( Ok )
1764   {
1765     if ( _removeLogOnSuccess )
1766       removeFile( aLogFileName );
1767   }
1768   else if ( mgHybrid.HasLog() )
1769   {
1770     // get problem description from the log file
1771     _Ghs2smdsConvertor conv( aNodeByHybridId );
1772     storeErrorDescription( _logInStandardOutput ? 0 : aLogFileName.c_str(),
1773                            mgHybrid.GetLog(), conv );
1774   }
1775   else {
1776     // the log file is empty
1777     removeFile( aLogFileName );
1778     INFOS( "HYBRID Error, command '" << cmd << "' failed" );
1779     error(COMPERR_ALGO_FAILED, "hybrid: command not found" );
1780   }
1781
1782   if ( !_keepFiles )
1783   {
1784     if (! Ok && _computeCanceled)
1785       removeFile( aLogFileName );
1786     removeFile( aGMFFileName );
1787     removeFile( aResultFileName );
1788     removeFile( aRequiredVerticesFileName );
1789     removeFile( aSolFileName );
1790     removeFile( aResSolFileName );
1791   }
1792   return Ok;
1793 }
1794
1795 void HYBRIDPlugin_HYBRID::CancelCompute()
1796 {
1797   _computeCanceled = true;
1798 #if !defined(WIN32) && !defined(__APPLE__)
1799   std::string cmd = "ps xo pid,args | grep " + _genericName;
1800   //cmd += " | grep -e \"^ *[0-9]\\+ \\+" + HYBRIDPlugin_Hypothesis::GetExeName() + "\"";
1801   cmd += " | awk '{print $1}' | xargs kill -9 > /dev/null 2>&1";
1802   system( cmd.c_str() );
1803 #endif
1804 }
1805
1806 //================================================================================
1807 /*!
1808  * \brief Provide human readable text by error code reported by hybrid
1809  */
1810 //================================================================================
1811
1812 static const char* translateError(const int errNum)
1813 {
1814   switch ( errNum ) {
1815   case 0:
1816     return "error distene 0";
1817   case 1:
1818     return "error distene 1";
1819   }
1820   return "unknown distene error";
1821 }
1822
1823 //================================================================================
1824 /*!
1825  * \brief Retrieve from a string given number of integers
1826  */
1827 //================================================================================
1828
1829 static char* getIds( char* ptr, int nbIds, std::vector<int>& ids )
1830 {
1831   ids.clear();
1832   ids.reserve( nbIds );
1833   while ( nbIds )
1834   {
1835     while ( !isdigit( *ptr )) ++ptr;
1836     if ( ptr[-1] == '-' ) --ptr;
1837     ids.push_back( strtol( ptr, &ptr, 10 ));
1838     --nbIds;
1839   }
1840   return ptr;
1841 }
1842
1843 //================================================================================
1844 /*!
1845  * \brief Retrieve problem description form a log file
1846  *  \retval bool - always false
1847  */
1848 //================================================================================
1849
1850 bool HYBRIDPlugin_HYBRID::storeErrorDescription(const char*                logFile,
1851                                                 const std::string&         log,
1852                                                 const _Ghs2smdsConvertor & toSmdsConvertor )
1853 {
1854   if(_computeCanceled)
1855     return error(SMESH_Comment("interruption initiated by user"));
1856
1857   char* ptr = const_cast<char*>( log.c_str() );
1858   char* buf = ptr, * bufEnd = ptr + log.size();
1859
1860   SMESH_Comment errDescription;
1861
1862   enum { NODE = 1, EDGE, TRIA, VOL, SKIP_ID = 1 };
1863
1864   // look for MeshGems version
1865   // Since "MG-TETRA -- MeshGems 1.1-3 (January, 2013)" error codes change.
1866   // To discriminate old codes from new ones we add 1000000 to the new codes.
1867   // This way value of the new codes is same as absolute value of codes printed
1868   // in the log after "MGMESSAGE" string.
1869   int versionAddition = 0;
1870   {
1871     char* verPtr = ptr;
1872     while ( ++verPtr < bufEnd )
1873     {
1874       if ( strncmp( verPtr, "MG-TETRA -- MeshGems ", 21 ) != 0 )
1875         continue;
1876       if ( strcmp( verPtr, "MG-TETRA -- MeshGems 1.1-3 " ) >= 0 )
1877         versionAddition = 1000000;
1878       ptr = verPtr;
1879       break;
1880     }
1881   }
1882
1883   // look for errors "ERR #"
1884
1885   std::set<std::string> foundErrorStr; // to avoid reporting same error several times
1886   std::set<int>         elemErrorNums; // not to report different types of errors with bad elements
1887   while ( ++ptr < bufEnd )
1888   {
1889     if ( strncmp( ptr, "ERR ", 4 ) != 0 )
1890       continue;
1891
1892     std::list<const SMDS_MeshElement*> badElems;
1893     std::vector<int> nodeIds;
1894
1895     ptr += 4;
1896     char* errBeg = ptr;
1897     int   errNum = strtol(ptr, &ptr, 10) + versionAddition;
1898     // we treat errors enumerated in [SALOME platform 0019316] issue
1899     // and all errors from a new (Release 1.1) MeshGems User Manual
1900     switch ( errNum ) {
1901     case 0015: // The face number (numfac) with vertices (f 1, f 2, f 3) has a null vertex.
1902     case 1005620 : // a too bad quality face is detected. This face is considered degenerated.
1903       ptr = getIds(ptr, SKIP_ID, nodeIds);
1904       ptr = getIds(ptr, TRIA, nodeIds);
1905       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1906       break;
1907     case 1005621 : // a too bad quality face is detected. This face is degenerated.
1908       // hence the is degenerated it is invisible, add its edges in addition
1909       ptr = getIds(ptr, SKIP_ID, nodeIds);
1910       ptr = getIds(ptr, TRIA, nodeIds);
1911       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1912       {
1913         std::vector<int> edgeNodes( nodeIds.begin(), --nodeIds.end() ); // 01
1914         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1915         edgeNodes[1] = nodeIds[2]; // 02
1916         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
1917         edgeNodes[0] = nodeIds[1]; // 12
1918       }      
1919       break;
1920     case 1000: // Face (f 1, f 2, f 3) appears more than once in the input surface mesh.
1921       // ERR  1000 :  1 3 2
1922     case 1002: // Face (f 1, f 2, f 3) has a vertex negative or null
1923     case 3019: // Constrained face (f 1, f 2, f 3) cannot be enforced
1924     case 1002211: // a face has a vertex negative or null.
1925     case 1005200 : // a surface mesh appears more than once in the input surface mesh.
1926     case 1008423 : // a constrained face cannot be enforced (regeneration phase failed).
1927       ptr = getIds(ptr, TRIA, nodeIds);
1928       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1929       break;
1930     case 1001: // Edge (e1, e2) appears more than once in the input surface mesh
1931     case 3009: // Constrained edge (e1, e2) cannot be enforced (warning).
1932       // ERR  3109 :  EDGE  5 6 UNIQUE
1933     case 3109: // Edge (e1, e2) is unique (i.e., bounds a hole in the surface)
1934     case 1005210 : // an edge appears more than once in the input surface mesh.
1935     case 1005820 : // an edge is unique (i.e., bounds a hole in the surface).
1936     case 1008441 : // a constrained edge cannot be enforced.
1937       ptr = getIds(ptr, EDGE, nodeIds);
1938       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1939       break;
1940     case 2004: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
1941     case 2014: // at least two points whose distance is dist, i.e., considered as coincident
1942     case 2103: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
1943       // ERR  2103 :  16 WITH  3
1944     case 1005105 : // two vertices are too close to one another or coincident.
1945     case 1005107: // Two vertices are too close to one another or coincident.
1946       ptr = getIds(ptr, NODE, nodeIds);
1947       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1948       ptr = getIds(ptr, NODE, nodeIds);
1949       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1950       break;
1951     case 2012: // Vertex v1 cannot be inserted (warning).
1952     case 1005106 : // a vertex cannot be inserted.
1953       ptr = getIds(ptr, NODE, nodeIds);
1954       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1955       break;
1956     case 3103: // The surface edge (e1, e2) intersects another surface edge (e3, e4)
1957     case 1005110 : // two surface edges are intersecting.
1958       // ERR  3103 :  1 2 WITH  7 3
1959       ptr = getIds(ptr, EDGE, nodeIds);
1960       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1961       ptr = getIds(ptr, EDGE, nodeIds);
1962       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1963       break;
1964     case 3104: // The surface edge (e1, e2) intersects the surface face (f 1, f 2, f 3)
1965       // ERR  3104 :  9 10 WITH  1 2 3
1966     case 3106: // One surface edge (say e1, e2) intersects a surface face (f 1, f 2, f 3)
1967     case 1005120 : // a surface edge intersects a surface face.
1968       ptr = getIds(ptr, EDGE, nodeIds);
1969       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1970       ptr = getIds(ptr, TRIA, nodeIds);
1971       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1972       break;
1973     case 3105: // One boundary point (say p1) lies within a surface face (f 1, f 2, f 3)
1974       // ERR  3105 :  8 IN  2 3 5
1975     case 1005150 : // a boundary point lies within a surface face.
1976       ptr = getIds(ptr, NODE, nodeIds);
1977       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1978       ptr = getIds(ptr, TRIA, nodeIds);
1979       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1980       break;
1981     case 3107: // One boundary point (say p1) lies within a surface edge (e1, e2) (stop).
1982       // ERR  3107 :  2 IN  4 1
1983     case 1005160 : // a boundary point lies within a surface edge.
1984       ptr = getIds(ptr, NODE, nodeIds);
1985       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1986       ptr = getIds(ptr, EDGE, nodeIds);
1987       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1988       break;
1989     case 9000: // ERR  9000
1990       //  ELEMENT  261 WITH VERTICES :  7 396 -8 242
1991       //  VOLUME   : -1.11325045E+11 W.R.T. EPSILON   0.
1992       // A too small volume element is detected. Are reported the index of the element,
1993       // its four vertex indices, its volume and the tolerance threshold value
1994       ptr = getIds(ptr, SKIP_ID, nodeIds);
1995       ptr = getIds(ptr, VOL, nodeIds);
1996       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
1997       // even if all nodes found, volume it most probably invisible,
1998       // add its faces to demonstrate it anyhow
1999       {
2000         std::vector<int> faceNodes( nodeIds.begin(), --nodeIds.end() ); // 012
2001         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2002         faceNodes[2] = nodeIds[3]; // 013
2003         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2004         faceNodes[1] = nodeIds[2]; // 023
2005         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2006         faceNodes[0] = nodeIds[1]; // 123
2007         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
2008       }
2009       break;
2010     case 9001: // ERR  9001
2011       //  %% NUMBER OF NEGATIVE VOLUME TETS  :  1
2012       //  %% THE LARGEST NEGATIVE TET        :   1.75376581E+11
2013       //  %%  NUMBER OF NULL VOLUME TETS     :  0
2014       // There exists at least a null or negative volume element
2015       break;
2016     case 9002:
2017       // There exist n null or negative volume elements
2018       break;
2019     case 9003:
2020       // A too small volume element is detected
2021       break;
2022     case 9102:
2023       // A too bad quality face is detected. This face is considered degenerated,
2024       // its index, its three vertex indices together with its quality value are reported
2025       break; // same as next
2026     case 9112: // ERR  9112
2027       //  FACE   2 WITH VERTICES :  4 2 5
2028       //  SMALL INRADIUS :   0.
2029       // A too bad quality face is detected. This face is degenerated,
2030       // its index, its three vertex indices together with its inradius are reported
2031       ptr = getIds(ptr, SKIP_ID, nodeIds);
2032       ptr = getIds(ptr, TRIA, nodeIds);
2033       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2034       // add triangle edges as it most probably has zero area and hence invisible
2035       {
2036         std::vector<int> edgeNodes(2);
2037         edgeNodes[0] = nodeIds[0]; edgeNodes[1] = nodeIds[1]; // 0-1
2038         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2039         edgeNodes[1] = nodeIds[2]; // 0-2
2040         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2041         edgeNodes[0] = nodeIds[1]; // 1-2
2042         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
2043       }
2044       break;
2045     case 1005103 : // the vertices of an element are too close to one another or coincident.
2046       ptr = getIds(ptr, TRIA, nodeIds);
2047       if ( nodeIds.back() == 0 ) // index of the third vertex of the element (0 for an edge)
2048         nodeIds.resize( EDGE );
2049       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
2050       break;
2051     }
2052
2053     bool isNewError = foundErrorStr.insert( std::string( errBeg, ptr )).second;
2054     if ( !isNewError )
2055       continue; // not to report same error several times
2056
2057 //     const SMDS_MeshElement* nullElem = 0;
2058 //     bool allElemsOk = ( find( badElems.begin(), badElems.end(), nullElem) == badElems.end());
2059
2060 //     if ( allElemsOk && !badElems.empty() && !elemErrorNums.empty() ) {
2061 //       bool oneMoreErrorType = elemErrorNums.insert( errNum ).second;
2062 //       if ( oneMoreErrorType )
2063 //         continue; // not to report different types of errors with bad elements
2064 //     }
2065
2066     // store bad elements
2067     //if ( allElemsOk ) {
2068       std::list<const SMDS_MeshElement*>::iterator elem = badElems.begin();
2069       for ( ; elem != badElems.end(); ++elem )
2070         addBadInputElement( *elem );
2071       //}
2072
2073     // make error text
2074     std::string text = translateError( errNum );
2075     if ( errDescription.find( text ) == text.npos ) {
2076       if ( !errDescription.empty() )
2077         errDescription << "\n";
2078       errDescription << text;
2079     }
2080
2081   } // end while
2082
2083   if ( errDescription.empty() ) { // no errors found
2084     char msgLic1[] = "connection to server failed";
2085     char msgLic2[] = " Dlim ";
2086     if ( std::search( &buf[0], bufEnd, msgLic1, msgLic1 + strlen(msgLic1)) != bufEnd ||
2087          std::search( &buf[0], bufEnd, msgLic2, msgLic2 + strlen(msgLic2)) != bufEnd )
2088       errDescription << "Licence problems.";
2089     else
2090     {
2091       char msg2[] = "SEGMENTATION FAULT";
2092       if ( std::search( &buf[0], bufEnd, msg2, msg2 + strlen(msg2)) != bufEnd )
2093         errDescription << "hybrid: SEGMENTATION FAULT. ";
2094     }
2095   }
2096
2097   if ( logFile && logFile[0] )
2098   {
2099     if ( errDescription.empty() )
2100       errDescription << "See " << logFile << " for problem description";
2101     else
2102       errDescription << "\nSee " << logFile << " for more information";
2103   }
2104   return error( errDescription );
2105 }
2106
2107 //================================================================================
2108 /*!
2109  * \brief Creates _Ghs2smdsConvertor
2110  */
2111 //================================================================================
2112
2113 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const std::map <int,const SMDS_MeshNode*> & ghs2NodeMap)
2114   :_ghs2NodeMap( & ghs2NodeMap ), _nodeByGhsId( 0 )
2115 {
2116 }
2117
2118 //================================================================================
2119 /*!
2120  * \brief Creates _Ghs2smdsConvertor
2121  */
2122 //================================================================================
2123
2124 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const std::vector <const SMDS_MeshNode*> &  nodeByGhsId)
2125   : _ghs2NodeMap( 0 ), _nodeByGhsId( &nodeByGhsId )
2126 {
2127 }
2128
2129 //================================================================================
2130 /*!
2131  * \brief Return SMDS element by ids of HYBRID nodes
2132  */
2133 //================================================================================
2134
2135 const SMDS_MeshElement* _Ghs2smdsConvertor::getElement(const std::vector<int>& ghsNodes) const
2136 {
2137   size_t nbNodes = ghsNodes.size();
2138   std::vector<const SMDS_MeshNode*> nodes( nbNodes, 0 );
2139   for ( size_t i = 0; i < nbNodes; ++i ) {
2140     int ghsNode = ghsNodes[ i ];
2141     if ( _ghs2NodeMap ) {
2142       std::map <int,const SMDS_MeshNode*>::const_iterator in = _ghs2NodeMap->find( ghsNode);
2143       if ( in == _ghs2NodeMap->end() )
2144         return 0;
2145       nodes[ i ] = in->second;
2146     }
2147     else {
2148       if ( ghsNode < 1 || ghsNode > (int)_nodeByGhsId->size() )
2149         return 0;
2150       nodes[ i ] = (*_nodeByGhsId)[ ghsNode-1 ];
2151     }
2152   }
2153   if ( nbNodes == 1 )
2154     return nodes[0];
2155
2156   if ( nbNodes == 2 ) {
2157     const SMDS_MeshElement* edge= SMDS_Mesh::FindEdge( nodes[0], nodes[1] );
2158     if ( !edge )
2159       edge = new SMDS_LinearEdge( nodes[0], nodes[1] );
2160     return edge;
2161   }
2162   if ( nbNodes == 3 ) {
2163     const SMDS_MeshElement* face = SMDS_Mesh::FindFace( nodes );
2164     if ( !face )
2165       face = new SMDS_FaceOfNodes( nodes[0], nodes[1], nodes[2] );
2166     return face;
2167   }
2168   if ( nbNodes == 4 )
2169     return new SMDS_VolumeOfNodes( nodes[0], nodes[1], nodes[2], nodes[3] );
2170
2171   return 0;
2172 }
2173
2174
2175 //=============================================================================
2176 /*!
2177  *
2178  */
2179 //=============================================================================
2180 bool HYBRIDPlugin_HYBRID::Evaluate(SMESH_Mesh& aMesh,
2181                                  const TopoDS_Shape& aShape,
2182                                  MapShapeNbElems& aResMap)
2183 {
2184   int nbtri = 0, nbqua = 0;
2185   double fullArea = 0.0;
2186   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
2187     TopoDS_Face F = TopoDS::Face( exp.Current() );
2188     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
2189     MapShapeNbElemsItr anIt = aResMap.find(sm);
2190     if( anIt==aResMap.end() ) {
2191       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
2192       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
2193                                             "Submesh can not be evaluated",this));
2194       return false;
2195     }
2196     std::vector<int> aVec = (*anIt).second;
2197     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
2198     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
2199     GProp_GProps G;
2200     BRepGProp::SurfaceProperties(F,G);
2201     double anArea = G.Mass();
2202     fullArea += anArea;
2203   }
2204
2205   // collect info from edges
2206   int nb0d_e = 0, nb1d_e = 0;
2207   bool IsQuadratic = false;
2208   bool IsFirst = true;
2209   TopTools_MapOfShape tmpMap;
2210   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
2211     TopoDS_Edge E = TopoDS::Edge(exp.Current());
2212     if( tmpMap.Contains(E) )
2213       continue;
2214     tmpMap.Add(E);
2215     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
2216     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
2217     std::vector<int> aVec = (*anIt).second;
2218     nb0d_e += aVec[SMDSEntity_Node];
2219     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
2220     if(IsFirst) {
2221       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
2222       IsFirst = false;
2223     }
2224   }
2225   tmpMap.Clear();
2226
2227   double ELen = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
2228
2229   GProp_GProps G;
2230   BRepGProp::VolumeProperties(aShape,G);
2231   double aVolume = G.Mass();
2232   double tetrVol = 0.1179*ELen*ELen*ELen;
2233   double CoeffQuality = 0.9;
2234   int nbVols = int(aVolume/tetrVol/CoeffQuality);
2235   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
2236   int nb1d_in = (int) ( nbVols*6 - nb1d_e - nb1d_f ) / 5;
2237   std::vector<int> aVec(SMDSEntity_Last);
2238   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
2239   if( IsQuadratic ) {
2240     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
2241     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
2242     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
2243   }
2244   else {
2245     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
2246     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
2247     aVec[SMDSEntity_Pyramid] = nbqua;
2248   }
2249   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
2250   aResMap.insert(std::make_pair(sm,aVec));
2251
2252   return true;
2253 }
2254
2255 bool HYBRIDPlugin_HYBRID::importGMFMesh(const char* theGMFFileName, SMESH_Mesh& theMesh)
2256 {
2257   SMESH_ComputeErrorPtr err = theMesh.GMFToMesh( theGMFFileName, /*makeRequiredGroups =*/ true );
2258
2259   theMesh.GetMeshDS()->Modified();
2260
2261   return ( !err || err->IsOK());
2262 }
2263
2264 namespace
2265 {
2266   //================================================================================
2267   /*!
2268    * \brief Sub-mesh event listener setting enforced elements as soon as an enforced
2269    *        mesh is loaded
2270    */
2271   struct _EnforcedMeshRestorer : public SMESH_subMeshEventListener
2272   {
2273     _EnforcedMeshRestorer():
2274       SMESH_subMeshEventListener( /*isDeletable = */true, Name() )
2275     {}
2276
2277     //================================================================================
2278     /*!
2279      * \brief Returns an ID of listener
2280      */
2281     static const char* Name() { return "HYBRIDPlugin_HYBRID::_EnforcedMeshRestorer"; }
2282
2283     //================================================================================
2284     /*!
2285      * \brief Treat events of the subMesh
2286      */
2287     void ProcessEvent(const int                       event,
2288                       const int                       eventType,
2289                       SMESH_subMesh*                  subMesh,
2290                       SMESH_subMeshEventListenerData* data,
2291                       const SMESH_Hypothesis*         hyp)
2292     {
2293       if ( SMESH_subMesh::SUBMESH_LOADED == event &&
2294            SMESH_subMesh::COMPUTE_EVENT  == eventType &&
2295            data &&
2296            !data->mySubMeshes.empty() )
2297       {
2298         // An enforced mesh (subMesh->_father) has been loaded from hdf file
2299         if ( HYBRIDPlugin_Hypothesis* hyp = GetGHSHypothesis( data->mySubMeshes.front() ))
2300           hyp->RestoreEnfElemsByMeshes();
2301       }
2302     }
2303     //================================================================================
2304     /*!
2305      * \brief Returns HYBRIDPlugin_Hypothesis used to compute a subMesh
2306      */
2307     static HYBRIDPlugin_Hypothesis* GetGHSHypothesis( SMESH_subMesh* subMesh )
2308     {
2309       SMESH_HypoFilter ghsHypFilter( SMESH_HypoFilter::HasName( "HYBRID_Parameters" ));
2310       return (HYBRIDPlugin_Hypothesis* )
2311         subMesh->GetFather()->GetHypothesis( subMesh->GetSubShape(),
2312                                              ghsHypFilter,
2313                                              /*visitAncestors=*/true);
2314     }
2315   };
2316
2317   //================================================================================
2318   /*!
2319    * \brief Sub-mesh event listener removing empty groups created due to "To make
2320    *        groups of domains".
2321    */
2322   struct _GroupsOfDomainsRemover : public SMESH_subMeshEventListener
2323   {
2324     _GroupsOfDomainsRemover():
2325       SMESH_subMeshEventListener( /*isDeletable = */true,
2326                                   "HYBRIDPlugin_HYBRID::_GroupsOfDomainsRemover" ) {}
2327     /*!
2328      * \brief Treat events of the subMesh
2329      */
2330     void ProcessEvent(const int                       event,
2331                       const int                       eventType,
2332                       SMESH_subMesh*                  subMesh,
2333                       SMESH_subMeshEventListenerData* data,
2334                       const SMESH_Hypothesis*         hyp)
2335     {
2336       if (SMESH_subMesh::ALGO_EVENT == eventType &&
2337           !subMesh->GetAlgo() )
2338       {
2339         removeEmptyGroupsOfDomains( subMesh->GetFather(), /*notEmptyAsWell=*/true );
2340       }
2341     }
2342   };
2343 }
2344
2345 //================================================================================
2346 /*!
2347  * \brief Set an event listener to set enforced elements as soon as an enforced
2348  *        mesh is loaded
2349  */
2350 //================================================================================
2351
2352 void HYBRIDPlugin_HYBRID::SubmeshRestored(SMESH_subMesh* subMesh)
2353 {
2354   if ( HYBRIDPlugin_Hypothesis* hyp = _EnforcedMeshRestorer::GetGHSHypothesis( subMesh ))
2355   {
2356     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMeshList enfMeshes = hyp->_GetEnforcedMeshes();
2357     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMeshList::iterator it = enfMeshes.begin();
2358     for(;it != enfMeshes.end();++it) {
2359       HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMesh* enfMesh = *it;
2360       if ( SMESH_Mesh* mesh = GetMeshByPersistentID( enfMesh->persistID ))
2361       {
2362         SMESH_subMesh* smToListen = mesh->GetSubMesh( mesh->GetShapeToMesh() );
2363         // a listener set to smToListen will care of hypothesis stored in SMESH_EventListenerData
2364         subMesh->SetEventListener( new _EnforcedMeshRestorer(),
2365                                    SMESH_subMeshEventListenerData::MakeData( subMesh ),
2366                                    smToListen);
2367       }
2368     }
2369   }
2370 }
2371
2372 //================================================================================
2373 /*!
2374  * \brief Sets an event listener removing empty groups created due to "To make
2375  *        groups of domains".
2376  * \param subMesh - submesh where algo is set
2377  *
2378  * This method is called when a submesh gets HYP_OK algo_state.
2379  * After being set, event listener is notified on each event of a submesh.
2380  */
2381 //================================================================================
2382
2383 void HYBRIDPlugin_HYBRID::SetEventListener(SMESH_subMesh* subMesh)
2384 {
2385   subMesh->SetEventListener( new _GroupsOfDomainsRemover(), 0, subMesh );
2386 }