Salome HOME
769bea33fd0cd14412fb060d06093fd987e33c48
[plugins/hybridplugin.git] / src / HYBRIDPlugin / HYBRIDPlugin_HYBRID.cxx
1 // Copyright (C) 2004-2013  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 //=============================================================================
21 // File      : HYBRIDPlugin_HYBRID.cxx
22 // Created   : 
23 // Author    : Edward AGAPOV, modified by Lioka RAZAFINDRAZAKA (CEA) 09/02/2007
24 // Project   : SALOME
25 //=============================================================================
26 //
27 #include "HYBRIDPlugin_HYBRID.hxx"
28 #include "HYBRIDPlugin_Hypothesis.hxx"
29
30 #include <SMDS_FaceOfNodes.hxx>
31 #include <SMDS_MeshElement.hxx>
32 #include <SMDS_MeshNode.hxx>
33 #include <SMDS_VolumeOfNodes.hxx>
34 #include <SMESHDS_Group.hxx>
35 #include <SMESH_Comment.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_OctreeNode.hxx>
43 #include <SMESH_subMeshEventListener.hxx>
44 #include <StdMeshers_QuadToTriaAdaptor.hxx>
45 #include <StdMeshers_ViscousLayers.hxx>
46
47 #include <BRepAdaptor_Surface.hxx>
48 #include <BRepBndLib.hxx>
49 #include <BRepBuilderAPI_MakeVertex.hxx>
50 #include <BRepClass3d.hxx>
51 #include <BRepClass3d_SolidClassifier.hxx>
52 #include <BRepExtrema_DistShapeShape.hxx>
53 #include <BRepGProp.hxx>
54 #include <BRepTools.hxx>
55 #include <BRep_Tool.hxx>
56 #include <Bnd_Box.hxx>
57 #include <GProp_GProps.hxx>
58 #include <GeomAPI_ProjectPointOnSurf.hxx>
59 #include <OSD_File.hxx>
60 #include <Precision.hxx>
61 #include <Standard_ErrorHandler.hxx>
62 #include <Standard_Failure.hxx>
63 #include <Standard_ProgramError.hxx>
64 #include <TopExp.hxx>
65 #include <TopExp_Explorer.hxx>
66 #include <TopTools_IndexedMapOfShape.hxx>
67 #include <TopTools_ListIteratorOfListOfShape.hxx>
68 #include <TopTools_MapOfShape.hxx>
69 #include <TopoDS.hxx>
70 #include <TopoDS_Shell.hxx>
71 #include <TopoDS_Solid.hxx>
72
73 #include <Basics_Utils.hxx>
74 #include <utilities.h>
75
76 #ifdef WIN32
77 #include <io.h>
78 #else
79 #include <sys/sysinfo.h>
80 #endif
81 #include <algorithm>
82
83 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
84
85 extern "C"
86 {
87 #ifndef WIN32
88 #include <unistd.h>
89 #include <sys/mman.h>
90 #endif
91 #include <sys/stat.h>
92 #include <fcntl.h>
93 }
94
95 #define HOLE_ID -1
96
97 typedef const list<const SMDS_MeshFace*> TTriaList;
98
99 static const char theDomainGroupNamePrefix[] = "Domain_";
100
101 static void removeFile( const TCollection_AsciiString& fileName )
102 {
103   try {
104     OSD_File( fileName ).Remove();
105   }
106   catch ( Standard_ProgramError ) {
107     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
108   }
109 }
110
111 //=============================================================================
112 /*!
113  *  
114  */
115 //=============================================================================
116
117 HYBRIDPlugin_HYBRID::HYBRIDPlugin_HYBRID(int hypId, int studyId, SMESH_Gen* gen)
118   : SMESH_3D_Algo(hypId, studyId, gen)
119 {
120   MESSAGE("HYBRIDPlugin_HYBRID::HYBRIDPlugin_HYBRID");
121   _name = Name();
122   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
123   _onlyUnaryInput = false; // Compute() will be called on a compound of solids
124   _iShape=0;
125   _nbShape=0;
126   _compatibleHypothesis.push_back( HYBRIDPlugin_Hypothesis::GetHypType());
127   _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
128   _requireShape = false; // can work without shape_studyId
129
130   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
131   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
132   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
133
134   MESSAGE("studyid = " << _studyId);
135
136   myStudy = NULL;
137   myStudy = aStudyMgr->GetStudyByID(_studyId);
138   if (myStudy)
139     MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
140   
141   _compute_canceled = false;
142 }
143
144 //=============================================================================
145 /*!
146  *  
147  */
148 //=============================================================================
149
150 HYBRIDPlugin_HYBRID::~HYBRIDPlugin_HYBRID()
151 {
152   MESSAGE("HYBRIDPlugin_HYBRID::~HYBRIDPlugin_HYBRID");
153 }
154
155 //=============================================================================
156 /*!
157  *  
158  */
159 //=============================================================================
160
161 bool HYBRIDPlugin_HYBRID::CheckHypothesis ( SMESH_Mesh&         aMesh,
162                                           const TopoDS_Shape& aShape,
163                                           Hypothesis_Status&  aStatus )
164 {
165   aStatus = SMESH_Hypothesis::HYP_OK;
166
167   _hyp = 0;
168   _viscousLayersHyp = 0;
169   _keepFiles = false;
170   _removeLogOnSuccess = true;
171   _logInStandardOutput = false;
172
173   const list <const SMESHDS_Hypothesis * >& hyps =
174     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
175   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
176   for ( ; h != hyps.end(); ++h )
177   {
178     if ( !_hyp )
179       _hyp = dynamic_cast< const HYBRIDPlugin_Hypothesis*> ( *h );
180     if ( !_viscousLayersHyp )
181       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
182   }
183   if ( _hyp )
184   {
185     _keepFiles = _hyp->GetKeepFiles();
186     _removeLogOnSuccess = _hyp->GetRemoveLogOnSuccess();
187     _logInStandardOutput = _hyp->GetStandardOutputLog();
188   }
189
190   return true;
191 }
192
193
194 //=======================================================================
195 //function : entryToShape
196 //purpose  : 
197 //=======================================================================
198
199 TopoDS_Shape HYBRIDPlugin_HYBRID::entryToShape(std::string entry)
200 {
201   MESSAGE("HYBRIDPlugin_HYBRID::entryToShape "<<entry );
202   GEOM::GEOM_Object_var aGeomObj;
203   TopoDS_Shape S = TopoDS_Shape();
204   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
205   if (!aSObj->_is_nil() ) {
206     CORBA::Object_var obj = aSObj->GetObject();
207     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
208     aSObj->UnRegister();
209   }
210   if ( !aGeomObj->_is_nil() )
211     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
212   return S;
213 }
214
215 //=======================================================================
216 //function : findShape
217 //purpose  : 
218 //=======================================================================
219
220 static TopoDS_Shape findShape(const SMDS_MeshNode *aNode[],
221                               TopoDS_Shape        aShape,
222                               const TopoDS_Shape  shape[],
223                               double**            box,
224                               const int           nShape,
225                               TopAbs_State *      state = 0)
226 {
227   gp_XYZ aPnt(0,0,0);
228   int j, iShape, nbNode = 4;
229
230   for ( j=0; j<nbNode; j++ ) {
231     gp_XYZ p ( aNode[j]->X(), aNode[j]->Y(), aNode[j]->Z() );
232     if ( aNode[j]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE ) {
233       aPnt = p;
234       break;
235     }
236     aPnt += p / nbNode;
237   }
238
239   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
240   if (state) *state = SC.State();
241   if ( SC.State() != TopAbs_IN || aShape.IsNull() || aShape.ShapeType() != TopAbs_SOLID) {
242     for (iShape = 0; iShape < nShape; iShape++) {
243       aShape = shape[iShape];
244       if ( !( aPnt.X() < box[iShape][0] || box[iShape][1] < aPnt.X() ||
245               aPnt.Y() < box[iShape][2] || box[iShape][3] < aPnt.Y() ||
246               aPnt.Z() < box[iShape][4] || box[iShape][5] < aPnt.Z()) ) {
247         BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
248         if (state) *state = SC.State();
249         if (SC.State() == TopAbs_IN)
250           break;
251       }
252     }
253   }
254   return aShape;
255 }
256
257 //=======================================================================
258 //function : readMapIntLine
259 //purpose  : 
260 //=======================================================================
261
262 static char* readMapIntLine(char* ptr, int tab[]) {
263   long int intVal;
264   std::cout << std::endl;
265
266   for ( int i=0; i<17; i++ ) {
267     intVal = strtol(ptr, &ptr, 10);
268     if ( i < 3 )
269       tab[i] = intVal;
270   }
271   return ptr;
272 }
273
274 //================================================================================
275 /*!
276  * \brief returns true if a triangle defined by the nodes is a temporary face on a
277  * side facet of pyramid and defines sub-domain inside the pyramid
278  */
279 //================================================================================
280
281 static bool isTmpFace(const SMDS_MeshNode* node1,
282                       const SMDS_MeshNode* node2,
283                       const SMDS_MeshNode* node3)
284 {
285   // find a pyramid sharing the 3 nodes
286   //const SMDS_MeshElement* pyram = 0;
287   SMDS_ElemIteratorPtr vIt1 = node1->GetInverseElementIterator(SMDSAbs_Volume);
288   while ( vIt1->more() )
289   {
290     const SMDS_MeshElement* pyram = vIt1->next();
291     if ( pyram->NbCornerNodes() != 5 ) continue;
292     int i2, i3;
293     if ( (i2 = pyram->GetNodeIndex( node2 )) >= 0 &&
294          (i3 = pyram->GetNodeIndex( node3 )) >= 0 )
295     {
296       // Triangle defines sub-domian inside the pyramid if it's
297       // normal points out of the pyram
298
299       // make i2 and i3 hold indices of base nodes of the pyram while
300       // keeping the nodes order in the triangle
301       const int iApex = 4;
302       if ( i2 == iApex )
303         i2 = i3, i3 = pyram->GetNodeIndex( node1 );
304       else if ( i3 == iApex )
305         i3 = i2, i2 = pyram->GetNodeIndex( node1 );
306
307       int i3base = (i2+1) % 4; // next index after i2 within the pyramid base
308       return ( i3base != i3 );
309     }
310   }
311   return false;
312 }
313
314 //=======================================================================
315 //function : findShapeID
316 //purpose  : find the solid corresponding to HYBRID sub-domain following
317 //           the technique proposed in GHS3D manual (available within
318 //           ghs3d installation) in chapter "B.4 Subdomain (sub-region) assignment".
319 //           In brief: normal of the triangle defined by the given nodes
320 //           points out of the domain it is associated to
321 //=======================================================================
322
323 static int findShapeID(SMESH_Mesh&          mesh,
324                        const SMDS_MeshNode* node1,
325                        const SMDS_MeshNode* node2,
326                        const SMDS_MeshNode* node3,
327                        const bool           toMeshHoles)
328 {
329   const int invalidID = 0;
330   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
331
332   // face the nodes belong to
333   vector<const SMDS_MeshNode *> nodes(3);
334   nodes[0] = node1;
335   nodes[1] = node2;
336   nodes[2] = node3;
337   const SMDS_MeshElement * face = meshDS->FindElement( nodes, SMDSAbs_Face, /*noMedium=*/true);
338   if ( !face )
339     return isTmpFace(node1, node2, node3) ? HOLE_ID : invalidID;
340 #ifdef _DEBUG_
341   std::cout << "bnd face " << face->GetID() << " - ";
342 #endif
343   // geom face the face assigned to
344   SMESH_MeshEditor editor(&mesh);
345   int geomFaceID = editor.FindShape( face );
346   if ( !geomFaceID )
347     return isTmpFace(node1, node2, node3) ? HOLE_ID : invalidID;
348   TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
349   if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
350     return invalidID;
351   TopoDS_Face geomFace = TopoDS::Face( shape );
352
353   // solids bounded by geom face
354   TopTools_IndexedMapOfShape solids, shells;
355   TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
356   for ( ; ansIt.More(); ansIt.Next() ) {
357     switch ( ansIt.Value().ShapeType() ) {
358     case TopAbs_SOLID:
359       solids.Add( ansIt.Value() ); break;
360     case TopAbs_SHELL:
361       shells.Add( ansIt.Value() ); break;
362     default:;
363     }
364   }
365   // analyse found solids
366   if ( solids.Extent() == 0 || shells.Extent() == 0)
367     return invalidID;
368
369   const TopoDS_Solid& solid1 = TopoDS::Solid( solids(1) );
370   if ( solids.Extent() == 1 )
371   {
372     if ( toMeshHoles )
373       return meshDS->ShapeToIndex( solid1 );
374
375     // - Are we at a hole boundary face?
376     if ( shells(1).IsSame( BRepClass3d::OuterShell( solid1 )) )
377     { // - No, but maybe a hole is bound by two shapes? Does shells(1) touches another shell?
378       bool touch = false;
379       TopExp_Explorer eExp( shells(1), TopAbs_EDGE );
380       // check if any edge of shells(1) belongs to another shell
381       for ( ; eExp.More() && !touch; eExp.Next() ) {
382         ansIt = mesh.GetAncestors( eExp.Current() );
383         for ( ; ansIt.More() && !touch; ansIt.Next() ) {
384           if ( ansIt.Value().ShapeType() == TopAbs_SHELL )
385             touch = ( !ansIt.Value().IsSame( shells(1) ));
386         }
387       }
388       if (!touch)
389         return meshDS->ShapeToIndex( solid1 );
390     }
391   }
392   // find orientation of geom face within the first solid
393   TopExp_Explorer fExp( solid1, TopAbs_FACE );
394   for ( ; fExp.More(); fExp.Next() )
395     if ( geomFace.IsSame( fExp.Current() )) {
396       geomFace = TopoDS::Face( fExp.Current() );
397       break;
398     }
399   if ( !fExp.More() )
400     return invalidID; // face not found
401
402   // normale to triangle
403   gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
404   gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
405   gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
406   gp_Vec vec12( node1Pnt, node2Pnt );
407   gp_Vec vec13( node1Pnt, node3Pnt );
408   gp_Vec meshNormal = vec12 ^ vec13;
409   if ( meshNormal.SquareMagnitude() < DBL_MIN )
410     return invalidID;
411
412   // get normale to geomFace at any node
413   bool geomNormalOK = false;
414   gp_Vec geomNormal;
415   SMESH_MesherHelper helper( mesh ); helper.SetSubShape( geomFace );
416   for ( int i = 0; !geomNormalOK && i < 3; ++i )
417   {
418     // find UV of i-th node on geomFace
419     const SMDS_MeshNode* nNotOnSeamEdge = 0;
420     if ( helper.IsSeamShape( nodes[i]->getshapeId() )) {
421       if ( helper.IsSeamShape( nodes[(i+1)%3]->getshapeId() ))
422         nNotOnSeamEdge = nodes[(i+2)%3];
423       else
424         nNotOnSeamEdge = nodes[(i+1)%3];
425     }
426     bool uvOK;
427     gp_XY uv = helper.GetNodeUV( geomFace, nodes[i], nNotOnSeamEdge, &uvOK );
428     // check that uv is correct
429     if (uvOK) {
430       double tol = 1e-6;
431       TopoDS_Shape nodeShape = helper.GetSubShapeByNode( nodes[i], meshDS );
432       if ( !nodeShape.IsNull() )
433         switch ( nodeShape.ShapeType() )
434         {
435         case TopAbs_FACE:   tol = BRep_Tool::Tolerance( TopoDS::Face( nodeShape )); break;
436         case TopAbs_EDGE:   tol = BRep_Tool::Tolerance( TopoDS::Edge( nodeShape )); break;
437         case TopAbs_VERTEX: tol = BRep_Tool::Tolerance( TopoDS::Vertex( nodeShape )); break;
438         default:;
439         }
440       gp_Pnt nodePnt ( nodes[i]->X(), nodes[i]->Y(), nodes[i]->Z() );
441       BRepAdaptor_Surface surface( geomFace );
442       uvOK = ( nodePnt.Distance( surface.Value( uv.X(), uv.Y() )) < 2 * tol );
443       if ( uvOK ) {
444         // normale to geomFace at UV
445         gp_Vec du, dv;
446         surface.D1( uv.X(), uv.Y(), nodePnt, du, dv );
447         geomNormal = du ^ dv;
448         if ( geomFace.Orientation() == TopAbs_REVERSED )
449           geomNormal.Reverse();
450         geomNormalOK = ( geomNormal.SquareMagnitude() > DBL_MIN * 1e3 );
451       }
452     }
453   }
454   if ( !geomNormalOK)
455     return invalidID;
456
457   // compare normals
458   bool isReverse = ( meshNormal * geomNormal ) < 0;
459   if ( !isReverse )
460     return meshDS->ShapeToIndex( solid1 );
461
462   if ( solids.Extent() == 1 )
463     return HOLE_ID; // we are inside a hole
464   else
465     return meshDS->ShapeToIndex( solids(2) );
466 }
467
468
469 //=======================================================================
470 //function : addElemInMeshGroup
471 //purpose  : Update or create groups in mesh
472 //=======================================================================
473
474 static void addElemInMeshGroup(SMESH_Mesh*             theMesh,
475                                const SMDS_MeshElement* anElem,
476                                std::string&            groupName,
477                                std::set<std::string>&  groupsToRemove)
478 {
479   if ( !anElem ) return; // issue 0021776
480
481   bool groupDone = false;
482   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
483   while (grIt->more()) {
484     SMESH_Group * group = grIt->next();
485     if ( !group ) continue;
486     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
487     if ( !groupDS ) continue;
488     if ( groupDS->GetType()==anElem->GetType() &&groupName.compare(group->GetName())==0) {
489       SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
490       aGroupDS->SMDSGroup().Add(anElem);
491       groupDone = true;
492 //       MESSAGE("Successfully added enforced element to existing group " << groupName);
493       break;
494     }
495   }
496   
497   if (!groupDone)
498   {
499     int groupId;
500     SMESH_Group* aGroup = theMesh->AddGroup(anElem->GetType(), groupName.c_str(), groupId);
501     aGroup->SetName( groupName.c_str() );
502     SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
503     aGroupDS->SMDSGroup().Add(anElem);
504 //     MESSAGE("Successfully created enforced vertex group " << groupName);
505     groupDone = true;
506   }
507   if (!groupDone)
508     throw SALOME_Exception(LOCALIZED("A given element was not added to a group"));
509 }
510
511
512 //=======================================================================
513 //function : updateMeshGroups
514 //purpose  : Update or create groups in mesh
515 //=======================================================================
516
517 static void updateMeshGroups(SMESH_Mesh* theMesh, std::set<std::string> groupsToRemove)
518 {
519   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
520   while (grIt->more()) {
521     SMESH_Group * group = grIt->next();
522     if ( !group ) continue;
523     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
524     if ( !groupDS ) continue;
525     std::string currentGroupName = (string)group->GetName();
526     if (groupDS->IsEmpty() && groupsToRemove.find(currentGroupName) != groupsToRemove.end()) {
527       // Previous group created by enforced elements
528       MESSAGE("Delete previous group created by removed enforced elements: " << group->GetName())
529       theMesh->RemoveGroup(groupDS->GetID());
530     }
531   }
532 }
533
534 //=======================================================================
535 //function : removeEmptyGroupsOfDomains
536 //purpose  : remove empty groups named "Domain_nb" created due to
537 //           "To make groups of domains" option.
538 //=======================================================================
539
540 static void removeEmptyGroupsOfDomains(SMESH_Mesh* mesh,
541                                        bool        notEmptyAsWell = false)
542 {
543   const char* refName = theDomainGroupNamePrefix;
544   const size_t refLen = strlen( theDomainGroupNamePrefix );
545
546   std::list<int> groupIDs = mesh->GetGroupIds();
547   std::list<int>::const_iterator id = groupIDs.begin();
548   for ( ; id != groupIDs.end(); ++id )
549   {
550     SMESH_Group* group = mesh->GetGroup( *id );
551     if ( !group || ( !group->GetGroupDS()->IsEmpty() && !notEmptyAsWell ))
552       continue;
553     const char* name = group->GetName();
554     char* end;
555     // check the name
556     if ( strncmp( name, refName, refLen ) == 0 && // starts from refName;
557          isdigit( *( name + refLen )) &&          // refName is followed by a digit;
558          strtol( name + refLen, &end, 10) >= 0 && // there are only digits ...
559          *end == '\0')                            // ... till a string end.
560     {
561       mesh->RemoveGroup( *id );
562     }
563   }
564 }
565
566 //================================================================================
567 /*!
568  * \brief Create the groups corresponding to domains
569  */
570 //================================================================================
571
572 static void makeDomainGroups( std::vector< std::vector< const SMDS_MeshElement* > >& elemsOfDomain,
573                               SMESH_MesherHelper*                                    theHelper)
574 {
575   // int nbDomains = 0;
576   // for ( size_t i = 0; i < elemsOfDomain.size(); ++i )
577   //   nbDomains += ( elemsOfDomain[i].size() > 0 );
578
579   // if ( nbDomains > 1 )
580   for ( size_t iDomain = 0; iDomain < elemsOfDomain.size(); ++iDomain )
581   {
582     std::vector< const SMDS_MeshElement* > & elems = elemsOfDomain[ iDomain ];
583     if ( elems.empty() ) continue;
584
585     // find existing groups
586     std::vector< SMESH_Group* > groupOfType( SMDSAbs_NbElementTypes, (SMESH_Group*)NULL );
587     const std::string domainName = ( SMESH_Comment( theDomainGroupNamePrefix ) << iDomain );
588     SMESH_Mesh::GroupIteratorPtr groupIt = theHelper->GetMesh()->GetGroups();
589     while ( groupIt->more() )
590     {
591       SMESH_Group* group = groupIt->next();
592       if ( domainName == group->GetName() &&
593            dynamic_cast< SMESHDS_Group* >( group->GetGroupDS()) )
594         groupOfType[ group->GetGroupDS()->GetType() ] = group;
595     }
596     // create and fill the groups
597     size_t iElem = 0;
598     int groupID;
599     do
600     {
601       SMESH_Group* group = groupOfType[ elems[ iElem ]->GetType() ];
602       if ( !group )
603         group = theHelper->GetMesh()->AddGroup( elems[ iElem ]->GetType(),
604                                                 domainName.c_str(), groupID );
605       SMDS_MeshGroup& groupDS =
606         static_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
607
608       while ( iElem < elems.size() && groupDS.Add( elems[iElem] ))
609         ++iElem;
610
611     } while ( iElem < elems.size() );
612   }
613 }
614
615 //=======================================================================
616 //function : readGMFFile
617 //purpose  : read GMF file w/o geometry associated to mesh
618 //=======================================================================
619
620 static bool readGMFFile(const char*                     theFile,
621                         HYBRIDPlugin_HYBRID*              theAlgo,
622                         SMESH_MesherHelper*             theHelper,
623                         std::vector <const SMDS_MeshNode*> &    theNodeByHybridId,
624                         std::vector <const SMDS_MeshElement*> & theFaceByHybridId,
625                         map<const SMDS_MeshNode*,int> & theNodeToHybridIdMap,
626                         std::vector<std::string> &      aNodeGroupByHybridId,
627                         std::vector<std::string> &      anEdgeGroupByHybridId,
628                         std::vector<std::string> &      aFaceGroupByHybridId,
629                         std::set<std::string> &         groupsToRemove,
630                         bool                            toMakeGroupsOfDomains=false,
631                         bool                            toMeshHoles=true)
632 {
633   std::string tmpStr;
634   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
635   const bool hasGeom = ( theHelper->GetMesh()->HasShapeToMesh() );
636
637   int nbInitialNodes = theNodeByHybridId.size();
638   int nbMeshNodes = theMeshDS->NbNodes();
639   
640   const bool isQuadMesh = 
641     theHelper->GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
642     theHelper->GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
643     theHelper->GetMesh()->NbVolumes( ORDER_QUADRATIC );
644     
645 #ifdef _DEBUG_
646   std::cout << "theNodeByHybridId.size(): " << nbInitialNodes << std::endl;
647   std::cout << "theHelper->GetMesh()->NbNodes(): " << nbMeshNodes << std::endl;
648   std::cout << "isQuadMesh: " << isQuadMesh << std::endl;
649 #endif
650   
651   // ---------------------------------
652   // Read generated elements and nodes
653   // ---------------------------------
654
655   int nbElem = 0, nbRef = 0;
656   int aGMFNodeID = 0;
657   const SMDS_MeshNode** GMFNode;
658 #ifdef _DEBUG_
659   std::map<int, std::set<int> > subdomainId2tetraId;
660 #endif
661   std::map <GmfKwdCod,int> tabRef;
662   const bool force3d = !hasGeom;
663   const int  noID    = 0;
664
665   tabRef[GmfVertices]       = 3; // for new nodes and enforced nodes
666   tabRef[GmfCorners]        = 1;
667   tabRef[GmfEdges]          = 2; // for enforced edges
668   tabRef[GmfRidges]         = 1;
669   tabRef[GmfTriangles]      = 3; // for enforced faces
670   tabRef[GmfQuadrilaterals] = 4;
671   tabRef[GmfTetrahedra]     = 4; // for new tetras
672   tabRef[GmfPrisms]         = 6; // for new prisms
673   tabRef[GmfHexahedra]      = 8;
674
675   int ver, dim;
676   MESSAGE("Read " << theFile << " file");
677   int InpMsh = GmfOpenMesh(theFile, GmfRead, &ver, &dim);
678   if (!InpMsh)
679     return false;
680   MESSAGE("Done ");
681
682   // Read ids of domains
683   vector< int > solidIDByDomain;
684   if ( hasGeom )
685   {
686     int solid1; // id used in case of 1 domain or some reading failure
687     if ( theHelper->GetSubShape().ShapeType() == TopAbs_SOLID )
688       solid1 = theHelper->GetSubShapeID();
689     else
690       solid1 = theMeshDS->ShapeToIndex
691         ( TopExp_Explorer( theHelper->GetSubShape(), TopAbs_SOLID ).Current() );
692
693     int nbDomains = GmfStatKwd( InpMsh, GmfSubDomainFromGeom );
694     if ( nbDomains > 1 )
695     {
696       solidIDByDomain.resize( nbDomains+1, theHelper->GetSubShapeID() );
697       int faceNbNodes, faceIndex, orientation, domainNb;
698       GmfGotoKwd( InpMsh, GmfSubDomainFromGeom );
699       for ( int i = 0; i < nbDomains; ++i )
700       {
701         faceIndex = 0;
702         GmfGetLin( InpMsh, GmfSubDomainFromGeom,
703                    &faceNbNodes, &faceIndex, &orientation, &domainNb);
704         solidIDByDomain[ domainNb ] = 1;
705         if ( 0 < faceIndex && faceIndex-1 < theFaceByHybridId.size() )
706         {
707           const SMDS_MeshElement* face = theFaceByHybridId[ faceIndex-1 ];
708           const SMDS_MeshNode* nn[3] = { face->GetNode(0),
709                                          face->GetNode(1),
710                                          face->GetNode(2) };
711           if ( orientation < 0 )
712             std::swap( nn[1], nn[2] );
713           solidIDByDomain[ domainNb ] =
714             findShapeID( *theHelper->GetMesh(), nn[0], nn[1], nn[2], toMeshHoles );
715           if ( solidIDByDomain[ domainNb ] > 0 )
716           {
717             const TopoDS_Shape& foundShape = theMeshDS->IndexToShape( solidIDByDomain[ domainNb ] );
718             if ( ! theHelper->IsSubShape( foundShape, theHelper->GetSubShape() ))
719               solidIDByDomain[ domainNb ] = HOLE_ID;
720           }
721         }
722       }
723     }
724     if ( solidIDByDomain.size() < 2 )
725       solidIDByDomain.resize( 2, solid1 );
726   }
727
728   // Issue 0020682. Avoid creating nodes and tetras at place where
729   // volumic elements already exist
730   SMESH_ElementSearcher* elemSearcher = 0;
731   std::vector< const SMDS_MeshElement* > foundVolumes;
732   if ( !hasGeom && theHelper->GetMesh()->NbVolumes() > 0 )
733     elemSearcher = SMESH_MeshAlgos::GetElementSearcher( *theMeshDS );
734   auto_ptr< SMESH_ElementSearcher > elemSearcherDeleter( elemSearcher );
735
736   // IMP 0022172: [CEA 790] create the groups corresponding to domains
737   std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain;
738
739   int nbVertices = GmfStatKwd(InpMsh, GmfVertices) - nbInitialNodes;
740   GMFNode = new const SMDS_MeshNode*[ nbVertices + 1 ];
741
742   std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
743   for ( ; it != tabRef.end() ; ++it)
744   {
745     if(theAlgo->computeCanceled()) {
746       GmfCloseMesh(InpMsh);
747       delete [] GMFNode;
748       return false;
749     }
750     int dummy, solidID;
751     GmfKwdCod token = it->first;
752     nbRef           = it->second;
753
754     nbElem = GmfStatKwd(InpMsh, token);
755     if (nbElem > 0) {
756       GmfGotoKwd(InpMsh, token);
757       std::cout << "Read " << nbElem;
758     }
759     else
760       continue;
761
762     std::vector<int> id (nbElem*tabRef[token]); // node ids
763     std::vector<int> domainID( nbElem ); // domain
764
765     if (token == GmfVertices) {
766       (nbElem <= 1) ? tmpStr = " vertex" : tmpStr = " vertices";
767 //       std::cout << nbInitialNodes << " from input mesh " << std::endl;
768
769       // Remove orphan nodes from previous enforced mesh which was cleared
770 //       if ( nbElem < nbMeshNodes ) {
771 //         const SMDS_MeshNode* node;
772 //         SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
773 //         while ( nodeIt->more() )
774 //         {
775 //           node = nodeIt->next();
776 //           if (theNodeToHybridIdMap.find(node) != theNodeToHybridIdMap.end())
777 //             theMeshDS->RemoveNode(node);
778 //         }
779 //       }
780
781       
782       int aGMFID;
783
784       float VerTab_f[3];
785       double x, y, z;
786       const SMDS_MeshNode * aGMFNode;
787
788       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
789         if(theAlgo->computeCanceled()) {
790           GmfCloseMesh(InpMsh);
791           delete [] GMFNode;
792           return false;
793         }
794         if (ver == GmfFloat) {
795           GmfGetLin(InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
796           x = VerTab_f[0];
797           y = VerTab_f[1];
798           z = VerTab_f[2];
799         }
800         else {
801           GmfGetLin(InpMsh, token, &x, &y, &z, &dummy);
802         }
803         if (iElem >= nbInitialNodes) {
804           if ( elemSearcher &&
805                 elemSearcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_Volume, foundVolumes))
806             aGMFNode = 0;
807           else
808             aGMFNode = theHelper->AddNode(x, y, z);
809           
810           aGMFID = iElem -nbInitialNodes +1;
811           GMFNode[ aGMFID ] = aGMFNode;
812           if (aGMFID-1 < aNodeGroupByHybridId.size() && !aNodeGroupByHybridId.at(aGMFID-1).empty())
813             addElemInMeshGroup(theHelper->GetMesh(), aGMFNode, aNodeGroupByHybridId.at(aGMFID-1), groupsToRemove);
814         }
815       }
816     }
817     else if (token == GmfCorners && nbElem > 0) {
818       (nbElem <= 1) ? tmpStr = " corner" : tmpStr = " corners";
819       for ( int iElem = 0; iElem < nbElem; iElem++ )
820         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
821     }
822     else if (token == GmfRidges && nbElem > 0) {
823       (nbElem <= 1) ? tmpStr = " ridge" : tmpStr = " ridges";
824       for ( int iElem = 0; iElem < nbElem; iElem++ )
825         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
826     }
827     else if (token == GmfEdges && nbElem > 0) {
828       (nbElem <= 1) ? tmpStr = " edge" : tmpStr = " edges";
829       for ( int iElem = 0; iElem < nbElem; iElem++ )
830         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
831     }
832     else if (token == GmfTriangles && nbElem > 0) {
833       (nbElem <= 1) ? tmpStr = " triangle" : tmpStr = " triangles";
834       for ( int iElem = 0; iElem < nbElem; iElem++ )
835         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
836     }
837     else if (token == GmfQuadrilaterals && nbElem > 0) {
838       (nbElem <= 1) ? tmpStr = " Quadrilateral" : tmpStr = " Quadrilaterals";
839       for ( int iElem = 0; iElem < nbElem; iElem++ )
840         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
841     }
842     else if (token == GmfTetrahedra && nbElem > 0) {
843       (nbElem <= 1) ? tmpStr = " Tetrahedron" : tmpStr = " Tetrahedra";
844       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
845         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
846 #ifdef _DEBUG_
847         subdomainId2tetraId[dummy].insert(iElem+1);
848 //         MESSAGE("subdomainId2tetraId["<<dummy<<"].insert("<<iElem+1<<")");
849 #endif
850       }
851     }
852     else if (token == GmfPrisms && nbElem > 0) {
853       (nbElem <= 1) ? tmpStr = " Prism" : tmpStr = " Prisms";
854       for ( int iElem = 0; iElem < nbElem; iElem++ )
855         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
856                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &domainID[iElem]);
857     }
858     else if (token == GmfHexahedra && nbElem > 0) {
859       (nbElem <= 1) ? tmpStr = " Hexahedron" : tmpStr = " Hexahedra";
860       for ( int iElem = 0; iElem < nbElem; iElem++ )
861         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
862                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &domainID[iElem]);
863     }
864     std::cout << tmpStr << std::endl;
865     std::cout << std::endl;
866
867     switch (token) {
868     case GmfCorners:
869     case GmfRidges:
870     case GmfEdges:
871     case GmfTriangles:
872     case GmfQuadrilaterals:
873     case GmfTetrahedra:
874     case GmfPrisms:
875     case GmfHexahedra:
876     {
877       std::vector< const SMDS_MeshNode* > node( nbRef );
878       std::vector< int >          nodeID( nbRef );
879       std::vector< SMDS_MeshNode* > enfNode( nbRef );
880       const SMDS_MeshElement* aCreatedElem;
881
882       for ( int iElem = 0; iElem < nbElem; iElem++ )
883       {
884         if(theAlgo->computeCanceled()) {
885           GmfCloseMesh(InpMsh);
886           delete [] GMFNode;
887           return false;
888         }
889         // Check if elem is already in input mesh. If yes => skip
890         bool fullyCreatedElement = false; // if at least one of the nodes was created
891         for ( int iRef = 0; iRef < nbRef; iRef++ )
892         {
893           aGMFNodeID = id[iElem*tabRef[token]+iRef]; // read nbRef aGMFNodeID
894           if (aGMFNodeID <= nbInitialNodes) // input nodes
895           {
896             aGMFNodeID--;
897             node[ iRef ] = theNodeByHybridId[aGMFNodeID];
898           }
899           else
900           {
901             fullyCreatedElement = true;
902             aGMFNodeID -= nbInitialNodes;
903             nodeID[ iRef ] = aGMFNodeID ;
904             node  [ iRef ] = GMFNode[ aGMFNodeID ];
905           }
906         }
907         aCreatedElem = 0;
908         switch (token)
909         {
910         case GmfEdges:
911           if (fullyCreatedElement) {
912             aCreatedElem = theHelper->AddEdge( node[0], node[1], noID, force3d );
913             if (anEdgeGroupByHybridId.size() && !anEdgeGroupByHybridId[iElem].empty())
914               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, anEdgeGroupByHybridId[iElem], groupsToRemove);
915           }
916           break;
917         case GmfTriangles:
918           if (fullyCreatedElement) {
919             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], noID, force3d );
920             if (aFaceGroupByHybridId.size() && !aFaceGroupByHybridId[iElem].empty())
921               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, aFaceGroupByHybridId[iElem], groupsToRemove);
922           }
923           break;
924         case GmfQuadrilaterals:
925           if (fullyCreatedElement) {
926             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], node[3], noID, force3d );
927           }
928           break;
929         case GmfTetrahedra:
930           if ( hasGeom )
931           {
932             solidID = solidIDByDomain[ domainID[iElem]];
933             if ( solidID != HOLE_ID )
934             {
935               aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
936                                                    noID, force3d );
937               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
938               for ( int iN = 0; iN < 4; ++iN )
939                 if ( node[iN]->getshapeId() < 1 )
940                   theMeshDS->SetNodeInVolume( node[iN], solidID );
941             }
942           }
943           else
944           {
945             if ( elemSearcher ) {
946               // Issue 0020682. Avoid creating nodes and tetras at place where
947               // volumic elements already exist
948               if ( !node[1] || !node[0] || !node[2] || !node[3] )
949                 continue;
950               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
951                                                       SMESH_TNodeXYZ(node[1]) +
952                                                       SMESH_TNodeXYZ(node[2]) +
953                                                       SMESH_TNodeXYZ(node[3]) ) / 4.,
954                                                      SMDSAbs_Volume, foundVolumes ))
955                 break;
956             }
957             aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
958                                                  noID, force3d );
959           }
960           break;
961         case GmfPrisms:
962           if ( hasGeom )
963           {
964             solidID = solidIDByDomain[ domainID[iElem]];
965             if ( solidID != HOLE_ID )
966             {
967               aCreatedElem = theHelper->AddVolume( node[0], node[2], node[1],
968                                                    node[3], node[5], node[4],
969                                                    noID, force3d );
970               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
971               for ( int iN = 0; iN < 6; ++iN )
972                 if ( node[iN]->getshapeId() < 1 )
973                   theMeshDS->SetNodeInVolume( node[iN], solidID );
974             }
975           }
976           else
977           {
978             if ( elemSearcher ) {
979               // Issue 0020682. Avoid creating nodes and tetras at place where
980               // volumic elements already exist
981               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] )
982                 continue;
983               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
984                                                       SMESH_TNodeXYZ(node[1]) +
985                                                       SMESH_TNodeXYZ(node[2]) +
986                                                       SMESH_TNodeXYZ(node[3]) +
987                                                       SMESH_TNodeXYZ(node[4]) +
988                                                       SMESH_TNodeXYZ(node[5])) / 6.,
989                                                      SMDSAbs_Volume, foundVolumes ))
990                 break;
991             }
992             aCreatedElem = theHelper->AddVolume( node[0], node[2], node[1],
993                                                  node[3], node[5], node[4],
994                                                  noID, force3d );
995           }
996           break;
997         case GmfHexahedra:
998           if ( hasGeom )
999           {
1000             solidID = solidIDByDomain[ domainID[iElem]];
1001             if ( solidID != HOLE_ID )
1002             {
1003               aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
1004                                                    node[4], node[7], node[6], node[5],
1005                                                    noID, force3d );
1006               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
1007               for ( int iN = 0; iN < 8; ++iN )
1008                 if ( node[iN]->getshapeId() < 1 )
1009                   theMeshDS->SetNodeInVolume( node[iN], solidID );
1010             }
1011           }
1012           else
1013           {
1014             if ( elemSearcher ) {
1015               // Issue 0020682. Avoid creating nodes and tetras at place where
1016               // volumic elements already exist
1017               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] || !node[6] || !node[7])
1018                 continue;
1019               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
1020                                                       SMESH_TNodeXYZ(node[1]) +
1021                                                       SMESH_TNodeXYZ(node[2]) +
1022                                                       SMESH_TNodeXYZ(node[3]) +
1023                                                       SMESH_TNodeXYZ(node[4]) +
1024                                                       SMESH_TNodeXYZ(node[5]) +
1025                                                       SMESH_TNodeXYZ(node[6]) +
1026                                                       SMESH_TNodeXYZ(node[7])) / 8.,
1027                                                      SMDSAbs_Volume, foundVolumes ))
1028                 break;
1029             }
1030             aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
1031                                                  node[4], node[7], node[6], node[5],
1032                                                  noID, force3d );
1033           }
1034           break;
1035         default: continue;
1036         } // switch (token)
1037
1038         if ( aCreatedElem && toMakeGroupsOfDomains )
1039         {
1040           if ( domainID[iElem] >= (int) elemsOfDomain.size() )
1041             elemsOfDomain.resize( domainID[iElem] + 1 );
1042           elemsOfDomain[ domainID[iElem] ].push_back( aCreatedElem );
1043         }
1044       } // loop on elements of one type
1045       break;
1046     } // case ...
1047     } // switch (token)
1048   } // loop on tabRef
1049
1050   // remove nodes in holes
1051   if ( hasGeom )
1052   {
1053     for ( int i = 1; i <= nbVertices; ++i )
1054       if ( GMFNode[i]->NbInverseElements() == 0 )
1055         theMeshDS->RemoveFreeNode( GMFNode[i], /*sm=*/0, /*fromGroups=*/false );
1056   }
1057
1058   GmfCloseMesh(InpMsh);
1059   delete [] GMFNode;
1060
1061   // 0022172: [CEA 790] create the groups corresponding to domains
1062   if ( toMakeGroupsOfDomains )
1063     makeDomainGroups( elemsOfDomain, theHelper );
1064
1065 #ifdef _DEBUG_
1066   MESSAGE("Nb subdomains " << subdomainId2tetraId.size());
1067   std::map<int, std::set<int> >::const_iterator subdomainIt = subdomainId2tetraId.begin();
1068   TCollection_AsciiString aSubdomainFileName = theFile;
1069   aSubdomainFileName = aSubdomainFileName + ".subdomain";
1070   ofstream aSubdomainFile  ( aSubdomainFileName.ToCString()  , ios::out);
1071
1072   aSubdomainFile << "Nb subdomains " << subdomainId2tetraId.size() << std::endl;
1073   for(;subdomainIt != subdomainId2tetraId.end() ; ++subdomainIt) {
1074     int subdomainId = subdomainIt->first;
1075     std::set<int> tetraIds = subdomainIt->second;
1076     MESSAGE("Subdomain #"<<subdomainId<<": "<<tetraIds.size()<<" tetrahedrons");
1077     std::set<int>::const_iterator tetraIdsIt = tetraIds.begin();
1078     aSubdomainFile << subdomainId << std::endl;
1079     for(;tetraIdsIt != tetraIds.end() ; ++tetraIdsIt) {
1080       aSubdomainFile << (*tetraIdsIt) << " ";
1081     }
1082     aSubdomainFile << std::endl;
1083   }
1084   aSubdomainFile.close();
1085 #endif  
1086   
1087   return true;
1088 }
1089
1090
1091 static bool writeGMFFile(const char*                                     theMeshFileName,
1092                          const char*                                     theRequiredFileName,
1093                          const char*                                     theSolFileName,
1094                          const SMESH_ProxyMesh&                          theProxyMesh,
1095                          SMESH_MesherHelper&                             theHelper,
1096                          std::vector <const SMDS_MeshNode*> &            theNodeByHybridId,
1097                          std::vector <const SMDS_MeshElement*> &         theFaceByHybridId,
1098                          std::map<const SMDS_MeshNode*,int> &            aNodeToHybridIdMap,
1099                          std::vector<std::string> &                      aNodeGroupByHybridId,
1100                          std::vector<std::string> &                      anEdgeGroupByHybridId,
1101                          std::vector<std::string> &                      aFaceGroupByHybridId,
1102                          HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
1103                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
1104                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles,
1105                          std::map<std::vector<double>, std::string> &    enfVerticesWithGroup,
1106                          HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues & theEnforcedVertices)
1107 {
1108   MESSAGE("writeGMFFile w/o geometry");
1109   std::cout << "!!!!!!!!!!!writeGMFFile w/o geometry..." << std::endl;
1110   std::string tmpStr;
1111   int idx, idxRequired = 0, idxSol = 0;
1112   //tabg each dummyint
1113   const int dummyint = 0;
1114   const int dummyint1 = 1;
1115   const int dummyint2 = 2;
1116   const int dummyint3 = 3;
1117   const int dummyint4 = 4;
1118   const int dummyint5 = 5;
1119   const int dummyint6 = 6; //are interesting for layers
1120   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues::const_iterator vertexIt;
1121   std::vector<double> enfVertexSizes;
1122   const SMDS_MeshElement* elem;
1123   TIDSortedElemSet anElemSet, theKeptEnforcedEdges, theKeptEnforcedTriangles;
1124   SMDS_ElemIteratorPtr nodeIt;
1125   std::vector <const SMDS_MeshNode*> theEnforcedNodeByHybridId;
1126   map<const SMDS_MeshNode*,int> anEnforcedNodeToHybridIdMap, anExistingEnforcedNodeToHybridIdMap;
1127   std::vector< const SMDS_MeshElement* > foundElems;
1128   map<const SMDS_MeshNode*,TopAbs_State> aNodeToTopAbs_StateMap;
1129   int nbFoundElems;
1130   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap::iterator elemIt;
1131   TIDSortedElemSet::iterator elemSetIt;
1132   bool isOK;
1133   SMESH_Mesh* theMesh = theHelper.GetMesh();
1134   const bool hasGeom = theMesh->HasShapeToMesh();
1135   auto_ptr< SMESH_ElementSearcher > pntCls
1136     ( SMESH_MeshAlgos::GetElementSearcher(*theMesh->GetMeshDS()));
1137   
1138   int nbEnforcedVertices = theEnforcedVertices.size();
1139   
1140   // count faces
1141   int nbFaces = theProxyMesh.NbFaces();
1142   int nbNodes;
1143   theFaceByHybridId.reserve( nbFaces );
1144   
1145   // groups management
1146   int usedEnforcedNodes = 0;
1147   std::string gn = "";
1148
1149   if ( nbFaces == 0 )
1150     return false;
1151   
1152   idx = GmfOpenMesh(theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1153   if (!idx)
1154     return false;
1155   
1156   // ========================== FACES ==========================
1157   // TRIANGLES ==========================
1158   SMDS_ElemIteratorPtr eIt =
1159     hasGeom ? theProxyMesh.GetFaces( theHelper.GetSubShape()) : theProxyMesh.GetFaces();
1160   while ( eIt->more() )
1161   {
1162     elem = eIt->next();
1163     anElemSet.insert(elem);
1164     nodeIt = elem->nodesIterator();
1165     nbNodes = elem->NbCornerNodes();
1166     while ( nodeIt->more() && nbNodes--)
1167     {
1168       // find HYBRID ID
1169       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1170       int newId = aNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
1171       aNodeToHybridIdMap.insert( make_pair( node, newId ));
1172     }
1173   }
1174   
1175   //EDGES ==========================
1176   
1177   // Iterate over the enforced edges
1178   for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
1179     elem = elemIt->first;
1180     isOK = true;
1181     nodeIt = elem->nodesIterator();
1182     nbNodes = 2;
1183     while ( nodeIt->more() && nbNodes-- ) {
1184       // find HYBRID ID
1185       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1186       // Test if point is inside shape to mesh
1187       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1188       TopAbs_State result = pntCls->GetPointState( myPoint );
1189       if ( result == TopAbs_OUT ) {
1190         isOK = false;
1191         break;
1192       }
1193       aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1194     }
1195     if (isOK) {
1196       nodeIt = elem->nodesIterator();
1197       nbNodes = 2;
1198       int newId = -1;
1199       while ( nodeIt->more() && nbNodes-- ) {
1200         // find HYBRID ID
1201         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1202         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1203         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1204 #ifdef _DEBUG_
1205         std::cout << "Node at "<<node->X()<<", "<<node->Y()<<", "<<node->Z()<<std::endl;
1206         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1207 #endif
1208         if (nbFoundElems ==0) {
1209           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1210             newId = aNodeToHybridIdMap.size() + anEnforcedNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
1211             anEnforcedNodeToHybridIdMap.insert( make_pair( node, newId ));
1212           }
1213         }
1214         else if (nbFoundElems ==1) {
1215           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1216           newId = (*aNodeToHybridIdMap.find(existingNode)).second;
1217           anExistingEnforcedNodeToHybridIdMap.insert( make_pair( node, newId ));
1218         }
1219         else
1220           isOK = false;
1221 #ifdef _DEBUG_
1222         std::cout << "HYBRID node ID: "<<newId<<std::endl;
1223 #endif
1224       }
1225       if (isOK)
1226         theKeptEnforcedEdges.insert(elem);
1227     }
1228   }
1229   
1230   //ENFORCED TRIANGLES ==========================
1231   
1232   // Iterate over the enforced triangles
1233   for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
1234     elem = elemIt->first;
1235     isOK = true;
1236     nodeIt = elem->nodesIterator();
1237     nbNodes = 3;
1238     while ( nodeIt->more() && nbNodes--) {
1239       // find HYBRID ID
1240       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1241       // Test if point is inside shape to mesh
1242       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1243       TopAbs_State result = pntCls->GetPointState( myPoint );
1244       if ( result == TopAbs_OUT ) {
1245         isOK = false;
1246         break;
1247       }
1248       aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1249     }
1250     if (isOK) {
1251       nodeIt = elem->nodesIterator();
1252       nbNodes = 3;
1253       int newId = -1;
1254       while ( nodeIt->more() && nbNodes--) {
1255         // find HYBRID ID
1256         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1257         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1258         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1259 #ifdef _DEBUG_
1260         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1261 #endif
1262         if (nbFoundElems ==0) {
1263           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1264             newId = aNodeToHybridIdMap.size() + anEnforcedNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
1265             anEnforcedNodeToHybridIdMap.insert( make_pair( node, newId ));
1266           }
1267         }
1268         else if (nbFoundElems ==1) {
1269           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1270           newId = (*aNodeToHybridIdMap.find(existingNode)).second;
1271           anExistingEnforcedNodeToHybridIdMap.insert( make_pair( node, newId ));
1272         }
1273         else
1274           isOK = false;
1275 #ifdef _DEBUG_
1276         std::cout << "HYBRID node ID: "<<newId<<std::endl;
1277 #endif
1278       }
1279       if (isOK)
1280         theKeptEnforcedTriangles.insert(elem);
1281     }
1282   }
1283   
1284   // put nodes to theNodeByHybridId vector
1285 #ifdef _DEBUG_
1286   std::cout << "aNodeToHybridIdMap.size(): "<<aNodeToHybridIdMap.size()<<std::endl;
1287 #endif
1288   theNodeByHybridId.resize( aNodeToHybridIdMap.size() );
1289   map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToHybridIdMap.begin();
1290   for ( ; n2id != aNodeToHybridIdMap.end(); ++ n2id)
1291   {
1292 //     std::cout << "n2id->first: "<<n2id->first<<std::endl;
1293     theNodeByHybridId[ n2id->second - 1 ] = n2id->first; // hybrid ids count from 1
1294   }
1295
1296   // put nodes to anEnforcedNodeToHybridIdMap vector
1297 #ifdef _DEBUG_
1298   std::cout << "anEnforcedNodeToHybridIdMap.size(): "<<anEnforcedNodeToHybridIdMap.size()<<std::endl;
1299 #endif
1300   theEnforcedNodeByHybridId.resize( anEnforcedNodeToHybridIdMap.size());
1301   n2id = anEnforcedNodeToHybridIdMap.begin();
1302   for ( ; n2id != anEnforcedNodeToHybridIdMap.end(); ++ n2id)
1303   {
1304     if (n2id->second > aNodeToHybridIdMap.size()) {
1305       theEnforcedNodeByHybridId[ n2id->second - aNodeToHybridIdMap.size() - 1 ] = n2id->first; // hybrid ids count from 1
1306     }
1307   }
1308   
1309   
1310   //========================== NODES ==========================
1311   vector<const SMDS_MeshNode*> theOrderedNodes, theRequiredNodes;
1312   std::set< std::vector<double> > nodesCoords;
1313   vector<const SMDS_MeshNode*>::const_iterator hybridNodeIt = theNodeByHybridId.begin();
1314   vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByHybridId.end();
1315   
1316   (theNodeByHybridId.size() <= 1) ? tmpStr = " node" : " nodes";
1317   std::cout << theNodeByHybridId.size() << tmpStr << " from mesh ..." << std::endl;
1318   for ( ; hybridNodeIt != after; ++hybridNodeIt )
1319   {
1320     const SMDS_MeshNode* node = *hybridNodeIt;
1321     std::vector<double> coords;
1322     coords.push_back(node->X());
1323     coords.push_back(node->Y());
1324     coords.push_back(node->Z());
1325     nodesCoords.insert(coords);
1326     theOrderedNodes.push_back(node);
1327   }
1328   
1329   // Iterate over the enforced nodes given by enforced elements
1330   hybridNodeIt = theEnforcedNodeByHybridId.begin();
1331   after  = theEnforcedNodeByHybridId.end();
1332   (theEnforcedNodeByHybridId.size() <= 1) ? tmpStr = " node" : " nodes";
1333   std::cout << theEnforcedNodeByHybridId.size() << tmpStr << " from enforced elements ..." << std::endl;
1334   for ( ; hybridNodeIt != after; ++hybridNodeIt )
1335   {
1336     const SMDS_MeshNode* node = *hybridNodeIt;
1337     std::vector<double> coords;
1338     coords.push_back(node->X());
1339     coords.push_back(node->Y());
1340     coords.push_back(node->Z());
1341 #ifdef _DEBUG_
1342     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1343 #endif
1344     
1345     if (nodesCoords.find(coords) != nodesCoords.end()) {
1346       // node already exists in original mesh
1347 #ifdef _DEBUG_
1348       std::cout << " found" << std::endl;
1349 #endif
1350       continue;
1351     }
1352     
1353     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1354       // node already exists in enforced vertices
1355 #ifdef _DEBUG_
1356       std::cout << " found" << std::endl;
1357 #endif
1358       continue;
1359     }
1360     
1361 //     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1362 //     nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1363 //     if (nbFoundElems ==0) {
1364 //       std::cout << " not found" << std::endl;
1365 //       if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1366 //         nodesCoords.insert(coords);
1367 //         theOrderedNodes.push_back(node);
1368 //       }
1369 //     }
1370 //     else {
1371 //       std::cout << " found in initial mesh" << std::endl;
1372 //       const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1373 //       nodesCoords.insert(coords);
1374 //       theOrderedNodes.push_back(existingNode);
1375 //     }
1376     
1377 #ifdef _DEBUG_
1378     std::cout << " not found" << std::endl;
1379 #endif
1380     
1381     nodesCoords.insert(coords);
1382     theOrderedNodes.push_back(node);
1383 //     theRequiredNodes.push_back(node);
1384   }
1385   
1386   
1387   // Iterate over the enforced nodes
1388   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt;
1389   (theEnforcedNodes.size() <= 1) ? tmpStr = " node" : " nodes";
1390   std::cout << theEnforcedNodes.size() << tmpStr << " from enforced nodes ..." << std::endl;
1391   for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt)
1392   {
1393     const SMDS_MeshNode* node = enfNodeIt->first;
1394     std::vector<double> coords;
1395     coords.push_back(node->X());
1396     coords.push_back(node->Y());
1397     coords.push_back(node->Z());
1398 #ifdef _DEBUG_
1399     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1400 #endif
1401     
1402     // Test if point is inside shape to mesh
1403     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1404     TopAbs_State result = pntCls->GetPointState( myPoint );
1405     if ( result == TopAbs_OUT ) {
1406 #ifdef _DEBUG_
1407       std::cout << " out of volume" << std::endl;
1408 #endif
1409       continue;
1410     }
1411     
1412     if (nodesCoords.find(coords) != nodesCoords.end()) {
1413 #ifdef _DEBUG_
1414       std::cout << " found in nodesCoords" << std::endl;
1415 #endif
1416 //       theRequiredNodes.push_back(node);
1417       continue;
1418     }
1419
1420     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1421 #ifdef _DEBUG_
1422       std::cout << " found in theEnforcedVertices" << std::endl;
1423 #endif
1424       continue;
1425     }
1426     
1427 //     nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1428 //     if (nbFoundElems ==0) {
1429 //       std::cout << " not found" << std::endl;
1430 //       if (result == TopAbs_IN) {
1431 //         nodesCoords.insert(coords);
1432 //         theRequiredNodes.push_back(node);
1433 //       }
1434 //     }
1435 //     else {
1436 //       std::cout << " found in initial mesh" << std::endl;
1437 //       const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1438 // //       nodesCoords.insert(coords);
1439 //       theRequiredNodes.push_back(existingNode);
1440 //     }
1441 //     
1442 //     
1443 //     
1444 //     if (pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems) == 0)
1445 //       continue;
1446
1447 //     if ( result != TopAbs_IN )
1448 //       continue;
1449     
1450 #ifdef _DEBUG_
1451     std::cout << " not found" << std::endl;
1452 #endif
1453     nodesCoords.insert(coords);
1454 //     theOrderedNodes.push_back(node);
1455     theRequiredNodes.push_back(node);
1456   }
1457   int requiredNodes = theRequiredNodes.size();
1458   
1459   int solSize = 0;
1460   std::vector<std::vector<double> > ReqVerTab;
1461   if (nbEnforcedVertices) {
1462 //    ReqVerTab.clear();
1463     (nbEnforcedVertices <= 1) ? tmpStr = " node" : " nodes";
1464     std::cout << nbEnforcedVertices << tmpStr << " from enforced vertices ..." << std::endl;
1465     // Iterate over the enforced vertices
1466     for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
1467       double x = vertexIt->first[0];
1468       double y = vertexIt->first[1];
1469       double z = vertexIt->first[2];
1470       // Test if point is inside shape to mesh
1471       gp_Pnt myPoint(x,y,z);
1472       TopAbs_State result = pntCls->GetPointState( myPoint );
1473       if ( result == TopAbs_OUT )
1474         continue;
1475       //if (pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems) == 0)
1476       //continue;
1477
1478 //       if ( result != TopAbs_IN )
1479 //         continue;
1480       std::vector<double> coords;
1481       coords.push_back(x);
1482       coords.push_back(y);
1483       coords.push_back(z);
1484       ReqVerTab.push_back(coords);
1485       enfVertexSizes.push_back(vertexIt->second);
1486       solSize++;
1487     }
1488   }
1489   
1490   
1491   // GmfVertices
1492   std::cout << "Begin writting required nodes in GmfVertices" << std::endl;
1493   std::cout << "Nb vertices: " << theOrderedNodes.size() << std::endl;
1494   GmfSetKwd(idx, GmfVertices, theOrderedNodes.size()); //theOrderedNodes.size()+solSize)
1495   for (hybridNodeIt = theOrderedNodes.begin();hybridNodeIt != theOrderedNodes.end();++hybridNodeIt) {
1496     GmfSetLin(idx, GmfVertices, (*hybridNodeIt)->X(), (*hybridNodeIt)->Y(), (*hybridNodeIt)->Z(), dummyint1);
1497   }
1498
1499   std::cout << "End writting required nodes in GmfVertices" << std::endl;
1500
1501   if (requiredNodes + solSize) {
1502     std::cout << "Begin writting in req and sol file" << std::endl;
1503     aNodeGroupByHybridId.resize( requiredNodes + solSize );
1504     idxRequired = GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1505     if (!idxRequired) {
1506       GmfCloseMesh(idx);
1507       return false;
1508     }
1509     idxSol = GmfOpenMesh(theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1510     if (!idxSol) {
1511       GmfCloseMesh(idx);
1512       if (idxRequired)
1513         GmfCloseMesh(idxRequired);
1514       return false;
1515     }
1516     int TypTab[] = {GmfSca};
1517     double ValTab[] = {0.0};
1518     GmfSetKwd(idxRequired, GmfVertices, requiredNodes + solSize);
1519     GmfSetKwd(idxSol, GmfSolAtVertices, requiredNodes + solSize, 1, TypTab);
1520 //     int usedEnforcedNodes = 0;
1521 //     std::string gn = "";
1522     for (hybridNodeIt = theRequiredNodes.begin();hybridNodeIt != theRequiredNodes.end();++hybridNodeIt) {
1523       GmfSetLin(idxRequired, GmfVertices, (*hybridNodeIt)->X(), (*hybridNodeIt)->Y(), (*hybridNodeIt)->Z(), dummyint2);
1524       GmfSetLin(idxSol, GmfSolAtVertices, ValTab);
1525       if (theEnforcedNodes.find((*hybridNodeIt)) != theEnforcedNodes.end())
1526         gn = theEnforcedNodes.find((*hybridNodeIt))->second;
1527       aNodeGroupByHybridId[usedEnforcedNodes] = gn;
1528       usedEnforcedNodes++;
1529     }
1530
1531     for (int i=0;i<solSize;i++) {
1532       std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
1533 #ifdef _DEBUG_
1534       std::cout << "enfVertexSizes.at("<<i<<"): " << enfVertexSizes.at(i) << std::endl;
1535 #endif
1536       double solTab[] = {enfVertexSizes.at(i)};
1537       GmfSetLin(idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint3);
1538       GmfSetLin(idxSol, GmfSolAtVertices, solTab);
1539       aNodeGroupByHybridId[usedEnforcedNodes] = enfVerticesWithGroup.find(ReqVerTab[i])->second;
1540 #ifdef _DEBUG_
1541       std::cout << "aNodeGroupByHybridId["<<usedEnforcedNodes<<"] = \""<<aNodeGroupByHybridId[usedEnforcedNodes]<<"\""<<std::endl;
1542 #endif
1543       usedEnforcedNodes++;
1544     }
1545     std::cout << "End writting in req and sol file" << std::endl;
1546   }
1547
1548   int nedge[2], ntri[3];
1549     
1550   // GmfEdges
1551   int usedEnforcedEdges = 0;
1552   if (theKeptEnforcedEdges.size()) {
1553     anEdgeGroupByHybridId.resize( theKeptEnforcedEdges.size() );
1554 //    idxRequired = GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1555 //    if (!idxRequired)
1556 //      return false;
1557     GmfSetKwd(idx, GmfEdges, theKeptEnforcedEdges.size());
1558 //    GmfSetKwd(idxRequired, GmfEdges, theKeptEnforcedEdges.size());
1559     for(elemSetIt = theKeptEnforcedEdges.begin() ; elemSetIt != theKeptEnforcedEdges.end() ; ++elemSetIt) {
1560       elem = (*elemSetIt);
1561       nodeIt = elem->nodesIterator();
1562       int index=0;
1563       while ( nodeIt->more() ) {
1564         // find HYBRID ID
1565         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1566         map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToHybridIdMap.find(node);
1567         if (it == anEnforcedNodeToHybridIdMap.end()) {
1568           it = anExistingEnforcedNodeToHybridIdMap.find(node);
1569           if (it == anEnforcedNodeToHybridIdMap.end())
1570             throw "Node not found";
1571         }
1572         nedge[index] = it->second;
1573         index++;
1574       }
1575       GmfSetLin(idx, GmfEdges, nedge[0], nedge[1], dummyint4);
1576       anEdgeGroupByHybridId[usedEnforcedEdges] = theEnforcedEdges.find(elem)->second;
1577 //      GmfSetLin(idxRequired, GmfEdges, nedge[0], nedge[1], dummyint);
1578       usedEnforcedEdges++;
1579     }
1580 //    GmfCloseMesh(idxRequired);
1581   }
1582
1583
1584   if (usedEnforcedEdges) {
1585     GmfSetKwd(idx, GmfRequiredEdges, usedEnforcedEdges);
1586     for (int enfID=1;enfID<=usedEnforcedEdges;enfID++) {
1587       GmfSetLin(idx, GmfRequiredEdges, enfID);
1588     }
1589   }
1590
1591   // GmfTriangles
1592   int usedEnforcedTriangles = 0;
1593   if (anElemSet.size()+theKeptEnforcedTriangles.size()) {
1594     aFaceGroupByHybridId.resize( anElemSet.size()+theKeptEnforcedTriangles.size() );
1595     GmfSetKwd(idx, GmfTriangles, anElemSet.size()+theKeptEnforcedTriangles.size());
1596     int k=0;
1597     for(elemSetIt = anElemSet.begin() ; elemSetIt != anElemSet.end() ; ++elemSetIt,++k) {
1598       elem = (*elemSetIt);
1599       theFaceByHybridId.push_back( elem );
1600       nodeIt = elem->nodesIterator();
1601       int index=0;
1602       for ( int j = 0; j < 3; ++j ) {
1603         // find HYBRID ID
1604         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1605         map< const SMDS_MeshNode*,int >::iterator it = aNodeToHybridIdMap.find(node);
1606         if (it == aNodeToHybridIdMap.end())
1607           throw "Node not found";
1608         ntri[index] = it->second;
1609         index++;
1610       }
1611       GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint5);
1612       aFaceGroupByHybridId[k] = "";
1613     }
1614     if ( !theHelper.GetMesh()->HasShapeToMesh() )
1615       SMESHUtils::FreeVector( theFaceByHybridId );
1616     if (theKeptEnforcedTriangles.size()) {
1617       for(elemSetIt = theKeptEnforcedTriangles.begin() ; elemSetIt != theKeptEnforcedTriangles.end() ; ++elemSetIt,++k) {
1618         elem = (*elemSetIt);
1619         nodeIt = elem->nodesIterator();
1620         int index=0;
1621         for ( int j = 0; j < 3; ++j ) {
1622           // find HYBRID ID
1623           const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1624           map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToHybridIdMap.find(node);
1625           if (it == anEnforcedNodeToHybridIdMap.end()) {
1626             it = anExistingEnforcedNodeToHybridIdMap.find(node);
1627             if (it == anEnforcedNodeToHybridIdMap.end())
1628               throw "Node not found";
1629           }
1630           ntri[index] = it->second;
1631           index++;
1632         }
1633         GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint6);
1634         aFaceGroupByHybridId[k] = theEnforcedTriangles.find(elem)->second;
1635         usedEnforcedTriangles++;
1636       }
1637     }
1638   }
1639
1640   
1641   if (usedEnforcedTriangles) {
1642     GmfSetKwd(idx, GmfRequiredTriangles, usedEnforcedTriangles);
1643     for (int enfID=1;enfID<=usedEnforcedTriangles;enfID++)
1644       GmfSetLin(idx, GmfRequiredTriangles, anElemSet.size()+enfID);
1645   }
1646
1647   GmfCloseMesh(idx);
1648   if (idxRequired)
1649     GmfCloseMesh(idxRequired);
1650   if (idxSol)
1651     GmfCloseMesh(idxSol);
1652   
1653   return true;
1654   
1655 }
1656
1657 // static bool writeGMFFile(const char*                                    theMeshFileName,
1658 //                         const char*                                     theRequiredFileName,
1659 //                         const char*                                     theSolFileName,
1660 //                         SMESH_MesherHelper&                             theHelper,
1661 //                         const SMESH_ProxyMesh&                          theProxyMesh,
1662 //                         std::map <int,int> &                            theNodeId2NodeIndexMap,
1663 //                         std::map <int,int> &                            theSmdsToHybridIdMap,
1664 //                         std::map <int,const SMDS_MeshNode*> &           theHybridIdToNodeMap,
1665 //                         TIDSortedNodeSet &                              theEnforcedNodes,
1666 //                         TIDSortedElemSet &                              theEnforcedEdges,
1667 //                         TIDSortedElemSet &                              theEnforcedTriangles,
1668 // //                         TIDSortedElemSet &                              theEnforcedQuadrangles,
1669 //                         HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues & theEnforcedVertices)
1670 // {
1671 //   MESSAGE("writeGMFFile with geometry");
1672 //   int idx, idxRequired, idxSol;
1673 //   int nbv, nbev, nben, aHybridID = 0;
1674 //   const int dummyint = 0;
1675 //   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues::const_iterator vertexIt;
1676 //   std::vector<double> enfVertexSizes;
1677 //   TIDSortedNodeSet::const_iterator enfNodeIt;
1678 //   const SMDS_MeshNode* node;
1679 //   SMDS_NodeIteratorPtr nodeIt;
1680 // 
1681 //   idx = GmfOpenMesh(theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1682 //   if (!idx)
1683 //     return false;
1684 //   
1685 //   SMESHDS_Mesh * theMeshDS = theHelper.GetMeshDS();
1686 //   
1687 //   /* ========================== NODES ========================== */
1688 //   // NB_NODES
1689 //   nbv = theMeshDS->NbNodes();
1690 //   if ( nbv == 0 )
1691 //     return false;
1692 //   nbev = theEnforcedVertices.size();
1693 //   nben = theEnforcedNodes.size();
1694 //   
1695 //   // Issue 020674: EDF 870 SMESH: Mesh generated by Netgen not usable by HYBRID
1696 //   // The problem is in nodes on degenerated edges, we need to skip nodes which are free
1697 //   // and replace not-free nodes on edges by the node on vertex
1698 //   TNodeNodeMap n2nDegen; // map a node on degenerated edge to a node on vertex
1699 //   TNodeNodeMap::iterator n2nDegenIt;
1700 //   if ( theHelper.HasDegeneratedEdges() )
1701 //   {
1702 //     set<int> checkedSM;
1703 //     for (TopExp_Explorer e(theMeshDS->ShapeToMesh(), TopAbs_EDGE ); e.More(); e.Next())
1704 //     {
1705 //       SMESH_subMesh* sm = theHelper.GetMesh()->GetSubMesh( e.Current() );
1706 //       if ( checkedSM.insert( sm->GetId() ).second && theHelper.IsDegenShape(sm->GetId() ))
1707 //       {
1708 //         if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
1709 //         {
1710 //           TopoDS_Shape vertex = TopoDS_Iterator( e.Current() ).Value();
1711 //           const SMDS_MeshNode* vNode = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), theMeshDS);
1712 //           {
1713 //             SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1714 //             while ( nIt->more() )
1715 //               n2nDegen.insert( make_pair( nIt->next(), vNode ));
1716 //           }
1717 //         }
1718 //       }
1719 //     }
1720 //   }
1721 //   
1722 //   const bool isQuadMesh = 
1723 //     theHelper.GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
1724 //     theHelper.GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
1725 //     theHelper.GetMesh()->NbVolumes( ORDER_QUADRATIC );
1726 // 
1727 //   std::vector<std::vector<double> > VerTab;
1728 //   std::set<std::vector<double> > VerMap;
1729 //   VerTab.clear();
1730 //   std::vector<double> aVerTab;
1731 //   // Loop from 1 to NB_NODES
1732 // 
1733 //   nodeIt = theMeshDS->nodesIterator();
1734 //   
1735 //   while ( nodeIt->more() )
1736 //   {
1737 //     node = nodeIt->next();
1738 //     if ( isQuadMesh && theHelper.IsMedium( node )) // Issue 0021238
1739 //       continue;
1740 //     if ( n2nDegen.count( node ) ) // Issue 0020674
1741 //       continue;
1742 // 
1743 //     std::vector<double> coords;
1744 //     coords.push_back(node->X());
1745 //     coords.push_back(node->Y());
1746 //     coords.push_back(node->Z());
1747 //     if (VerMap.find(coords) != VerMap.end()) {
1748 //       aHybridID = theSmdsToHybridIdMap[node->GetID()];
1749 //       theHybridIdToNodeMap[theSmdsToHybridIdMap[node->GetID()]] = node;
1750 //       continue;
1751 //     }
1752 //     VerTab.push_back(coords);
1753 //     VerMap.insert(coords);
1754 //     aHybridID++;
1755 //     theSmdsToHybridIdMap.insert( make_pair( node->GetID(), aHybridID ));
1756 //     theHybridIdToNodeMap.insert( make_pair( aHybridID, node ));
1757 //   }
1758 //   
1759 //   
1760 //   /* ENFORCED NODES ========================== */
1761 //   if (nben) {
1762 //     std::cout << "Add " << nben << " enforced nodes to input .mesh file" << std::endl;
1763 //     for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt) {
1764 //       double x = (*enfNodeIt)->X();
1765 //       double y = (*enfNodeIt)->Y();
1766 //       double z = (*enfNodeIt)->Z();
1767 //       // Test if point is inside shape to mesh
1768 //       gp_Pnt myPoint(x,y,z);
1769 //       BRepClass3d_SolidClassifier scl(theMeshDS->ShapeToMesh());
1770 //       scl.Perform(myPoint, 1e-7);
1771 //       TopAbs_State result = scl.State();
1772 //       if ( result != TopAbs_IN )
1773 //         continue;
1774 //       std::vector<double> coords;
1775 //       coords.push_back(x);
1776 //       coords.push_back(y);
1777 //       coords.push_back(z);
1778 //       if (theEnforcedVertices.find(coords) != theEnforcedVertices.end())
1779 //         continue;
1780 //       if (VerMap.find(coords) != VerMap.end())
1781 //         continue;
1782 //       VerTab.push_back(coords);
1783 //       VerMap.insert(coords);
1784 //       aHybridID++;
1785 //       theNodeId2NodeIndexMap.insert( make_pair( (*enfNodeIt)->GetID(), aHybridID ));
1786 //     }
1787 //   }
1788 //     
1789 //   
1790 //   /* ENFORCED VERTICES ========================== */
1791 //   int solSize = 0;
1792 //   std::vector<std::vector<double> > ReqVerTab;
1793 //   ReqVerTab.clear();
1794 //   if (nbev) {
1795 //     std::cout << "Add " << nbev << " enforced vertices to input .mesh file" << std::endl;
1796 //     for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
1797 //       double x = vertexIt->first[0];
1798 //       double y = vertexIt->first[1];
1799 //       double z = vertexIt->first[2];
1800 //       // Test if point is inside shape to mesh
1801 //       gp_Pnt myPoint(x,y,z);
1802 //       BRepClass3d_SolidClassifier scl(theMeshDS->ShapeToMesh());
1803 //       scl.Perform(myPoint, 1e-7);
1804 //       TopAbs_State result = scl.State();
1805 //       if ( result != TopAbs_IN )
1806 //         continue;
1807 //       enfVertexSizes.push_back(vertexIt->second);
1808 //       std::vector<double> coords;
1809 //       coords.push_back(x);
1810 //       coords.push_back(y);
1811 //       coords.push_back(z);
1812 //       if (VerMap.find(coords) != VerMap.end())
1813 //         continue;
1814 //       ReqVerTab.push_back(coords);
1815 //       VerMap.insert(coords);
1816 //       solSize++;
1817 //     }
1818 //   }
1819 // 
1820 //   
1821 //   /* ========================== FACES ========================== */
1822 //   
1823 //   int nbTriangles = 0/*, nbQuadrangles = 0*/, aSmdsID;
1824 //   TopTools_IndexedMapOfShape facesMap, trianglesMap/*, quadranglesMap*/;
1825 //   TIDSortedElemSet::const_iterator elemIt;
1826 //   const SMESHDS_SubMesh* theSubMesh;
1827 //   TopoDS_Shape aShape;
1828 //   SMDS_ElemIteratorPtr itOnSubMesh, itOnSubFace;
1829 //   const SMDS_MeshElement* aFace;
1830 //   map<int,int>::const_iterator itOnMap;
1831 //   std::vector<std::vector<int> > tt, qt,et;
1832 //   tt.clear();
1833 //   qt.clear();
1834 //   et.clear();
1835 //   std::vector<int> att, aqt, aet;
1836 //   
1837 //   TopExp::MapShapes( theMeshDS->ShapeToMesh(), TopAbs_FACE, facesMap );
1838 // 
1839 //   for ( int i = 1; i <= facesMap.Extent(); ++i )
1840 //     if (( theSubMesh  = theProxyMesh.GetSubMesh( facesMap(i))))
1841 //     {
1842 //       SMDS_ElemIteratorPtr it = theSubMesh->GetElements();
1843 //       while (it->more())
1844 //       {
1845 //         const SMDS_MeshElement *elem = it->next();
1846 //         int nbCornerNodes = elem->NbCornerNodes();
1847 //         if (nbCornerNodes == 3)
1848 //         {
1849 //           trianglesMap.Add(facesMap(i));
1850 //           nbTriangles ++;
1851 //         }
1852 // //         else if (nbCornerNodes == 4)
1853 // //         {
1854 // //           quadranglesMap.Add(facesMap(i));
1855 // //           nbQuadrangles ++;
1856 // //         }
1857 //       }
1858 //     }
1859 //     
1860 //   /* TRIANGLES ========================== */
1861 //   if (nbTriangles) {
1862 //     for ( int i = 1; i <= trianglesMap.Extent(); i++ )
1863 //     {
1864 //       aShape = trianglesMap(i);
1865 //       theSubMesh = theProxyMesh.GetSubMesh(aShape);
1866 //       if ( !theSubMesh ) continue;
1867 //       itOnSubMesh = theSubMesh->GetElements();
1868 //       while ( itOnSubMesh->more() )
1869 //       {
1870 //         aFace = itOnSubMesh->next();
1871 //         itOnSubFace = aFace->nodesIterator();
1872 //         att.clear();
1873 //         for ( int j = 0; j < 3; ++j ) {
1874 //           // find HYBRID ID
1875 //           node = castToNode( itOnSubFace->next() );
1876 //           if (( n2nDegenIt = n2nDegen.find( node )) != n2nDegen.end() )
1877 //             node = n2nDegenIt->second;
1878 //           aSmdsID = node->GetID();
1879 //           itOnMap = theSmdsToHybridIdMap.find( aSmdsID );
1880 //           ASSERT( itOnMap != theSmdsToHybridIdMap.end() );
1881 //           att.push_back((*itOnMap).second);
1882 //         }
1883 //         tt.push_back(att);
1884 //       }
1885 //     }
1886 //   }
1887 // 
1888 //   if (theEnforcedTriangles.size()) {
1889 //     std::cout << "Add " << theEnforcedTriangles.size() << " enforced triangles to input .mesh file" << std::endl;
1890 //     // Iterate over the enforced triangles
1891 //     for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
1892 //       aFace = (*elemIt);
1893 //       itOnSubFace = aFace->nodesIterator();
1894 //       bool isOK = true;
1895 //       att.clear();
1896 //       
1897 //       for ( int j = 0; j < 3; ++j ) {
1898 //         node = castToNode( itOnSubFace->next() );
1899 //         if (( n2nDegenIt = n2nDegen.find( node )) != n2nDegen.end() )
1900 //           node = n2nDegenIt->second;
1901 // //         std::cout << node;
1902 //         double x = node->X();
1903 //         double y = node->Y();
1904 //         double z = node->Z();
1905 //         // Test if point is inside shape to mesh
1906 //         gp_Pnt myPoint(x,y,z);
1907 //         BRepClass3d_SolidClassifier scl(theMeshDS->ShapeToMesh());
1908 //         scl.Perform(myPoint, 1e-7);
1909 //         TopAbs_State result = scl.State();
1910 //         if ( result != TopAbs_IN ) {
1911 //           isOK = false;
1912 //           theEnforcedTriangles.erase(elemIt);
1913 //           continue;
1914 //         }
1915 //         std::vector<double> coords;
1916 //         coords.push_back(x);
1917 //         coords.push_back(y);
1918 //         coords.push_back(z);
1919 //         if (VerMap.find(coords) != VerMap.end()) {
1920 //           att.push_back(theNodeId2NodeIndexMap[node->GetID()]);
1921 //           continue;
1922 //         }
1923 //         VerTab.push_back(coords);
1924 //         VerMap.insert(coords);
1925 //         aHybridID++;
1926 //         theNodeId2NodeIndexMap.insert( make_pair( node->GetID(), aHybridID ));
1927 //         att.push_back(aHybridID);
1928 //       }
1929 //       if (isOK)
1930 //         tt.push_back(att);
1931 //     }
1932 //   }
1933 // 
1934 // 
1935 //   /* ========================== EDGES ========================== */
1936 // 
1937 //   if (theEnforcedEdges.size()) {
1938 //     // Iterate over the enforced edges
1939 //     std::cout << "Add " << theEnforcedEdges.size() << " enforced edges to input .mesh file" << std::endl;
1940 //     for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
1941 //       aFace = (*elemIt);
1942 //       bool isOK = true;
1943 //       itOnSubFace = aFace->nodesIterator();
1944 //       aet.clear();
1945 //       for ( int j = 0; j < 2; ++j ) {
1946 //         node = castToNode( itOnSubFace->next() );
1947 //         if (( n2nDegenIt = n2nDegen.find( node )) != n2nDegen.end() )
1948 //           node = n2nDegenIt->second;
1949 //         double x = node->X();
1950 //         double y = node->Y();
1951 //         double z = node->Z();
1952 //         // Test if point is inside shape to mesh
1953 //         gp_Pnt myPoint(x,y,z);
1954 //         BRepClass3d_SolidClassifier scl(theMeshDS->ShapeToMesh());
1955 //         scl.Perform(myPoint, 1e-7);
1956 //         TopAbs_State result = scl.State();
1957 //         if ( result != TopAbs_IN ) {
1958 //           isOK = false;
1959 //           theEnforcedEdges.erase(elemIt);
1960 //           continue;
1961 //         }
1962 //         std::vector<double> coords;
1963 //         coords.push_back(x);
1964 //         coords.push_back(y);
1965 //         coords.push_back(z);
1966 //         if (VerMap.find(coords) != VerMap.end()) {
1967 //           aet.push_back(theNodeId2NodeIndexMap[node->GetID()]);
1968 //           continue;
1969 //         }
1970 //         VerTab.push_back(coords);
1971 //         VerMap.insert(coords);
1972 //         
1973 //         aHybridID++;
1974 //         theNodeId2NodeIndexMap.insert( make_pair( node->GetID(), aHybridID ));
1975 //         aet.push_back(aHybridID);
1976 //       }
1977 //       if (isOK)
1978 //         et.push_back(aet);
1979 //     }
1980 //   }
1981 // 
1982 // 
1983 //   /* Write vertices number */
1984 //   MESSAGE("Number of vertices: "<<aHybridID);
1985 //   MESSAGE("Size of vector: "<<VerTab.size());
1986 //   GmfSetKwd(idx, GmfVertices, aHybridID/*+solSize*/);
1987 //   for (int i=0;i<aHybridID;i++)
1988 //     GmfSetLin(idx, GmfVertices, VerTab[i][0], VerTab[i][1], VerTab[i][2], dummyint);
1989 // //   for (int i=0;i<solSize;i++) {
1990 // //     std::cout << ReqVerTab[i][0] <<" "<< ReqVerTab[i][1] << " "<< ReqVerTab[i][2] << std::endl;
1991 // //     GmfSetLin(idx, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
1992 // //   }
1993 // 
1994 //   if (solSize) {
1995 //     idxRequired = GmfOpenMesh(theRequiredFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1996 //     if (!idxRequired) {
1997 //       GmfCloseMesh(idx);
1998 //       return false;
1999 //     }
2000 //     idxSol = GmfOpenMesh(theSolFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
2001 //     if (!idxSol){
2002 //       GmfCloseMesh(idx);
2003 //       if (idxRequired)
2004 //         GmfCloseMesh(idxRequired);
2005 //       return false;
2006 //     }
2007 //     
2008 //     int TypTab[] = {GmfSca};
2009 //     GmfSetKwd(idxRequired, GmfVertices, solSize);
2010 //     GmfSetKwd(idxSol, GmfSolAtVertices, solSize, 1, TypTab);
2011 //     
2012 //     for (int i=0;i<solSize;i++) {
2013 //       double solTab[] = {enfVertexSizes.at(i)};
2014 //       GmfSetLin(idxRequired, GmfVertices, ReqVerTab[i][0], ReqVerTab[i][1], ReqVerTab[i][2], dummyint);
2015 //       GmfSetLin(idxSol, GmfSolAtVertices, solTab);
2016 //     }
2017 //     GmfCloseMesh(idxRequired);
2018 //     GmfCloseMesh(idxSol);
2019 //   }
2020 //   
2021 //   /* Write triangles number */
2022 //   if (tt.size()) {
2023 //     GmfSetKwd(idx, GmfTriangles, tt.size());
2024 //     for (int i=0;i<tt.size();i++)
2025 //       GmfSetLin(idx, GmfTriangles, tt[i][0], tt[i][1], tt[i][2], dummyint);
2026 //   }  
2027 //   
2028 //   /* Write edges number */
2029 //   if (et.size()) {
2030 //     GmfSetKwd(idx, GmfEdges, et.size());
2031 //     for (int i=0;i<et.size();i++)
2032 //       GmfSetLin(idx, GmfEdges, et[i][0], et[i][1], dummyint);
2033 //   }
2034 // 
2035 //   /* QUADRANGLES ========================== */
2036 //   // TODO: add pyramids ?
2037 // //   if (nbQuadrangles) {
2038 // //     for ( int i = 1; i <= quadranglesMap.Extent(); i++ )
2039 // //     {
2040 // //       aShape = quadranglesMap(i);
2041 // //       theSubMesh = theProxyMesh.GetSubMesh(aShape);
2042 // //       if ( !theSubMesh ) continue;
2043 // //       itOnSubMesh = theSubMesh->GetElements();
2044 // //       for ( int j = 0; j < 4; ++j )
2045 // //       {
2046 // //         aFace = itOnSubMesh->next();
2047 // //         itOnSubFace = aFace->nodesIterator();
2048 // //         aqt.clear();
2049 // //         while ( itOnSubFace->more() ) {
2050 // //           // find HYBRID ID
2051 // //           aSmdsID = itOnSubFace->next()->GetID();
2052 // //           itOnMap = theSmdsToHybridIdMap.find( aSmdsID );
2053 // //           ASSERT( itOnMap != theSmdsToHybridIdMap.end() );
2054 // //           aqt.push_back((*itOnMap).second);
2055 // //         }
2056 // //         qt.push_back(aqt);
2057 // //       }
2058 // //     }
2059 // //   }
2060 // // 
2061 // //   if (theEnforcedQuadrangles.size()) {
2062 // //     // Iterate over the enforced triangles
2063 // //     for(elemIt = theEnforcedQuadrangles.begin() ; elemIt != theEnforcedQuadrangles.end() ; ++elemIt) {
2064 // //       aFace = (*elemIt);
2065 // //       bool isOK = true;
2066 // //       itOnSubFace = aFace->nodesIterator();
2067 // //       aqt.clear();
2068 // //       for ( int j = 0; j < 4; ++j ) {
2069 // //         int aNodeID = itOnSubFace->next()->GetID();
2070 // //         itOnMap = theNodeId2NodeIndexMap.find(aNodeID);
2071 // //         if (itOnMap != theNodeId2NodeIndexMap.end())
2072 // //           aqt.push_back((*itOnMap).second);
2073 // //         else {
2074 // //           isOK = false;
2075 // //           theEnforcedQuadrangles.erase(elemIt);
2076 // //           break;
2077 // //         }
2078 // //       }
2079 // //       if (isOK)
2080 // //         qt.push_back(aqt);
2081 // //     }
2082 // //   }
2083 // //  
2084 //   
2085 // //   /* Write quadrilaterals number */
2086 // //   if (qt.size()) {
2087 // //     GmfSetKwd(idx, GmfQuadrilaterals, qt.size());
2088 // //     for (int i=0;i<qt.size();i++)
2089 // //       GmfSetLin(idx, GmfQuadrilaterals, qt[i][0], qt[i][1], qt[i][2], qt[i][3], dummyint);
2090 // //   }
2091 // 
2092 //   GmfCloseMesh(idx);
2093 //   return true;
2094 // }
2095
2096
2097 //=======================================================================
2098 //function : writeFaces
2099 //purpose  : 
2100 //=======================================================================
2101
2102 static bool writeFaces (ofstream &              theFile,
2103                         const SMESH_ProxyMesh&  theMesh,
2104                         const TopoDS_Shape&     theShape,
2105                         const map <int,int> &   theSmdsToHybridIdMap,
2106                         const map <int,int> &   theEnforcedNodeIdToHybridIdMap,
2107                         HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
2108                         HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles)
2109 {
2110   // record structure:
2111   //
2112   // NB_ELEMS DUMMY_INT
2113   // Loop from 1 to NB_ELEMS
2114   // NB_NODES NODE_NB_1 NODE_NB_2 ... (NB_NODES + 1) times: DUMMY_INT
2115
2116   TopoDS_Shape aShape;
2117   const SMESHDS_SubMesh* theSubMesh;
2118   const SMDS_MeshElement* aFace;
2119   const char* space    = "  ";
2120   const int   dummyint = 0;
2121   map<int,int>::const_iterator itOnMap;
2122   SMDS_ElemIteratorPtr itOnSubMesh, itOnSubFace;
2123   int nbNodes, aSmdsID;
2124
2125   TIDSortedElemSet::const_iterator elemIt;
2126   int nbEnforcedEdges       = theEnforcedEdges.size();
2127   int nbEnforcedTriangles   = theEnforcedTriangles.size();
2128
2129   // count triangles bound to geometry
2130   int nbTriangles = 0;
2131
2132   TopTools_IndexedMapOfShape facesMap, trianglesMap;
2133   TopExp::MapShapes( theShape, TopAbs_FACE, facesMap );
2134   
2135   int nbFaces = facesMap.Extent();
2136
2137   for ( int i = 1; i <= nbFaces; ++i )
2138     if (( theSubMesh  = theMesh.GetSubMesh( facesMap(i))))
2139       nbTriangles += theSubMesh->NbElements();
2140   std::string tmpStr;
2141   (nbFaces == 0 || nbFaces == 1) ? tmpStr = " shape " : tmpStr = " shapes " ;
2142   std::cout << "    " << nbFaces << tmpStr << "of 2D dimension";
2143   int nbEnforcedElements = nbEnforcedEdges+nbEnforcedTriangles;
2144   if (nbEnforcedElements > 0) {
2145     (nbEnforcedElements == 1) ? tmpStr = "shape:" : tmpStr = "shapes:";
2146     std::cout << " and" << std::endl;
2147     std::cout << "    " << nbEnforcedElements 
2148                         << " enforced " << tmpStr << std::endl;
2149   }
2150   else
2151     std::cout << std::endl;
2152   if (nbEnforcedEdges) {
2153     (nbEnforcedEdges == 1) ? tmpStr = "edge" : tmpStr = "edges";
2154     std::cout << "      " << nbEnforcedEdges << " enforced " << tmpStr << std::endl;
2155   }
2156   if (nbEnforcedTriangles) {
2157     (nbEnforcedTriangles == 1) ? tmpStr = "triangle" : tmpStr = "triangles";
2158     std::cout << "      " << nbEnforcedTriangles << " enforced " << tmpStr << std::endl;
2159   }
2160   std::cout << std::endl;
2161
2162 //   theFile << space << nbTriangles << space << dummyint << std::endl;
2163   std::ostringstream globalStream, localStream, aStream;
2164
2165   for ( int i = 1; i <= facesMap.Extent(); i++ )
2166   {
2167     aShape = facesMap(i);
2168     theSubMesh = theMesh.GetSubMesh(aShape);
2169     if ( !theSubMesh ) continue;
2170     itOnSubMesh = theSubMesh->GetElements();
2171     while ( itOnSubMesh->more() )
2172     {
2173       aFace = itOnSubMesh->next();
2174       nbNodes = aFace->NbCornerNodes();
2175
2176       localStream << nbNodes << space;
2177
2178       itOnSubFace = aFace->nodesIterator();
2179       for ( int j = 0; j < 3; ++j ) {
2180         // find HYBRID ID
2181         aSmdsID = itOnSubFace->next()->GetID();
2182         itOnMap = theSmdsToHybridIdMap.find( aSmdsID );
2183         // if ( itOnMap == theSmdsToHybridIdMap.end() ) {
2184         //   cout << "not found node: " << aSmdsID << endl;
2185         //   return false;
2186         // }
2187         ASSERT( itOnMap != theSmdsToHybridIdMap.end() );
2188
2189         localStream << (*itOnMap).second << space ;
2190       }
2191
2192       // (NB_NODES + 1) times: DUMMY_INT
2193       for ( int j=0; j<=nbNodes; j++)
2194         localStream << dummyint << space ;
2195
2196       localStream << std::endl;
2197     }
2198   }
2199   
2200   globalStream << localStream.str();
2201   localStream.str("");
2202
2203   //
2204   //        FACES : END
2205   //
2206
2207 //   //
2208 //   //        ENFORCED EDGES : BEGIN
2209 //   //
2210 //   
2211 //   // Iterate over the enforced edges
2212 //   int usedEnforcedEdges = 0;
2213 //   bool isOK;
2214 //   for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
2215 //     aFace = (*elemIt);
2216 //     isOK = true;
2217 //     itOnSubFace = aFace->nodesIterator();
2218 //     aStream.str("");
2219 //     aStream << "2" << space ;
2220 //     for ( int j = 0; j < 2; ++j ) {
2221 //       aSmdsID = itOnSubFace->next()->GetID();
2222 //       itOnMap = theEnforcedNodeIdToHybridIdMap.find(aSmdsID);
2223 //       if (itOnMap != theEnforcedNodeIdToHybridIdMap.end())
2224 //         aStream << (*itOnMap).second << space;
2225 //       else {
2226 //         isOK = false;
2227 //         break;
2228 //       }
2229 //     }
2230 //     if (isOK) {
2231 //       for ( int j=0; j<=2; j++)
2232 //         aStream << dummyint << space ;
2233 // //       aStream << dummyint << space << dummyint;
2234 //       localStream << aStream.str() << std::endl;
2235 //       usedEnforcedEdges++;
2236 //     }
2237 //   }
2238 //   
2239 //   if (usedEnforcedEdges) {
2240 //     globalStream << localStream.str();
2241 //     localStream.str("");
2242 //   }
2243 // 
2244 //   //
2245 //   //        ENFORCED EDGES : END
2246 //   //
2247 //   //
2248 // 
2249 //   //
2250 //   //        ENFORCED TRIANGLES : BEGIN
2251 //   //
2252 //     // Iterate over the enforced triangles
2253 //   int usedEnforcedTriangles = 0;
2254 //   for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
2255 //     aFace = (*elemIt);
2256 //     nbNodes = aFace->NbCornerNodes();
2257 //     isOK = true;
2258 //     itOnSubFace = aFace->nodesIterator();
2259 //     aStream.str("");
2260 //     aStream << nbNodes << space ;
2261 //     for ( int j = 0; j < 3; ++j ) {
2262 //       aSmdsID = itOnSubFace->next()->GetID();
2263 //       itOnMap = theEnforcedNodeIdToHybridIdMap.find(aSmdsID);
2264 //       if (itOnMap != theEnforcedNodeIdToHybridIdMap.end())
2265 //         aStream << (*itOnMap).second << space;
2266 //       else {
2267 //         isOK = false;
2268 //         break;
2269 //       }
2270 //     }
2271 //     if (isOK) {
2272 //       for ( int j=0; j<=3; j++)
2273 //         aStream << dummyint << space ;
2274 //       localStream << aStream.str() << std::endl;
2275 //       usedEnforcedTriangles++;
2276 //     }
2277 //   }
2278 //   
2279 //   if (usedEnforcedTriangles) {
2280 //     globalStream << localStream.str();
2281 //     localStream.str("");
2282 //   }
2283 // 
2284 //   //
2285 //   //        ENFORCED TRIANGLES : END
2286 //   //
2287   
2288   theFile
2289   << nbTriangles/*+usedEnforcedTriangles+usedEnforcedEdges*/
2290   << " 0" << std::endl
2291   << globalStream.str();
2292
2293   return true;
2294 }
2295
2296 //=======================================================================
2297 //function : writePoints
2298 //purpose  : 
2299 //=======================================================================
2300
2301 static bool writePoints (ofstream &                       theFile,
2302                          SMESH_MesherHelper&              theHelper,
2303                          map <int,int> &                  theSmdsToHybridIdMap,
2304                          map <int,int> &                  theEnforcedNodeIdToHybridIdMap,
2305                          map <int,const SMDS_MeshNode*> & theHybridIdToNodeMap,
2306                          HYBRIDPlugin_Hypothesis::TID2SizeMap & theNodeIDToSizeMap,
2307                          HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues & theEnforcedVertices,
2308                          HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
2309                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
2310                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles)
2311 {
2312   // record structure:
2313   //
2314   // NB_NODES
2315   // Loop from 1 to NB_NODES
2316   //   X Y Z DUMMY_INT
2317
2318   SMESHDS_Mesh * theMeshDS = theHelper.GetMeshDS();
2319   int nbNodes = theMeshDS->NbNodes();
2320   if ( nbNodes == 0 )
2321     return false;
2322   
2323   int nbEnforcedVertices = theEnforcedVertices.size();
2324   int nbEnforcedNodes    = theEnforcedNodes.size();
2325   
2326   const TopoDS_Shape shapeToMesh = theMeshDS->ShapeToMesh();
2327   
2328   int aHybridID = 1;
2329   SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
2330   const SMDS_MeshNode* node;
2331
2332   // Issue 020674: EDF 870 SMESH: Mesh generated by Netgen not usable by HYBRID
2333   // The problem is in nodes on degenerated edges, we need to skip nodes which are free
2334   // and replace not-free nodes on degenerated edges by the node on vertex
2335   TNodeNodeMap n2nDegen; // map a node on degenerated edge to a node on vertex
2336   TNodeNodeMap::iterator n2nDegenIt;
2337   if ( theHelper.HasDegeneratedEdges() )
2338   {
2339     set<int> checkedSM;
2340     for (TopExp_Explorer e(theMeshDS->ShapeToMesh(), TopAbs_EDGE ); e.More(); e.Next())
2341     {
2342       SMESH_subMesh* sm = theHelper.GetMesh()->GetSubMesh( e.Current() );
2343       if ( checkedSM.insert( sm->GetId() ).second && theHelper.IsDegenShape(sm->GetId() ))
2344       {
2345         if ( SMESHDS_SubMesh* smDS = sm->GetSubMeshDS() )
2346         {
2347           TopoDS_Shape vertex = TopoDS_Iterator( e.Current() ).Value();
2348           const SMDS_MeshNode* vNode = SMESH_Algo::VertexNode( TopoDS::Vertex( vertex ), theMeshDS);
2349           {
2350             SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2351             while ( nIt->more() )
2352               n2nDegen.insert( make_pair( nIt->next(), vNode ));
2353           }
2354         }
2355       }
2356     }
2357     nbNodes -= n2nDegen.size();
2358   }
2359
2360   const bool isQuadMesh = 
2361     theHelper.GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
2362     theHelper.GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
2363     theHelper.GetMesh()->NbVolumes( ORDER_QUADRATIC );
2364   if ( isQuadMesh )
2365   {
2366     // descrease nbNodes by nb of medium nodes
2367     while ( nodeIt->more() )
2368     {
2369       node = nodeIt->next();
2370       if ( !theHelper.IsDegenShape( node->getshapeId() ))
2371         nbNodes -= int( theHelper.IsMedium( node ));
2372     }
2373     nodeIt = theMeshDS->nodesIterator();
2374   }
2375
2376   const char* space    = "  ";
2377   const int   dummyint = 0;
2378
2379   std::string tmpStr;
2380   (nbNodes == 0 || nbNodes == 1) ? tmpStr = " node" : tmpStr = " nodes";
2381   // NB_NODES
2382   std::cout << std::endl;
2383   std::cout << "The initial 2D mesh contains :" << std::endl;
2384   std::cout << "    " << nbNodes << tmpStr << std::endl;
2385   if (nbEnforcedVertices > 0) {
2386     (nbEnforcedVertices == 1) ? tmpStr = "vertex" : tmpStr = "vertices";
2387     std::cout << "    " << nbEnforcedVertices << " enforced " << tmpStr << std::endl;
2388   }
2389   if (nbEnforcedNodes > 0) {
2390     (nbEnforcedNodes == 1) ? tmpStr = "node" : tmpStr = "nodes";
2391     std::cout << "    " << nbEnforcedNodes << " enforced " << tmpStr << std::endl;
2392   }
2393   std::cout << std::endl;
2394   std::cout << "Start writing in 'points' file ..." << std::endl;
2395
2396   theFile << nbNodes << std::endl;
2397
2398   // Loop from 1 to NB_NODES
2399
2400   while ( nodeIt->more() )
2401   {
2402     node = nodeIt->next();
2403     if ( isQuadMesh && theHelper.IsMedium( node )) // Issue 0021238
2404       continue;
2405     if ( n2nDegen.count( node ) ) // Issue 0020674
2406       continue;
2407
2408     theSmdsToHybridIdMap.insert( make_pair( node->GetID(), aHybridID ));
2409     theHybridIdToNodeMap.insert( make_pair( aHybridID, node ));
2410     aHybridID++;
2411
2412     // X Y Z DUMMY_INT
2413     theFile
2414     << node->X() << space 
2415     << node->Y() << space 
2416     << node->Z() << space 
2417     << dummyint;
2418
2419     theFile << std::endl;
2420
2421   }
2422   
2423   // Iterate over the enforced nodes
2424   std::map<int,double> enfVertexIndexSizeMap;
2425   if (nbEnforcedNodes) {
2426     HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator nodeIt = theEnforcedNodes.begin();
2427     for( ; nodeIt != theEnforcedNodes.end() ; ++nodeIt) {
2428       double x = nodeIt->first->X();
2429       double y = nodeIt->first->Y();
2430       double z = nodeIt->first->Z();
2431       // Test if point is inside shape to mesh
2432       gp_Pnt myPoint(x,y,z);
2433       BRepClass3d_SolidClassifier scl(shapeToMesh);
2434       scl.Perform(myPoint, 1e-7);
2435       TopAbs_State result = scl.State();
2436       if ( result != TopAbs_IN )
2437         continue;
2438       std::vector<double> coords;
2439       coords.push_back(x);
2440       coords.push_back(y);
2441       coords.push_back(z);
2442       if (theEnforcedVertices.find(coords) != theEnforcedVertices.end())
2443         continue;
2444         
2445 //      double size = theNodeIDToSizeMap.find(nodeIt->first->GetID())->second;
2446   //       theHybridIdToNodeMap.insert( make_pair( nbNodes + i, (*nodeIt) ));
2447   //       MESSAGE("Adding enforced node (" << x << "," << y <<"," << z << ")");
2448       // X Y Z PHY_SIZE DUMMY_INT
2449       theFile
2450       << x << space 
2451       << y << space 
2452       << z << space
2453       << -1 << space
2454       << dummyint << space;
2455       theFile << std::endl;
2456       theEnforcedNodeIdToHybridIdMap.insert( make_pair( nodeIt->first->GetID(), aHybridID ));
2457       enfVertexIndexSizeMap[aHybridID] = -1;
2458       aHybridID++;
2459   //     else
2460   //         MESSAGE("Enforced vertex (" << x << "," << y <<"," << z << ") is not inside the geometry: it was not added ");
2461     }
2462   }
2463   
2464   if (nbEnforcedVertices) {
2465     // Iterate over the enforced vertices
2466     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues::const_iterator vertexIt = theEnforcedVertices.begin();
2467     for( ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
2468       double x = vertexIt->first[0];
2469       double y = vertexIt->first[1];
2470       double z = vertexIt->first[2];
2471       // Test if point is inside shape to mesh
2472       gp_Pnt myPoint(x,y,z);
2473       BRepClass3d_SolidClassifier scl(shapeToMesh);
2474       scl.Perform(myPoint, 1e-7);
2475       TopAbs_State result = scl.State();
2476       if ( result != TopAbs_IN )
2477         continue;
2478       MESSAGE("Adding enforced vertex (" << x << "," << y <<"," << z << ") = " << vertexIt->second);
2479       // X Y Z PHY_SIZE DUMMY_INT
2480       theFile
2481       << x << space 
2482       << y << space 
2483       << z << space
2484       << vertexIt->second << space 
2485       << dummyint << space;
2486       theFile << std::endl;
2487       enfVertexIndexSizeMap[aHybridID] = vertexIt->second;
2488       aHybridID++;
2489     }
2490   }
2491   
2492   
2493   std::cout << std::endl;
2494   std::cout << "End writing in 'points' file." << std::endl;
2495
2496   return true;
2497 }
2498
2499 //=======================================================================
2500 //function : readResultFile
2501 //purpose  : readResultFile with geometry
2502 //=======================================================================
2503
2504 static bool readResultFile(const int                       fileOpen,
2505 #ifdef WIN32
2506                            const char*                     fileName,
2507 #endif
2508                            HYBRIDPlugin_HYBRID*            theAlgo,
2509                            SMESH_MesherHelper&             theHelper,
2510                            TopoDS_Shape                    tabShape[],
2511                            double**                        tabBox,
2512                            const int                       nbShape,
2513                            map <int,const SMDS_MeshNode*>& theHybridIdToNodeMap,
2514                            std::map <int,int> &            theNodeId2NodeIndexMap,
2515                            bool                            toMeshHoles,
2516                            int                             nbEnforcedVertices,
2517                            int                             nbEnforcedNodes,
2518                            HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
2519                            HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles,
2520                            bool                            toMakeGroupsOfDomains)
2521 {
2522   MESSAGE("HYBRIDPlugin_HYBRID::readResultFile()");
2523   Kernel_Utils::Localizer loc;
2524   struct stat status;
2525   size_t      length;
2526   
2527   std::string tmpStr;
2528
2529   char *ptr, *mapPtr;
2530   char *tetraPtr;
2531   char *shapePtr;
2532
2533   SMESHDS_Mesh* theMeshDS = theHelper.GetMeshDS();
2534
2535   int nbElems, nbNodes, nbInputNodes;
2536   int nbTriangle;
2537   int ID, shapeID, hybridShapeID;
2538   int IdShapeRef = 1;
2539   int compoundID =
2540     nbShape ? theMeshDS->ShapeToIndex( tabShape[0] ) : theMeshDS->ShapeToIndex( theMeshDS->ShapeToMesh() );
2541
2542   int *tab, *tabID, *nodeID, *nodeAssigne;
2543   double *coord;
2544   const SMDS_MeshNode **node;
2545
2546   tab    = new int[3];
2547   nodeID = new int[4];
2548   coord  = new double[3];
2549   node   = new const SMDS_MeshNode*[4];
2550
2551   TopoDS_Shape aSolid;
2552   SMDS_MeshNode * aNewNode;
2553   map <int,const SMDS_MeshNode*>::iterator itOnNode;
2554   SMDS_MeshElement* aTet;
2555 #ifdef _DEBUG_
2556   set<int> shapeIDs;
2557 #endif
2558
2559   // Read the file state
2560   fstat(fileOpen, &status);
2561   length   = status.st_size;
2562
2563   // Mapping the result file into memory
2564 #ifdef WIN32
2565   HANDLE fd = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ,
2566                          NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2567   HANDLE hMapObject = CreateFileMapping(fd, NULL, PAGE_READONLY,
2568                                         0, (DWORD)length, NULL);
2569   ptr = ( char* ) MapViewOfFile(hMapObject, FILE_MAP_READ, 0, 0, 0 );
2570 #else
2571   ptr = (char *) mmap(0,length,PROT_READ,MAP_PRIVATE,fileOpen,0);
2572 #endif
2573   mapPtr = ptr;
2574
2575   ptr      = readMapIntLine(ptr, tab);
2576   tetraPtr = ptr;
2577
2578   nbElems      = tab[0];
2579   nbNodes      = tab[1];
2580   nbInputNodes = tab[2];
2581
2582   nodeAssigne = new int[ nbNodes+1 ];
2583
2584   if (nbShape > 0)
2585     aSolid = tabShape[0];
2586
2587   // Reading the nodeId
2588   for (int i=0; i < 4*nbElems; i++)
2589     strtol(ptr, &ptr, 10);
2590
2591   MESSAGE("nbInputNodes: "<<nbInputNodes);
2592   MESSAGE("nbEnforcedVertices: "<<nbEnforcedVertices);
2593   MESSAGE("nbEnforcedNodes: "<<nbEnforcedNodes);
2594   // Reading the nodeCoor and update the nodeMap
2595   for (int iNode=1; iNode <= nbNodes; iNode++) {
2596     if(theAlgo->computeCanceled())
2597       return false;
2598     for (int iCoor=0; iCoor < 3; iCoor++)
2599       coord[ iCoor ] = strtod(ptr, &ptr);
2600     nodeAssigne[ iNode ] = 1;
2601     if ( iNode > (nbInputNodes-(nbEnforcedVertices+nbEnforcedNodes)) ) {
2602       // Creating SMESH nodes
2603       // - for enforced vertices
2604       // - for vertices of forced edges
2605       // - for hybrid nodes
2606       nodeAssigne[ iNode ] = 0;
2607       aNewNode = theMeshDS->AddNode( coord[0],coord[1],coord[2] );
2608       theHybridIdToNodeMap.insert(theHybridIdToNodeMap.end(), make_pair( iNode, aNewNode ));
2609     }
2610   }
2611
2612   // Reading the number of triangles which corresponds to the number of sub-domains
2613   nbTriangle = strtol(ptr, &ptr, 10);
2614
2615   tabID = new int[nbTriangle];
2616   for (int i=0; i < nbTriangle; i++) {
2617     if(theAlgo->computeCanceled())
2618       return false;
2619     tabID[i] = 0;
2620     // find the solid corresponding to HYBRID sub-domain following
2621     // the technique proposed in HYBRID manual in chapter
2622     // "B.4 Subdomain (sub-region) assignment"
2623     int nodeId1 = strtol(ptr, &ptr, 10);
2624     int nodeId2 = strtol(ptr, &ptr, 10);
2625     int nodeId3 = strtol(ptr, &ptr, 10);
2626     if ( nbTriangle > 1 ) {
2627       const SMDS_MeshNode* n1 = theHybridIdToNodeMap[ nodeId1 ];
2628       const SMDS_MeshNode* n2 = theHybridIdToNodeMap[ nodeId2 ];
2629       const SMDS_MeshNode* n3 = theHybridIdToNodeMap[ nodeId3 ];
2630       if (!n1 || !n2 || !n3) {
2631         tabID[i] = HOLE_ID;
2632         continue;
2633       }
2634       try {
2635         OCC_CATCH_SIGNALS;
2636 //         tabID[i] = findShapeID( theHelper, n1, n2, n3, toMeshHoles );
2637         tabID[i] = findShapeID( *theHelper.GetMesh(), n1, n2, n3, toMeshHoles );
2638         // -- 0020330: Pb with hybrid as a submesh
2639         // check that found shape is to be meshed
2640         if ( tabID[i] > 0 ) {
2641           const TopoDS_Shape& foundShape = theMeshDS->IndexToShape( tabID[i] );
2642           bool isToBeMeshed = false;
2643           for ( int iS = 0; !isToBeMeshed && iS < nbShape; ++iS )
2644             isToBeMeshed = foundShape.IsSame( tabShape[ iS ]);
2645           if ( !isToBeMeshed )
2646             tabID[i] = HOLE_ID;
2647         }
2648         // END -- 0020330: Pb with hybrid as a submesh
2649 #ifdef _DEBUG_
2650         std::cout << i+1 << " subdomain: findShapeID() returns " << tabID[i] << std::endl;
2651 #endif
2652       }
2653       catch ( Standard_Failure & ex)
2654       {
2655 #ifdef _DEBUG_
2656         std::cout << i+1 << " subdomain: Exception caugt: " << ex.GetMessageString() << std::endl;
2657 #endif
2658       }
2659       catch (...) {
2660 #ifdef _DEBUG_
2661         std::cout << i+1 << " subdomain: unknown exception caught " << std::endl;
2662 #endif
2663       }
2664     }
2665   }
2666
2667   shapePtr = ptr;
2668
2669   if ( nbTriangle <= nbShape ) // no holes
2670     toMeshHoles = true; // not avoid creating tetras in holes
2671
2672   // IMP 0022172: [CEA 790] create the groups corresponding to domains
2673   std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain( Max( nbTriangle, nbShape ));
2674
2675   // Associating the tetrahedrons to the shapes
2676   shapeID = compoundID;
2677   for (int iElem = 0; iElem < nbElems; iElem++) {
2678     if(theAlgo->computeCanceled())
2679       return false;
2680     for (int iNode = 0; iNode < 4; iNode++) {
2681       ID = strtol(tetraPtr, &tetraPtr, 10);
2682       itOnNode = theHybridIdToNodeMap.find(ID);
2683       node[ iNode ] = itOnNode->second;
2684       nodeID[ iNode ] = ID;
2685     }
2686     // We always run HYBRID with "to mesh holes"==TRUE but we must not create
2687     // tetras within holes depending on hypo option,
2688     // so we first check if aTet is inside a hole and then create it 
2689     //aTet = theMeshDS->AddVolume( node[1], node[0], node[2], node[3] );
2690     hybridShapeID = 0; // domain ID
2691     if ( nbTriangle > 1 ) {
2692       shapeID = HOLE_ID; // negative shapeID means not to create tetras if !toMeshHoles
2693       hybridShapeID = strtol(shapePtr, &shapePtr, 10) - IdShapeRef;
2694       if ( tabID[ hybridShapeID ] == 0 ) {
2695         TopAbs_State state;
2696         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape, &state);
2697         if ( toMeshHoles || state == TopAbs_IN )
2698           shapeID = theMeshDS->ShapeToIndex( aSolid );
2699         tabID[ hybridShapeID ] = shapeID;
2700       }
2701       else
2702         shapeID = tabID[ hybridShapeID ];
2703     }
2704     else if ( nbShape > 1 ) {
2705       // Case where nbTriangle == 1 while nbShape == 2 encountered
2706       // with compound of 2 boxes and "To mesh holes"==False,
2707       // so there are no subdomains specified for each tetrahedron.
2708       // Try to guess a solid by a node already bound to shape
2709       shapeID = 0;
2710       for ( int i=0; i<4 && shapeID==0; i++ ) {
2711         if ( nodeAssigne[ nodeID[i] ] == 1 &&
2712              node[i]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE &&
2713              node[i]->getshapeId() > 1 )
2714         {
2715           shapeID = node[i]->getshapeId();
2716         }
2717       }
2718       if ( shapeID==0 ) {
2719         aSolid = findShape(node, aSolid, tabShape, tabBox, nbShape);
2720         shapeID = theMeshDS->ShapeToIndex( aSolid );
2721       }
2722     }
2723     // set new nodes and tetrahedron onto the shape
2724     for ( int i=0; i<4; i++ ) {
2725       if ( nodeAssigne[ nodeID[i] ] == 0 ) {
2726         if ( shapeID != HOLE_ID )
2727           theMeshDS->SetNodeInVolume( node[i], shapeID );
2728         nodeAssigne[ nodeID[i] ] = shapeID;
2729       }
2730     }
2731     if ( toMeshHoles || shapeID != HOLE_ID ) {
2732       aTet = theHelper.AddVolume( node[1], node[0], node[2], node[3],
2733                                   /*id=*/0, /*force3d=*/false);
2734       theMeshDS->SetMeshElementOnShape( aTet, shapeID );
2735       if ( toMakeGroupsOfDomains )
2736       {
2737         if ( int( elemsOfDomain.size() ) < hybridShapeID+1 )
2738           elemsOfDomain.resize( hybridShapeID+1 );
2739         elemsOfDomain[ hybridShapeID ].push_back( aTet );
2740       }
2741     }
2742 #ifdef _DEBUG_
2743     shapeIDs.insert( shapeID );
2744 #endif
2745   }
2746   if ( toMakeGroupsOfDomains )
2747     makeDomainGroups( elemsOfDomain, &theHelper );
2748   
2749   // Add enforced elements
2750   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap::const_iterator elemIt;
2751   const SMDS_MeshElement* anElem;
2752   SMDS_ElemIteratorPtr itOnEnfElem;
2753   map<int,int>::const_iterator itOnMap;
2754   shapeID = compoundID;
2755   // Enforced edges
2756   if (theEnforcedEdges.size()) {
2757     (theEnforcedEdges.size() <= 1) ? tmpStr = " enforced edge" : " enforced edges";
2758     std::cout << "Add " << theEnforcedEdges.size() << tmpStr << std::endl;
2759     std::vector< const SMDS_MeshNode* > node( 2 );
2760     // Iterate over the enforced edges
2761     for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
2762       anElem = elemIt->first;
2763       bool addElem = true;
2764       itOnEnfElem = anElem->nodesIterator();
2765       for ( int j = 0; j < 2; ++j ) {
2766         int aNodeID = itOnEnfElem->next()->GetID();
2767         itOnMap = theNodeId2NodeIndexMap.find(aNodeID);
2768         if (itOnMap != theNodeId2NodeIndexMap.end()) {
2769           itOnNode = theHybridIdToNodeMap.find((*itOnMap).second);
2770           if (itOnNode != theHybridIdToNodeMap.end()) {
2771             node.push_back((*itOnNode).second);
2772 //             shapeID =(*itOnNode).second->getshapeId();
2773           }
2774           else
2775             addElem = false;
2776         }
2777         else
2778           addElem = false;
2779       }
2780       if (addElem) {
2781         aTet = theHelper.AddEdge( node[0], node[1], 0,  false);
2782         theMeshDS->SetMeshElementOnShape( aTet, shapeID );
2783       }
2784     }
2785   }
2786   // Enforced faces
2787   if (theEnforcedTriangles.size()) {
2788     (theEnforcedTriangles.size() <= 1) ? tmpStr = " enforced triangle" : " enforced triangles";
2789     std::cout << "Add " << theEnforcedTriangles.size() << " enforced triangles" << std::endl;
2790     std::vector< const SMDS_MeshNode* > node( 3 );
2791     // Iterate over the enforced triangles
2792     for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
2793       anElem = elemIt->first;
2794       bool addElem = true;
2795       itOnEnfElem = anElem->nodesIterator();
2796       for ( int j = 0; j < 3; ++j ) {
2797         int aNodeID = itOnEnfElem->next()->GetID();
2798         itOnMap = theNodeId2NodeIndexMap.find(aNodeID);
2799         if (itOnMap != theNodeId2NodeIndexMap.end()) {
2800           itOnNode = theHybridIdToNodeMap.find((*itOnMap).second);
2801           if (itOnNode != theHybridIdToNodeMap.end()) {
2802             node.push_back((*itOnNode).second);
2803 //             shapeID =(*itOnNode).second->getshapeId();
2804           }
2805           else
2806             addElem = false;
2807         }
2808         else
2809           addElem = false;
2810       }
2811       if (addElem) {
2812         aTet = theHelper.AddFace( node[0], node[1], node[2], 0,  false);
2813         theMeshDS->SetMeshElementOnShape( aTet, shapeID );
2814       }
2815     }
2816   }
2817
2818   // Remove nodes of tetras inside holes if !toMeshHoles
2819   if ( !toMeshHoles ) {
2820     itOnNode = theHybridIdToNodeMap.find( nbInputNodes );
2821     for ( ; itOnNode != theHybridIdToNodeMap.end(); ++itOnNode) {
2822       ID = itOnNode->first;
2823       if ( nodeAssigne[ ID ] == HOLE_ID )
2824         theMeshDS->RemoveFreeNode( itOnNode->second, 0 );
2825     }
2826   }
2827
2828   
2829   if ( nbElems ) {
2830     (nbElems <= 1) ? tmpStr = " tetrahedra" : " tetrahedrons";
2831     cout << nbElems << tmpStr << " have been associated to " << nbShape;
2832     (nbShape <= 1) ? tmpStr = " shape" : " shapes";
2833     cout << tmpStr << endl;
2834   }
2835 #ifdef WIN32
2836   UnmapViewOfFile(mapPtr);
2837   CloseHandle(hMapObject);
2838   CloseHandle(fd);
2839 #else
2840   munmap(mapPtr, length);
2841 #endif
2842   close(fileOpen);
2843
2844   delete [] tab;
2845   delete [] tabID;
2846   delete [] nodeID;
2847   delete [] coord;
2848   delete [] node;
2849   delete [] nodeAssigne;
2850
2851 #ifdef _DEBUG_
2852   shapeIDs.erase(-1);
2853   if ( shapeIDs.size() != nbShape ) {
2854     (shapeIDs.size() <= 1) ? tmpStr = " solid" : " solids";
2855     std::cout << "Only " << shapeIDs.size() << tmpStr << " of " << nbShape << " found" << std::endl;
2856     for (int i=0; i<nbShape; i++) {
2857       shapeID = theMeshDS->ShapeToIndex( tabShape[i] );
2858       if ( shapeIDs.find( shapeID ) == shapeIDs.end() )
2859         std::cout << "  Solid #" << shapeID << " not found" << std::endl;
2860     }
2861   }
2862 #endif
2863
2864   return true;
2865 }
2866
2867
2868 //=============================================================================
2869 /*!
2870  *Here we are going to use the HYBRID mesher with geometry
2871  */
2872 //=============================================================================
2873
2874 bool HYBRIDPlugin_HYBRID::Compute(SMESH_Mesh&         theMesh,
2875                                   const TopoDS_Shape& theShape)
2876 {
2877   bool Ok(false);
2878   //SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
2879
2880   // we count the number of shapes
2881   // _nbShape = countShape( meshDS, TopAbs_SOLID ); -- 0020330: Pb with hybrid as a submesh
2882   // _nbShape = 0;
2883   TopExp_Explorer expBox ( theShape, TopAbs_SOLID );
2884   // for ( ; expBox.More(); expBox.Next() )
2885   //   _nbShape++;
2886
2887   // create bounding box for every shape inside the compound
2888
2889   // int iShape = 0;
2890   // TopoDS_Shape* tabShape;
2891   // double**      tabBox;
2892   // tabShape = new TopoDS_Shape[_nbShape];
2893   // tabBox   = new double*[_nbShape];
2894   // for (int i=0; i<_nbShape; i++)
2895   //   tabBox[i] = new double[6];
2896   // Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
2897
2898   // for (expBox.ReInit(); expBox.More(); expBox.Next()) {
2899   //   tabShape[iShape] = expBox.Current();
2900   //   Bnd_Box BoundingBox;
2901   //   BRepBndLib::Add(expBox.Current(), BoundingBox);
2902   //   BoundingBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
2903   //   tabBox[iShape][0] = Xmin; tabBox[iShape][1] = Xmax;
2904   //   tabBox[iShape][2] = Ymin; tabBox[iShape][3] = Ymax;
2905   //   tabBox[iShape][4] = Zmin; tabBox[iShape][5] = Zmax;
2906   //   iShape++;
2907   // }
2908
2909   // a unique working file name
2910   // to avoid access to the same files by eg different users
2911   _genericName = HYBRIDPlugin_Hypothesis::GetFileName(_hyp);
2912   TCollection_AsciiString aGenericName((char*) _genericName.c_str() );
2913   TCollection_AsciiString aGenericNameRequired = aGenericName + "_required";
2914
2915   TCollection_AsciiString aLogFileName    = aGenericName + ".log";    // log
2916   TCollection_AsciiString aResultFileName;
2917
2918   TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
2919 //#ifdef _DEBUG_
2920   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
2921   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
2922   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
2923   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
2924   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
2925 //#else
2926 //  aGMFFileName    = aGenericName + ".meshb"; // GMF mesh file
2927 //  aResultFileName = aGenericName + "Vol.meshb"; // GMF mesh file
2928 //  aRequiredVerticesFileName    = aGenericNameRequired + ".meshb"; // GMF required vertices mesh file
2929 //  aSolFileName    = aGenericNameRequired + ".solb"; // GMF solution file
2930 //#endif
2931   
2932   std::map <int,int> aNodeId2NodeIndexMap, aSmdsToHybridIdMap, anEnforcedNodeIdToHybridIdMap;
2933   //std::map <int,const SMDS_MeshNode*> aHybridIdToNodeMap;
2934   std::map <int, int> nodeID2nodeIndexMap;
2935   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
2936   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues coordsSizeMap = HYBRIDPlugin_Hypothesis::GetEnforcedVerticesCoordsSize(_hyp);
2937   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = HYBRIDPlugin_Hypothesis::GetEnforcedNodes(_hyp);
2938   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = HYBRIDPlugin_Hypothesis::GetEnforcedEdges(_hyp);
2939   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = HYBRIDPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
2940 //   TIDSortedElemSet enforcedQuadrangles = HYBRIDPlugin_Hypothesis::GetEnforcedQuadrangles(_hyp);
2941   HYBRIDPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = HYBRIDPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
2942
2943   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList enfVertices = HYBRIDPlugin_Hypothesis::GetEnforcedVertices(_hyp);
2944   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
2945   std::vector<double> coords;
2946
2947   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
2948   {
2949     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertex* enfVertex = (*enfVerIt);
2950 //     if (enfVertex->geomEntry.empty() && enfVertex->coords.size()) {
2951     if (enfVertex->coords.size()) {
2952       coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
2953       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
2954 //       MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<enfVertex->coords[0]<<","<<enfVertex->coords[1]<<","<<enfVertex->coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
2955     }
2956     else {
2957 //     if (!enfVertex->geomEntry.empty()) {
2958       TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
2959 //       GeomType = GeomShape.ShapeType();
2960
2961 //       if (!enfVertex->isCompound) {
2962 // //       if (GeomType == TopAbs_VERTEX) {
2963 //         coords.clear();
2964 //         aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
2965 //         coords.push_back(aPnt.X());
2966 //         coords.push_back(aPnt.Y());
2967 //         coords.push_back(aPnt.Z());
2968 //         if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
2969 //           coordsSizeMap.insert(make_pair(coords,enfVertex->size));
2970 //           enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
2971 //         }
2972 //       }
2973 //
2974 //       // Group Management
2975 //       else {
2976 //       if (GeomType == TopAbs_COMPOUND){
2977         for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
2978           coords.clear();
2979           if (it.Value().ShapeType() == TopAbs_VERTEX){
2980             gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
2981             coords.push_back(aPnt.X());
2982             coords.push_back(aPnt.Y());
2983             coords.push_back(aPnt.Z());
2984             if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
2985               coordsSizeMap.insert(make_pair(coords,enfVertex->size));
2986               enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
2987 //               MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<coords[0]<<","<<coords[1]<<","<<coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
2988             }
2989           }
2990         }
2991 //       }
2992     }
2993   }
2994   int nbEnforcedVertices = coordsSizeMap.size();
2995   int nbEnforcedNodes = enforcedNodes.size();
2996   
2997   std::string tmpStr;
2998   (nbEnforcedNodes <= 1) ? tmpStr = "node" : "nodes";
2999   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
3000   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : "vertices";
3001   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
3002   
3003   SMESH_MesherHelper helper( theMesh );
3004   helper.SetSubShape( theShape );
3005
3006   std::vector <const SMDS_MeshNode*> aNodeByHybridId, anEnforcedNodeByHybridId;
3007   std::vector <const SMDS_MeshElement*> aFaceByHybridId;
3008   std::map<const SMDS_MeshNode*,int> aNodeToHybridIdMap;
3009   std::vector<std::string> aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId;
3010   {
3011     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
3012
3013     // make prisms on quadrangles
3014     if ( theMesh.NbQuadrangles() > 0 )
3015     {
3016       vector<SMESH_ProxyMesh::Ptr> components;
3017       for (expBox.ReInit(); expBox.More(); expBox.Next())
3018       {
3019         if ( _viscousLayersHyp )
3020         {
3021           proxyMesh = _viscousLayersHyp->Compute( theMesh, expBox.Current() );
3022           if ( !proxyMesh )
3023             return false;
3024         }
3025         StdMeshers_QuadToTriaAdaptor* q2t = new StdMeshers_QuadToTriaAdaptor;
3026         q2t->Compute( theMesh, expBox.Current(), proxyMesh.get() );
3027         components.push_back( SMESH_ProxyMesh::Ptr( q2t ));
3028       }
3029       proxyMesh.reset( new SMESH_ProxyMesh( components ));
3030     }
3031     // build viscous layers
3032     else if ( _viscousLayersHyp )
3033     {
3034       proxyMesh = _viscousLayersHyp->Compute( theMesh, theShape );
3035       if ( !proxyMesh )
3036         return false;
3037     }
3038
3039     // Ok = (writePoints( aPointsFile, helper, 
3040     //                    aSmdsToHybridIdMap, anEnforcedNodeIdToHybridIdMap, aHybridIdToNodeMap, 
3041     //                    nodeIDToSizeMap,
3042     //                    coordsSizeMap, enforcedNodes, enforcedEdges, enforcedTriangles)
3043     //       &&
3044     //       writeFaces ( aFacesFile, *proxyMesh, theShape, 
3045     //                    aSmdsToHybridIdMap, anEnforcedNodeIdToHybridIdMap,
3046     //                    enforcedEdges, enforcedTriangles ));
3047     Ok = writeGMFFile(aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
3048                       *proxyMesh, helper,
3049                       aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
3050                       aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
3051                       enforcedNodes, enforcedEdges, enforcedTriangles, /*enforcedQuadrangles,*/
3052                       enfVerticesWithGroup, coordsSizeMap);
3053   }
3054
3055   // Write aSmdsToHybridIdMap to temp file
3056   TCollection_AsciiString aSmdsToHybridIdMapFileName;
3057   aSmdsToHybridIdMapFileName = aGenericName + ".ids";  // ids relation
3058   ofstream aIdsFile  ( aSmdsToHybridIdMapFileName.ToCString()  , ios::out);
3059   Ok = aIdsFile.rdbuf()->is_open();
3060   if (!Ok) {
3061     INFOS( "Can't write into " << aSmdsToHybridIdMapFileName);
3062     return error(SMESH_Comment("Can't write into ") << aSmdsToHybridIdMapFileName);
3063   }
3064   INFOS( "Writing ids relation into " << aSmdsToHybridIdMapFileName);
3065   aIdsFile << "Smds Hybrid" << std::endl;
3066   map <int,int>::const_iterator myit;
3067   for (myit=aSmdsToHybridIdMap.begin() ; myit != aSmdsToHybridIdMap.end() ; ++myit) {
3068     aIdsFile << myit->first << " " << myit->second << std::endl;
3069   }
3070
3071   aIdsFile.close();
3072   
3073   if ( ! Ok ) {
3074     if ( !_keepFiles ) {
3075       removeFile( aGMFFileName );
3076       removeFile( aRequiredVerticesFileName );
3077       removeFile( aSolFileName );
3078       removeFile( aSmdsToHybridIdMapFileName );
3079     }
3080     return error(COMPERR_BAD_INPUT_MESH);
3081   }
3082   removeFile( aResultFileName ); // needed for boundary recovery module usage
3083
3084   // -----------------
3085   // run hybrid mesher
3086   // -----------------
3087
3088   TCollection_AsciiString cmd( (char*)HYBRIDPlugin_Hypothesis::CommandToRun( _hyp ).c_str() );
3089   
3090   cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
3091   //if ( nbEnforcedVertices + nbEnforcedNodes)
3092   //  cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
3093   cmd += TCollection_AsciiString(" --out ") + aResultFileName;
3094   if ( !_logInStandardOutput )
3095     cmd += TCollection_AsciiString(" &>" ) + aLogFileName;  // dump into file
3096
3097   std::cout << std::endl;
3098   std::cout << "Hybrid execution with geometry..." << std::endl;
3099   std::cout << cmd << std::endl;
3100
3101   _compute_canceled = false;
3102
3103   system( cmd.ToCString() ); // run
3104
3105   std::cout << std::endl;
3106   std::cout << "End of Hybrid execution !" << std::endl;
3107
3108   // --------------
3109   // read a result
3110   // --------------
3111
3112   // Mapping the result file
3113
3114   // int fileOpen;
3115   // fileOpen = open( aResultFileName.ToCString(), O_RDONLY);
3116   // if ( fileOpen < 0 ) {
3117   //   std::cout << std::endl;
3118   //   std::cout << "Can't open the " << aResultFileName.ToCString() << " HYBRID output file" << std::endl;
3119   //   std::cout << "Log: " << aLogFileName << std::endl;
3120   //   Ok = false;
3121   // }
3122   // else {
3123     HYBRIDPlugin_Hypothesis::TSetStrings groupsToRemove = HYBRIDPlugin_Hypothesis::GetGroupsToRemove(_hyp);
3124     bool toMeshHoles =
3125       _hyp ? _hyp->GetToMeshHoles(true) : HYBRIDPlugin_Hypothesis::DefaultMeshHoles();
3126     const bool toMakeGroupsOfDomains = HYBRIDPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
3127
3128     helper.IsQuadraticSubMesh( theShape );
3129     helper.SetElementsOnShape( false );
3130
3131 //     Ok = readResultFile( fileOpen,
3132 // #ifdef WIN32
3133 //                          aResultFileName.ToCString(),
3134 // #endif
3135 //                          this, //theMesh,
3136 //                          helper, tabShape, tabBox, _nbShape, 
3137 //                          aHybridIdToNodeMap, aNodeId2NodeIndexMap,
3138 //                          toMeshHoles, 
3139 //                          nbEnforcedVertices, nbEnforcedNodes, 
3140 //                          enforcedEdges, enforcedTriangles,
3141 //                          toMakeGroupsOfDomains );
3142                          
3143     Ok = readGMFFile(aResultFileName.ToCString(),
3144                      this,
3145                      &helper, aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
3146                      aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
3147                      groupsToRemove, toMakeGroupsOfDomains, toMeshHoles);
3148
3149     //removeEmptyGroupsOfDomains( helper.GetMesh(), notEmptyAsWell );
3150     removeEmptyGroupsOfDomains( helper.GetMesh(), !toMakeGroupsOfDomains );
3151     //}
3152
3153
3154
3155
3156   // ---------------------
3157   // remove working files
3158   // ---------------------
3159
3160   if ( Ok )
3161   {
3162     if ( _removeLogOnSuccess )
3163       removeFile( aLogFileName );
3164
3165     // if ( _hyp && _hyp->GetToMakeGroupsOfDomains() )
3166     //   error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since the mesh is on shape" );
3167   }
3168   else if ( OSD_File( aLogFileName ).Size() > 0 )
3169   {
3170     // get problem description from the log file
3171     _Ghs2smdsConvertor conv( aNodeByHybridId );
3172     storeErrorDescription( aLogFileName, conv );
3173   }
3174   else
3175   {
3176     // the log file is empty
3177     removeFile( aLogFileName );
3178     INFOS( "HYBRID Error, command '" << cmd.ToCString() << "' failed" );
3179     error(COMPERR_ALGO_FAILED, "hybrid: command not found" );
3180   }
3181
3182   if ( !_keepFiles ) {
3183     if (! Ok && _compute_canceled)
3184       removeFile( aLogFileName );
3185     removeFile( aGMFFileName );
3186     removeFile( aRequiredVerticesFileName );
3187     removeFile( aSolFileName );
3188     removeFile( aResSolFileName );
3189     removeFile( aResultFileName );
3190     removeFile( aSmdsToHybridIdMapFileName );
3191   }
3192   std::cout << "<" << aResultFileName.ToCString() << "> HYBRID output file ";
3193   if ( !Ok )
3194     std::cout << "not ";
3195   std::cout << "treated !" << std::endl;
3196   std::cout << std::endl;
3197
3198   // _nbShape = 0;    // re-initializing _nbShape for the next Compute() method call
3199   // delete [] tabShape;
3200   // delete [] tabBox;
3201
3202   return Ok;
3203 }
3204
3205 //=============================================================================
3206 /*!
3207  *Here we are going to use the HYBRID mesher w/o geometry
3208  */
3209 //=============================================================================
3210 bool HYBRIDPlugin_HYBRID::Compute(SMESH_Mesh&         theMesh,
3211                                   SMESH_MesherHelper* theHelper)
3212 {
3213   MESSAGE("HYBRIDPlugin_HYBRID::Compute()");
3214
3215   theHelper->IsQuadraticSubMesh( theHelper->GetSubShape() );
3216
3217   // a unique working file name
3218   // to avoid access to the same files by eg different users
3219   _genericName = HYBRIDPlugin_Hypothesis::GetFileName(_hyp);
3220   TCollection_AsciiString aGenericName((char*) _genericName.c_str() );
3221   TCollection_AsciiString aGenericNameRequired = aGenericName + "_required";
3222
3223   TCollection_AsciiString aLogFileName    = aGenericName + ".log";    // log
3224   TCollection_AsciiString aResultFileName;
3225   bool Ok;
3226
3227   TCollection_AsciiString aGMFFileName, aRequiredVerticesFileName, aSolFileName, aResSolFileName;
3228 //#ifdef _DEBUG_
3229   aGMFFileName              = aGenericName + ".mesh"; // GMF mesh file
3230   aResultFileName           = aGenericName + "Vol.mesh"; // GMF mesh file
3231   aResSolFileName           = aGenericName + "Vol.sol"; // GMF mesh file
3232   aRequiredVerticesFileName = aGenericNameRequired + ".mesh"; // GMF required vertices mesh file
3233   aSolFileName              = aGenericNameRequired + ".sol"; // GMF solution file
3234 //#else
3235 //  aGMFFileName    = aGenericName + ".meshb"; // GMF mesh file
3236 //  aResultFileName = aGenericName + "Vol.meshb"; // GMF mesh file
3237 //  aRequiredVerticesFileName    = aGenericNameRequired + ".meshb"; // GMF required vertices mesh file
3238 //  aSolFileName    = aGenericNameRequired + ".solb"; // GMF solution file
3239 //#endif
3240
3241   std::map <int, int> nodeID2nodeIndexMap;
3242   std::map<std::vector<double>, std::string> enfVerticesWithGroup;
3243   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues coordsSizeMap;
3244   TopoDS_Shape GeomShape;
3245 //   TopAbs_ShapeEnum GeomType;
3246   std::vector<double> coords;
3247   gp_Pnt aPnt;
3248   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertex* enfVertex;
3249
3250   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList enfVertices = HYBRIDPlugin_Hypothesis::GetEnforcedVertices(_hyp);
3251   HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexList::const_iterator enfVerIt = enfVertices.begin();
3252
3253   for ( ; enfVerIt != enfVertices.end() ; ++enfVerIt)
3254   {
3255     enfVertex = (*enfVerIt);
3256 //     if (enfVertex->geomEntry.empty() && enfVertex->coords.size()) {
3257     if (enfVertex->coords.size()) {
3258       coordsSizeMap.insert(make_pair(enfVertex->coords,enfVertex->size));
3259       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
3260 //       MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<enfVertex->coords[0]<<","<<enfVertex->coords[1]<<","<<enfVertex->coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
3261     }
3262     else {
3263 //     if (!enfVertex->geomEntry.empty()) {
3264       GeomShape = entryToShape(enfVertex->geomEntry);
3265 //       GeomType = GeomShape.ShapeType();
3266
3267 //       if (!enfVertex->isCompound) {
3268 // //       if (GeomType == TopAbs_VERTEX) {
3269 //         coords.clear();
3270 //         aPnt = BRep_Tool::Pnt(TopoDS::Vertex(GeomShape));
3271 //         coords.push_back(aPnt.X());
3272 //         coords.push_back(aPnt.Y());
3273 //         coords.push_back(aPnt.Z());
3274 //         if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
3275 //           coordsSizeMap.insert(make_pair(coords,enfVertex->size));
3276 //           enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
3277 //         }
3278 //       }
3279 //
3280 //       // Group Management
3281 //       else {
3282 //       if (GeomType == TopAbs_COMPOUND){
3283         for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
3284           coords.clear();
3285           if (it.Value().ShapeType() == TopAbs_VERTEX){
3286             aPnt = BRep_Tool::Pnt(TopoDS::Vertex(it.Value()));
3287             coords.push_back(aPnt.X());
3288             coords.push_back(aPnt.Y());
3289             coords.push_back(aPnt.Z());
3290             if (coordsSizeMap.find(coords) == coordsSizeMap.end()) {
3291               coordsSizeMap.insert(make_pair(coords,enfVertex->size));
3292               enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
3293 //               MESSAGE("enfVerticesWithGroup.insert(make_pair(("<<coords[0]<<","<<coords[1]<<","<<coords[2]<<"),\""<<enfVertex->groupName<<"\"))");
3294             }
3295           }
3296         }
3297 //       }
3298     }
3299   }
3300
3301 //   const SMDS_MeshNode* enfNode;
3302   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap enforcedNodes = HYBRIDPlugin_Hypothesis::GetEnforcedNodes(_hyp);
3303 //   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt = enforcedNodes.begin();
3304 //   for ( ; enfNodeIt != enforcedNodes.end() ; ++enfNodeIt)
3305 //   {
3306 //     enfNode = enfNodeIt->first;
3307 //     coords.clear();
3308 //     coords.push_back(enfNode->X());
3309 //     coords.push_back(enfNode->Y());
3310 //     coords.push_back(enfNode->Z());
3311 //     if (enfVerticesWithGro
3312 //       enfVerticesWithGroup.insert(make_pair(coords,enfNodeIt->second));
3313 //   }
3314
3315
3316   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedEdges = HYBRIDPlugin_Hypothesis::GetEnforcedEdges(_hyp);
3317   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap enforcedTriangles = HYBRIDPlugin_Hypothesis::GetEnforcedTriangles(_hyp);
3318 //   TIDSortedElemSet enforcedQuadrangles = HYBRIDPlugin_Hypothesis::GetEnforcedQuadrangles(_hyp);
3319   HYBRIDPlugin_Hypothesis::TID2SizeMap nodeIDToSizeMap = HYBRIDPlugin_Hypothesis::GetNodeIDToSizeMap(_hyp);
3320
3321   std::string tmpStr;
3322
3323   int nbEnforcedVertices = coordsSizeMap.size();
3324   int nbEnforcedNodes = enforcedNodes.size();
3325   (nbEnforcedNodes <= 1) ? tmpStr = "node" : tmpStr = "nodes";
3326   std::cout << nbEnforcedNodes << " enforced " << tmpStr << " from hypo" << std::endl;
3327   (nbEnforcedVertices <= 1) ? tmpStr = "vertex" : tmpStr = "vertices";
3328   std::cout << nbEnforcedVertices << " enforced " << tmpStr << " from hypo" << std::endl;
3329
3330   std::vector <const SMDS_MeshNode*> aNodeByHybridId, anEnforcedNodeByHybridId;
3331   std::vector <const SMDS_MeshElement*> aFaceByHybridId;
3332   std::map<const SMDS_MeshNode*,int> aNodeToHybridIdMap;
3333   std::vector<std::string> aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId;
3334   {
3335     SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( theMesh ));
3336     if ( theMesh.NbQuadrangles() > 0 )
3337     {
3338       StdMeshers_QuadToTriaAdaptor* aQuad2Trias = new StdMeshers_QuadToTriaAdaptor;
3339       aQuad2Trias->Compute( theMesh );
3340       proxyMesh.reset( aQuad2Trias );
3341     }
3342
3343     Ok = writeGMFFile(aGMFFileName.ToCString(), aRequiredVerticesFileName.ToCString(), aSolFileName.ToCString(),
3344                       *proxyMesh, *theHelper,
3345                       aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
3346                       aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
3347                       enforcedNodes, enforcedEdges, enforcedTriangles,
3348                       enfVerticesWithGroup, coordsSizeMap);
3349   }
3350
3351   // -----------------
3352   // run hybrid mesher
3353   // -----------------
3354
3355   TCollection_AsciiString cmd = TCollection_AsciiString((char*)HYBRIDPlugin_Hypothesis::CommandToRun( _hyp, false ).c_str());
3356
3357   cmd += TCollection_AsciiString(" --in ") + aGMFFileName;
3358   //if ( nbEnforcedVertices + nbEnforcedNodes)
3359   //  cmd += TCollection_AsciiString(" --required_vertices ") + aGenericNameRequired;
3360   cmd += TCollection_AsciiString(" --out ") + aResultFileName;
3361   if ( !_logInStandardOutput )
3362     cmd += TCollection_AsciiString(" &>" ) + aLogFileName;  // dump into file
3363
3364   std::cout << std::endl;
3365   std::cout << "Hybrid execution w/o geometry..." << std::endl;
3366   std::cout << cmd << std::endl;
3367
3368   _compute_canceled = false;
3369
3370   system( cmd.ToCString() ); // run
3371
3372   std::cout << std::endl;
3373   std::cout << "End of Hybrid execution !" << std::endl;
3374
3375   // --------------
3376   // read a result
3377   // --------------
3378   HYBRIDPlugin_Hypothesis::TSetStrings groupsToRemove = HYBRIDPlugin_Hypothesis::GetGroupsToRemove(_hyp);
3379   const bool toMakeGroupsOfDomains = HYBRIDPlugin_Hypothesis::GetToMakeGroupsOfDomains( _hyp );
3380
3381   Ok = readGMFFile(aResultFileName.ToCString(),
3382                    this,
3383                    theHelper, aNodeByHybridId, aFaceByHybridId, aNodeToHybridIdMap,
3384                    aNodeGroupByHybridId, anEdgeGroupByHybridId, aFaceGroupByHybridId,
3385                    groupsToRemove, toMakeGroupsOfDomains);
3386
3387   updateMeshGroups(theHelper->GetMesh(), groupsToRemove);
3388   //removeEmptyGroupsOfDomains( theHelper->GetMesh(), notEmptyAsWell );
3389   removeEmptyGroupsOfDomains( theHelper->GetMesh(), !toMakeGroupsOfDomains );
3390
3391   if ( Ok ) {
3392     HYBRIDPlugin_Hypothesis* that = (HYBRIDPlugin_Hypothesis*)this->_hyp;
3393     if (that)
3394       that->ClearGroupsToRemove();
3395   }
3396   // ---------------------
3397   // remove working files
3398   // ---------------------
3399
3400   if ( Ok )
3401   {
3402     if ( _removeLogOnSuccess )
3403       removeFile( aLogFileName );
3404
3405     //if ( !toMakeGroupsOfDomains && _hyp && _hyp->GetToMakeGroupsOfDomains() )
3406     //error( COMPERR_WARNING, "'toMakeGroupsOfDomains' is ignored since 'toMeshHoles' is OFF." );
3407   }
3408   else if ( OSD_File( aLogFileName ).Size() > 0 )
3409   {
3410     // get problem description from the log file
3411     _Ghs2smdsConvertor conv( aNodeByHybridId );
3412     storeErrorDescription( aLogFileName, conv );
3413   }
3414   else {
3415     // the log file is empty
3416     removeFile( aLogFileName );
3417     INFOS( "HYBRID Error, command '" << cmd.ToCString() << "' failed" );
3418     error(COMPERR_ALGO_FAILED, "hybrid: command not found" );
3419   }
3420
3421   if ( !_keepFiles )
3422   {
3423     if (! Ok && _compute_canceled)
3424       removeFile( aLogFileName );
3425     removeFile( aGMFFileName );
3426     removeFile( aResultFileName );
3427     removeFile( aRequiredVerticesFileName );
3428     removeFile( aSolFileName );
3429     removeFile( aResSolFileName );
3430   }
3431   return Ok;
3432 }
3433
3434 void HYBRIDPlugin_HYBRID::CancelCompute()
3435 {
3436   _compute_canceled = true;
3437 #ifdef WIN32
3438 #else
3439   std::string cmd = "ps xo pid,args | grep " + _genericName;
3440   //cmd += " | grep -e \"^ *[0-9]\\+ \\+" + HYBRIDPlugin_Hypothesis::GetExeName() + "\"";
3441   cmd += " | awk '{print $1}' | xargs kill -9 > /dev/null 2>&1";
3442   system( cmd.c_str() );
3443 #endif
3444 }
3445
3446 //================================================================================
3447 /*!
3448  * \brief Provide human readable text by error code reported by hybrid
3449  */
3450 //================================================================================
3451
3452 static const char* translateError(const int errNum)
3453 {
3454   switch ( errNum ) {
3455   case 0:
3456     return "error distene 0";
3457   case 1:
3458     return "error distene 1";
3459   }
3460   return "unknown distene error";
3461 }
3462
3463 //================================================================================
3464 /*!
3465  * \brief Retrieve from a string given number of integers
3466  */
3467 //================================================================================
3468
3469 static char* getIds( char* ptr, int nbIds, vector<int>& ids )
3470 {
3471   ids.clear();
3472   ids.reserve( nbIds );
3473   while ( nbIds )
3474   {
3475     while ( !isdigit( *ptr )) ++ptr;
3476     if ( ptr[-1] == '-' ) --ptr;
3477     ids.push_back( strtol( ptr, &ptr, 10 ));
3478     --nbIds;
3479   }
3480   return ptr;
3481 }
3482
3483 //================================================================================
3484 /*!
3485  * \brief Retrieve problem description form a log file
3486  *  \retval bool - always false
3487  */
3488 //================================================================================
3489
3490 bool HYBRIDPlugin_HYBRID::storeErrorDescription(const TCollection_AsciiString& logFile,
3491                                                 const _Ghs2smdsConvertor &     toSmdsConvertor )
3492 {
3493   if(_compute_canceled)
3494     return error(SMESH_Comment("interruption initiated by user"));
3495   // open file
3496 #ifdef WIN32
3497   int file = ::_open (logFile.ToCString(), _O_RDONLY|_O_BINARY);
3498 #else
3499   int file = ::open (logFile.ToCString(), O_RDONLY);
3500 #endif
3501   if ( file < 0 )
3502     return error( SMESH_Comment("See ") << logFile << " for problem description");
3503
3504   // get file size
3505   off_t length = lseek( file, 0, SEEK_END);
3506   lseek( file, 0, SEEK_SET);
3507
3508   // read file
3509   vector< char > buf( length );
3510   int nBytesRead = ::read (file, & buf[0], length);
3511   ::close (file);
3512   char* ptr = & buf[0];
3513   char* bufEnd = ptr + nBytesRead;
3514
3515   SMESH_Comment errDescription;
3516
3517   enum { NODE = 1, EDGE, TRIA, VOL, SKIP_ID = 1 };
3518
3519   // look for MeshGems version
3520   // Since "MG-TETRA -- MeshGems 1.1-3 (January, 2013)" error codes change.
3521   // To discriminate old codes from new ones we add 1000000 to the new codes.
3522   // This way value of the new codes is same as absolute value of codes printed
3523   // in the log after "MGMESSAGE" string.
3524   int versionAddition = 0;
3525   {
3526     char* verPtr = ptr;
3527     while ( ++verPtr < bufEnd )
3528     {
3529       if ( strncmp( verPtr, "MG-TETRA -- MeshGems ", 21 ) != 0 )
3530         continue;
3531       if ( strcmp( verPtr, "MG-TETRA -- MeshGems 1.1-3 " ) >= 0 )
3532         versionAddition = 1000000;
3533       ptr = verPtr;
3534       break;
3535     }
3536   }
3537
3538   // look for errors "ERR #"
3539
3540   set<string> foundErrorStr; // to avoid reporting same error several times
3541   set<int>    elemErrorNums; // not to report different types of errors with bad elements
3542   while ( ++ptr < bufEnd )
3543   {
3544     if ( strncmp( ptr, "ERR ", 4 ) != 0 )
3545       continue;
3546
3547     list<const SMDS_MeshElement*> badElems;
3548     vector<int> nodeIds;
3549
3550     ptr += 4;
3551     char* errBeg = ptr;
3552     int   errNum = strtol(ptr, &ptr, 10) + versionAddition;
3553     // we treat errors enumerated in [SALOME platform 0019316] issue
3554     // and all errors from a new (Release 1.1) MeshGems User Manual
3555     switch ( errNum ) {
3556     case 0015: // The face number (numfac) with vertices (f 1, f 2, f 3) has a null vertex.
3557     case 1005620 : // a too bad quality face is detected. This face is considered degenerated.
3558       ptr = getIds(ptr, SKIP_ID, nodeIds);
3559       ptr = getIds(ptr, TRIA, nodeIds);
3560       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3561       break;
3562     case 1005621 : // a too bad quality face is detected. This face is degenerated.
3563       // hence the is degenerated it is invisible, add its edges in addition
3564       ptr = getIds(ptr, SKIP_ID, nodeIds);
3565       ptr = getIds(ptr, TRIA, nodeIds);
3566       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3567       {
3568         vector<int> edgeNodes( nodeIds.begin(), --nodeIds.end() ); // 01
3569         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
3570         edgeNodes[1] = nodeIds[2]; // 02
3571         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
3572         edgeNodes[0] = nodeIds[1]; // 12
3573       }      
3574       break;
3575     case 1000: // Face (f 1, f 2, f 3) appears more than once in the input surface mesh.
3576       // ERR  1000 :  1 3 2
3577     case 1002: // Face (f 1, f 2, f 3) has a vertex negative or null
3578     case 3019: // Constrained face (f 1, f 2, f 3) cannot be enforced
3579     case 1002211: // a face has a vertex negative or null.
3580     case 1005200 : // a surface mesh appears more than once in the input surface mesh.
3581     case 1008423 : // a constrained face cannot be enforced (regeneration phase failed).
3582       ptr = getIds(ptr, TRIA, nodeIds);
3583       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3584       break;
3585     case 1001: // Edge (e1, e2) appears more than once in the input surface mesh
3586     case 3009: // Constrained edge (e1, e2) cannot be enforced (warning).
3587       // ERR  3109 :  EDGE  5 6 UNIQUE
3588     case 3109: // Edge (e1, e2) is unique (i.e., bounds a hole in the surface)
3589     case 1005210 : // an edge appears more than once in the input surface mesh.
3590     case 1005820 : // an edge is unique (i.e., bounds a hole in the surface).
3591     case 1008441 : // a constrained edge cannot be enforced.
3592       ptr = getIds(ptr, EDGE, nodeIds);
3593       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3594       break;
3595     case 2004: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
3596     case 2014: // at least two points whose distance is dist, i.e., considered as coincident
3597     case 2103: // Vertex v1 and vertex v2 are too close to one another or coincident (warning).
3598       // ERR  2103 :  16 WITH  3
3599     case 1005105 : // two vertices are too close to one another or coincident.
3600     case 1005107: // Two vertices are too close to one another or coincident.
3601       ptr = getIds(ptr, NODE, nodeIds);
3602       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3603       ptr = getIds(ptr, NODE, nodeIds);
3604       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3605       break;
3606     case 2012: // Vertex v1 cannot be inserted (warning).
3607     case 1005106 : // a vertex cannot be inserted.
3608       ptr = getIds(ptr, NODE, nodeIds);
3609       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3610       break;
3611     case 3103: // The surface edge (e1, e2) intersects another surface edge (e3, e4)
3612     case 1005110 : // two surface edges are intersecting.
3613       // ERR  3103 :  1 2 WITH  7 3
3614       ptr = getIds(ptr, EDGE, nodeIds);
3615       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3616       ptr = getIds(ptr, EDGE, nodeIds);
3617       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3618       break;
3619     case 3104: // The surface edge (e1, e2) intersects the surface face (f 1, f 2, f 3)
3620       // ERR  3104 :  9 10 WITH  1 2 3
3621     case 3106: // One surface edge (say e1, e2) intersects a surface face (f 1, f 2, f 3)
3622     case 1005120 : // a surface edge intersects a surface face.
3623       ptr = getIds(ptr, EDGE, nodeIds);
3624       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3625       ptr = getIds(ptr, TRIA, nodeIds);
3626       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3627       break;
3628     case 3105: // One boundary point (say p1) lies within a surface face (f 1, f 2, f 3)
3629       // ERR  3105 :  8 IN  2 3 5
3630     case 1005150 : // a boundary point lies within a surface face.
3631       ptr = getIds(ptr, NODE, nodeIds);
3632       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3633       ptr = getIds(ptr, TRIA, nodeIds);
3634       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3635       break;
3636     case 3107: // One boundary point (say p1) lies within a surface edge (e1, e2) (stop).
3637       // ERR  3107 :  2 IN  4 1
3638     case 1005160 : // a boundary point lies within a surface edge.
3639       ptr = getIds(ptr, NODE, nodeIds);
3640       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3641       ptr = getIds(ptr, EDGE, nodeIds);
3642       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3643       break;
3644     case 9000: // ERR  9000
3645       //  ELEMENT  261 WITH VERTICES :  7 396 -8 242
3646       //  VOLUME   : -1.11325045E+11 W.R.T. EPSILON   0.
3647       // A too small volume element is detected. Are reported the index of the element,
3648       // its four vertex indices, its volume and the tolerance threshold value
3649       ptr = getIds(ptr, SKIP_ID, nodeIds);
3650       ptr = getIds(ptr, VOL, nodeIds);
3651       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3652       // even if all nodes found, volume it most probably invisible,
3653       // add its faces to demonstrate it anyhow
3654       {
3655         vector<int> faceNodes( nodeIds.begin(), --nodeIds.end() ); // 012
3656         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
3657         faceNodes[2] = nodeIds[3]; // 013
3658         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
3659         faceNodes[1] = nodeIds[2]; // 023
3660         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
3661         faceNodes[0] = nodeIds[1]; // 123
3662         badElems.push_back( toSmdsConvertor.getElement(faceNodes));
3663       }
3664       break;
3665     case 9001: // ERR  9001
3666       //  %% NUMBER OF NEGATIVE VOLUME TETS  :  1
3667       //  %% THE LARGEST NEGATIVE TET        :   1.75376581E+11
3668       //  %%  NUMBER OF NULL VOLUME TETS     :  0
3669       // There exists at least a null or negative volume element
3670       break;
3671     case 9002:
3672       // There exist n null or negative volume elements
3673       break;
3674     case 9003:
3675       // A too small volume element is detected
3676       break;
3677     case 9102:
3678       // A too bad quality face is detected. This face is considered degenerated,
3679       // its index, its three vertex indices together with its quality value are reported
3680       break; // same as next
3681     case 9112: // ERR  9112
3682       //  FACE   2 WITH VERTICES :  4 2 5
3683       //  SMALL INRADIUS :   0.
3684       // A too bad quality face is detected. This face is degenerated,
3685       // its index, its three vertex indices together with its inradius are reported
3686       ptr = getIds(ptr, SKIP_ID, nodeIds);
3687       ptr = getIds(ptr, TRIA, nodeIds);
3688       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3689       // add triangle edges as it most probably has zero area and hence invisible
3690       {
3691         vector<int> edgeNodes(2);
3692         edgeNodes[0] = nodeIds[0]; edgeNodes[1] = nodeIds[1]; // 0-1
3693         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
3694         edgeNodes[1] = nodeIds[2]; // 0-2
3695         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
3696         edgeNodes[0] = nodeIds[1]; // 1-2
3697         badElems.push_back( toSmdsConvertor.getElement(edgeNodes));
3698       }
3699       break;
3700     case 1005103 : // the vertices of an element are too close to one another or coincident.
3701       ptr = getIds(ptr, TRIA, nodeIds);
3702       if ( nodeIds.back() == 0 ) // index of the third vertex of the element (0 for an edge)
3703         nodeIds.resize( EDGE );
3704       badElems.push_back( toSmdsConvertor.getElement(nodeIds));
3705       break;
3706     }
3707
3708     bool isNewError = foundErrorStr.insert( string( errBeg, ptr )).second;
3709     if ( !isNewError )
3710       continue; // not to report same error several times
3711
3712 //     const SMDS_MeshElement* nullElem = 0;
3713 //     bool allElemsOk = ( find( badElems.begin(), badElems.end(), nullElem) == badElems.end());
3714
3715 //     if ( allElemsOk && !badElems.empty() && !elemErrorNums.empty() ) {
3716 //       bool oneMoreErrorType = elemErrorNums.insert( errNum ).second;
3717 //       if ( oneMoreErrorType )
3718 //         continue; // not to report different types of errors with bad elements
3719 //     }
3720
3721     // store bad elements
3722     //if ( allElemsOk ) {
3723       list<const SMDS_MeshElement*>::iterator elem = badElems.begin();
3724       for ( ; elem != badElems.end(); ++elem )
3725         addBadInputElement( *elem );
3726       //}
3727
3728     // make error text
3729     string text = translateError( errNum );
3730     if ( errDescription.find( text ) == text.npos ) {
3731       if ( !errDescription.empty() )
3732         errDescription << "\n";
3733       errDescription << text;
3734     }
3735
3736   } // end while
3737
3738   if ( errDescription.empty() ) { // no errors found
3739     char msgLic1[] = "connection to server failed";
3740     char msgLic2[] = " Dlim ";
3741     if ( search( &buf[0], bufEnd, msgLic1, msgLic1 + strlen(msgLic1)) != bufEnd ||
3742          search( &buf[0], bufEnd, msgLic2, msgLic2 + strlen(msgLic2)) != bufEnd )
3743       errDescription << "Licence problems.";
3744     else
3745     {
3746       char msg2[] = "SEGMENTATION FAULT";
3747       if ( search( &buf[0], bufEnd, msg2, msg2 + strlen(msg2)) != bufEnd )
3748         errDescription << "hybrid: SEGMENTATION FAULT. ";
3749     }
3750   }
3751
3752   if ( errDescription.empty() )
3753     errDescription << "See " << logFile << " for problem description";
3754   else
3755     errDescription << "\nSee " << logFile << " for more information";
3756
3757   return error( errDescription );
3758 }
3759
3760 //================================================================================
3761 /*!
3762  * \brief Creates _Ghs2smdsConvertor
3763  */
3764 //================================================================================
3765
3766 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const map <int,const SMDS_MeshNode*> & ghs2NodeMap)
3767   :_ghs2NodeMap( & ghs2NodeMap ), _nodeByGhsId( 0 )
3768 {
3769 }
3770
3771 //================================================================================
3772 /*!
3773  * \brief Creates _Ghs2smdsConvertor
3774  */
3775 //================================================================================
3776
3777 _Ghs2smdsConvertor::_Ghs2smdsConvertor( const vector <const SMDS_MeshNode*> &  nodeByGhsId)
3778   : _ghs2NodeMap( 0 ), _nodeByGhsId( &nodeByGhsId )
3779 {
3780 }
3781
3782 //================================================================================
3783 /*!
3784  * \brief Return SMDS element by ids of HYBRID nodes
3785  */
3786 //================================================================================
3787
3788 const SMDS_MeshElement* _Ghs2smdsConvertor::getElement(const vector<int>& ghsNodes) const
3789 {
3790   size_t nbNodes = ghsNodes.size();
3791   vector<const SMDS_MeshNode*> nodes( nbNodes, 0 );
3792   for ( size_t i = 0; i < nbNodes; ++i ) {
3793     int ghsNode = ghsNodes[ i ];
3794     if ( _ghs2NodeMap ) {
3795       map <int,const SMDS_MeshNode*>::const_iterator in = _ghs2NodeMap->find( ghsNode);
3796       if ( in == _ghs2NodeMap->end() )
3797         return 0;
3798       nodes[ i ] = in->second;
3799     }
3800     else {
3801       if ( ghsNode < 1 || ghsNode > _nodeByGhsId->size() )
3802         return 0;
3803       nodes[ i ] = (*_nodeByGhsId)[ ghsNode-1 ];
3804     }
3805   }
3806   if ( nbNodes == 1 )
3807     return nodes[0];
3808
3809   if ( nbNodes == 2 ) {
3810     const SMDS_MeshElement* edge= SMDS_Mesh::FindEdge( nodes[0], nodes[1] );
3811     if ( !edge )
3812       edge = new SMDS_LinearEdge( nodes[0], nodes[1] );
3813     return edge;
3814   }
3815   if ( nbNodes == 3 ) {
3816     const SMDS_MeshElement* face = SMDS_Mesh::FindFace( nodes );
3817     if ( !face )
3818       face = new SMDS_FaceOfNodes( nodes[0], nodes[1], nodes[2] );
3819     return face;
3820   }
3821   if ( nbNodes == 4 )
3822     return new SMDS_VolumeOfNodes( nodes[0], nodes[1], nodes[2], nodes[3] );
3823
3824   return 0;
3825 }
3826
3827
3828 //=============================================================================
3829 /*!
3830  *
3831  */
3832 //=============================================================================
3833 bool HYBRIDPlugin_HYBRID::Evaluate(SMESH_Mesh& aMesh,
3834                                  const TopoDS_Shape& aShape,
3835                                  MapShapeNbElems& aResMap)
3836 {
3837   int nbtri = 0, nbqua = 0;
3838   double fullArea = 0.0;
3839   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3840     TopoDS_Face F = TopoDS::Face( exp.Current() );
3841     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3842     MapShapeNbElemsItr anIt = aResMap.find(sm);
3843     if( anIt==aResMap.end() ) {
3844       SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3845       smError.reset( new SMESH_ComputeError(COMPERR_ALGO_FAILED,
3846                                             "Submesh can not be evaluated",this));
3847       return false;
3848     }
3849     std::vector<int> aVec = (*anIt).second;
3850     nbtri += Max(aVec[SMDSEntity_Triangle],aVec[SMDSEntity_Quad_Triangle]);
3851     nbqua += Max(aVec[SMDSEntity_Quadrangle],aVec[SMDSEntity_Quad_Quadrangle]);
3852     GProp_GProps G;
3853     BRepGProp::SurfaceProperties(F,G);
3854     double anArea = G.Mass();
3855     fullArea += anArea;
3856   }
3857
3858   // collect info from edges
3859   int nb0d_e = 0, nb1d_e = 0;
3860   bool IsQuadratic = false;
3861   bool IsFirst = true;
3862   TopTools_MapOfShape tmpMap;
3863   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3864     TopoDS_Edge E = TopoDS::Edge(exp.Current());
3865     if( tmpMap.Contains(E) )
3866       continue;
3867     tmpMap.Add(E);
3868     SMESH_subMesh *aSubMesh = aMesh.GetSubMesh(exp.Current());
3869     MapShapeNbElemsItr anIt = aResMap.find(aSubMesh);
3870     std::vector<int> aVec = (*anIt).second;
3871     nb0d_e += aVec[SMDSEntity_Node];
3872     nb1d_e += Max(aVec[SMDSEntity_Edge],aVec[SMDSEntity_Quad_Edge]);
3873     if(IsFirst) {
3874       IsQuadratic = (aVec[SMDSEntity_Quad_Edge] > aVec[SMDSEntity_Edge]);
3875       IsFirst = false;
3876     }
3877   }
3878   tmpMap.Clear();
3879
3880   double ELen = sqrt(2.* ( fullArea/(nbtri+nbqua*2) ) / sqrt(3.0) );
3881
3882   GProp_GProps G;
3883   BRepGProp::VolumeProperties(aShape,G);
3884   double aVolume = G.Mass();
3885   double tetrVol = 0.1179*ELen*ELen*ELen;
3886   double CoeffQuality = 0.9;
3887   int nbVols = int(aVolume/tetrVol/CoeffQuality);
3888   int nb1d_f = (nbtri*3 + nbqua*4 - nb1d_e) / 2;
3889   int nb1d_in = (int) ( nbVols*6 - nb1d_e - nb1d_f ) / 5;
3890   std::vector<int> aVec(SMDSEntity_Last);
3891   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3892   if( IsQuadratic ) {
3893     aVec[SMDSEntity_Node] = nb1d_in/6 + 1 + nb1d_in;
3894     aVec[SMDSEntity_Quad_Tetra] = nbVols - nbqua*2;
3895     aVec[SMDSEntity_Quad_Pyramid] = nbqua;
3896   }
3897   else {
3898     aVec[SMDSEntity_Node] = nb1d_in/6 + 1;
3899     aVec[SMDSEntity_Tetra] = nbVols - nbqua*2;
3900     aVec[SMDSEntity_Pyramid] = nbqua;
3901   }
3902   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3903   aResMap.insert(std::make_pair(sm,aVec));
3904
3905   return true;
3906 }
3907
3908 bool HYBRIDPlugin_HYBRID::importGMFMesh(const char* theGMFFileName, SMESH_Mesh& theMesh)
3909 {
3910   SMESH_MesherHelper* helper  = new SMESH_MesherHelper(theMesh );
3911   std::vector <const SMDS_MeshNode*> dummyNodeVector;
3912   std::vector <const SMDS_MeshElement*> aFaceByHybridId;
3913   std::map<const SMDS_MeshNode*,int> dummyNodeMap;
3914   std::map<std::vector<double>, std::string> dummyEnfVertGroup;
3915   std::vector<std::string> dummyElemGroup;
3916   std::set<std::string> dummyGroupsToRemove;
3917
3918   bool ok = readGMFFile(theGMFFileName,
3919                         this,
3920                         helper, dummyNodeVector, aFaceByHybridId, dummyNodeMap, dummyElemGroup, dummyElemGroup, dummyElemGroup, dummyGroupsToRemove);
3921   theMesh.GetMeshDS()->Modified();
3922   return ok;
3923 }
3924
3925 namespace
3926 {
3927   //================================================================================
3928   /*!
3929    * \brief Sub-mesh event listener setting enforced elements as soon as an enforced
3930    *        mesh is loaded
3931    */
3932   struct _EnforcedMeshRestorer : public SMESH_subMeshEventListener
3933   {
3934     _EnforcedMeshRestorer():
3935       SMESH_subMeshEventListener( /*isDeletable = */true, Name() )
3936     {}
3937
3938     //================================================================================
3939     /*!
3940      * \brief Returns an ID of listener
3941      */
3942     static const char* Name() { return "HYBRIDPlugin_HYBRID::_EnforcedMeshRestorer"; }
3943
3944     //================================================================================
3945     /*!
3946      * \brief Treat events of the subMesh
3947      */
3948     void ProcessEvent(const int                       event,
3949                       const int                       eventType,
3950                       SMESH_subMesh*                  subMesh,
3951                       SMESH_subMeshEventListenerData* data,
3952                       const SMESH_Hypothesis*         hyp)
3953     {
3954       if ( SMESH_subMesh::SUBMESH_LOADED == event &&
3955            SMESH_subMesh::COMPUTE_EVENT  == eventType &&
3956            data &&
3957            !data->mySubMeshes.empty() )
3958       {
3959         // An enforced mesh (subMesh->_father) has been loaded from hdf file
3960         if ( HYBRIDPlugin_Hypothesis* hyp = GetGHSHypothesis( data->mySubMeshes.front() ))
3961           hyp->RestoreEnfElemsByMeshes();
3962       }
3963     }
3964     //================================================================================
3965     /*!
3966      * \brief Returns HYBRIDPlugin_Hypothesis used to compute a subMesh
3967      */
3968     static HYBRIDPlugin_Hypothesis* GetGHSHypothesis( SMESH_subMesh* subMesh )
3969     {
3970       SMESH_HypoFilter ghsHypFilter( SMESH_HypoFilter::HasName( "HYBRID_Parameters" ));
3971       return (HYBRIDPlugin_Hypothesis* )
3972         subMesh->GetFather()->GetHypothesis( subMesh->GetSubShape(),
3973                                              ghsHypFilter,
3974                                              /*visitAncestors=*/true);
3975     }
3976   };
3977
3978   //================================================================================
3979   /*!
3980    * \brief Sub-mesh event listener removing empty groups created due to "To make
3981    *        groups of domains".
3982    */
3983   struct _GroupsOfDomainsRemover : public SMESH_subMeshEventListener
3984   {
3985     _GroupsOfDomainsRemover():
3986       SMESH_subMeshEventListener( /*isDeletable = */true,
3987                                   "HYBRIDPlugin_HYBRID::_GroupsOfDomainsRemover" ) {}
3988     /*!
3989      * \brief Treat events of the subMesh
3990      */
3991     void ProcessEvent(const int                       event,
3992                       const int                       eventType,
3993                       SMESH_subMesh*                  subMesh,
3994                       SMESH_subMeshEventListenerData* data,
3995                       const SMESH_Hypothesis*         hyp)
3996     {
3997       if (SMESH_subMesh::ALGO_EVENT == eventType &&
3998           !subMesh->GetAlgo() )
3999       {
4000         removeEmptyGroupsOfDomains( subMesh->GetFather(), /*notEmptyAsWell=*/true );
4001       }
4002     }
4003   };
4004 }
4005
4006 //================================================================================
4007 /*!
4008  * \brief Set an event listener to set enforced elements as soon as an enforced
4009  *        mesh is loaded
4010  */
4011 //================================================================================
4012
4013 void HYBRIDPlugin_HYBRID::SubmeshRestored(SMESH_subMesh* subMesh)
4014 {
4015   if ( HYBRIDPlugin_Hypothesis* hyp = _EnforcedMeshRestorer::GetGHSHypothesis( subMesh ))
4016   {
4017     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMeshList enfMeshes = hyp->_GetEnforcedMeshes();
4018     HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMeshList::iterator it = enfMeshes.begin();
4019     for(;it != enfMeshes.end();++it) {
4020       HYBRIDPlugin_Hypothesis::THYBRIDEnforcedMesh* enfMesh = *it;
4021       if ( SMESH_Mesh* mesh = GetMeshByPersistentID( enfMesh->persistID ))
4022       {
4023         SMESH_subMesh* smToListen = mesh->GetSubMesh( mesh->GetShapeToMesh() );
4024         // a listener set to smToListen will care of hypothesis stored in SMESH_EventListenerData
4025         subMesh->SetEventListener( new _EnforcedMeshRestorer(),
4026                                    SMESH_subMeshEventListenerData::MakeData( subMesh ),
4027                                    smToListen);
4028       }
4029     }
4030   }
4031 }
4032
4033 //================================================================================
4034 /*!
4035  * \brief Sets an event listener removing empty groups created due to "To make
4036  *        groups of domains".
4037  * \param subMesh - submesh where algo is set
4038  *
4039  * This method is called when a submesh gets HYP_OK algo_state.
4040  * After being set, event listener is notified on each event of a submesh.
4041  */
4042 //================================================================================
4043
4044 void HYBRIDPlugin_HYBRID::SetEventListener(SMESH_subMesh* subMesh)
4045 {
4046   subMesh->SetEventListener( new _GroupsOfDomainsRemover(), 0, subMesh );
4047 }