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