]> SALOME platform Git repositories - plugins/hybridplugin.git/blob - src/HYBRIDPlugin/HYBRIDPlugin_HYBRID.cxx
Salome HOME
mg-hybrid.exe_Linux_64_juillet2014 et maj doc
[plugins/hybridplugin.git] / src / HYBRIDPlugin / HYBRIDPlugin_HYBRID.cxx
1 // Copyright (C) 2004-2013  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 //=============================================================================
21 // File      : HYBRIDPlugin_HYBRID.cxx
22 // Created   : 
23 // Author    : Edward AGAPOV, modified by Lioka RAZAFINDRAZAKA (CEA) 09/02/2007
24 // Project   : SALOME
25 //=============================================================================
26 //
27 #include "HYBRIDPlugin_HYBRID.hxx"
28 #include "HYBRIDPlugin_Hypothesis.hxx"
29
30 #include <SMDS_FaceOfNodes.hxx>
31 #include <SMDS_MeshElement.hxx>
32 #include <SMDS_MeshNode.hxx>
33 #include <SMDS_VolumeOfNodes.hxx>
34 #include <SMESHDS_Group.hxx>
35 #include <SMESH_Comment.hxx>
36 #include <SMESH_Group.hxx>
37 #include <SMESH_HypoFilter.hxx>
38 #include <SMESH_Mesh.hxx>
39 #include <SMESH_MeshAlgos.hxx>
40 #include <SMESH_MeshEditor.hxx>
41 #include <SMESH_MesherHelper.hxx>
42 #include <SMESH_OctreeNode.hxx>
43 #include <SMESH_subMeshEventListener.hxx>
44 #include <StdMeshers_QuadToTriaAdaptor.hxx>
45 #include <StdMeshers_ViscousLayers.hxx>
46
47 #include <BRepAdaptor_Surface.hxx>
48 #include <BRepBndLib.hxx>
49 #include <BRepBuilderAPI_MakeVertex.hxx>
50 #include <BRepClass3d.hxx>
51 #include <BRepClass3d_SolidClassifier.hxx>
52 #include <BRepExtrema_DistShapeShape.hxx>
53 #include <BRepGProp.hxx>
54 #include <BRepTools.hxx>
55 #include <BRep_Tool.hxx>
56 #include <Bnd_Box.hxx>
57 #include <GProp_GProps.hxx>
58 #include <GeomAPI_ProjectPointOnSurf.hxx>
59 #include <OSD_File.hxx>
60 #include <Precision.hxx>
61 #include <Standard_ErrorHandler.hxx>
62 #include <Standard_Failure.hxx>
63 #include <Standard_ProgramError.hxx>
64 #include <TopExp.hxx>
65 #include <TopExp_Explorer.hxx>
66 #include <TopTools_IndexedMapOfShape.hxx>
67 #include <TopTools_ListIteratorOfListOfShape.hxx>
68 #include <TopTools_MapOfShape.hxx>
69 #include <TopoDS.hxx>
70 #include <TopoDS_Shell.hxx>
71 #include <TopoDS_Solid.hxx>
72
73 #include <Basics_Utils.hxx>
74 #include <utilities.h>
75
76 #ifdef WIN32
77 #include <io.h>
78 #else
79 #include <sys/sysinfo.h>
80 #endif
81 #include <algorithm>
82
83 #define castToNode(n) static_cast<const SMDS_MeshNode *>( n );
84
85 extern "C"
86 {
87 #ifndef WIN32
88 #include <unistd.h>
89 #include <sys/mman.h>
90 #endif
91 #include <sys/stat.h>
92 #include <fcntl.h>
93 }
94
95 #define HOLE_ID -1
96
97 typedef const list<const SMDS_MeshFace*> TTriaList;
98
99 static const char theDomainGroupNamePrefix[] = "Domain_";
100
101 static void removeFile( const TCollection_AsciiString& fileName )
102 {
103   try {
104     OSD_File( fileName ).Remove();
105   }
106   catch ( Standard_ProgramError ) {
107     MESSAGE("Can't remove file: " << fileName.ToCString() << " ; file does not exist or permission denied");
108   }
109 }
110
111 //=============================================================================
112 /*!
113  *  
114  */
115 //=============================================================================
116
117 HYBRIDPlugin_HYBRID::HYBRIDPlugin_HYBRID(int hypId, int studyId, SMESH_Gen* gen)
118   : SMESH_3D_Algo(hypId, studyId, gen)
119 {
120   MESSAGE("HYBRIDPlugin_HYBRID::HYBRIDPlugin_HYBRID");
121   _name = Name();
122   _shapeType = (1 << TopAbs_SHELL) | (1 << TopAbs_SOLID);// 1 bit /shape type
123   _onlyUnaryInput = false; // Compute() will be called on a compound of solids
124   _iShape=0;
125   _nbShape=0;
126   _compatibleHypothesis.push_back( HYBRIDPlugin_Hypothesis::GetHypType());
127   _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
128   _requireShape = false; // can work without shape_studyId
129
130   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
131   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
132   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
133
134   MESSAGE("studyid = " << _studyId);
135
136   myStudy = NULL;
137   myStudy = aStudyMgr->GetStudyByID(_studyId);
138   if (myStudy)
139     MESSAGE("myStudy->StudyId() = " << myStudy->StudyId());
140   
141   _compute_canceled = false;
142 }
143
144 //=============================================================================
145 /*!
146  *  
147  */
148 //=============================================================================
149
150 HYBRIDPlugin_HYBRID::~HYBRIDPlugin_HYBRID()
151 {
152   MESSAGE("HYBRIDPlugin_HYBRID::~HYBRIDPlugin_HYBRID");
153 }
154
155 //=============================================================================
156 /*!
157  *  
158  */
159 //=============================================================================
160
161 bool HYBRIDPlugin_HYBRID::CheckHypothesis ( SMESH_Mesh&         aMesh,
162                                           const TopoDS_Shape& aShape,
163                                           Hypothesis_Status&  aStatus )
164 {
165   aStatus = SMESH_Hypothesis::HYP_OK;
166
167   _hyp = 0;
168   _viscousLayersHyp = 0;
169   _keepFiles = false;
170   _removeLogOnSuccess = true;
171   _logInStandardOutput = false;
172
173   const list <const SMESHDS_Hypothesis * >& hyps =
174     GetUsedHypothesis(aMesh, aShape, /*ignoreAuxiliary=*/false);
175   list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
176   for ( ; h != hyps.end(); ++h )
177   {
178     if ( !_hyp )
179       _hyp = dynamic_cast< const HYBRIDPlugin_Hypothesis*> ( *h );
180     if ( !_viscousLayersHyp )
181       _viscousLayersHyp = dynamic_cast< const StdMeshers_ViscousLayers*> ( *h );
182   }
183   if ( _hyp )
184   {
185     _keepFiles = _hyp->GetKeepFiles();
186     _removeLogOnSuccess = _hyp->GetRemoveLogOnSuccess();
187     _logInStandardOutput = _hyp->GetStandardOutputLog();
188   }
189
190   return true;
191 }
192
193
194 //=======================================================================
195 //function : entryToShape
196 //purpose  : 
197 //=======================================================================
198
199 TopoDS_Shape HYBRIDPlugin_HYBRID::entryToShape(std::string entry)
200 {
201   MESSAGE("HYBRIDPlugin_HYBRID::entryToShape "<<entry );
202   GEOM::GEOM_Object_var aGeomObj;
203   TopoDS_Shape S = TopoDS_Shape();
204   SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
205   if (!aSObj->_is_nil() ) {
206     CORBA::Object_var obj = aSObj->GetObject();
207     aGeomObj = GEOM::GEOM_Object::_narrow(obj);
208     aSObj->UnRegister();
209   }
210   if ( !aGeomObj->_is_nil() )
211     S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
212   return S;
213 }
214
215 //=======================================================================
216 //function : findShape
217 //purpose  : 
218 //=======================================================================
219
220 static TopoDS_Shape findShape(const SMDS_MeshNode *aNode[],
221                               TopoDS_Shape        aShape,
222                               const TopoDS_Shape  shape[],
223                               double**            box,
224                               const int           nShape,
225                               TopAbs_State *      state = 0)
226 {
227   gp_XYZ aPnt(0,0,0);
228   int j, iShape, nbNode = 4;
229
230   for ( j=0; j<nbNode; j++ ) {
231     gp_XYZ p ( aNode[j]->X(), aNode[j]->Y(), aNode[j]->Z() );
232     if ( aNode[j]->GetPosition()->GetTypeOfPosition() == SMDS_TOP_3DSPACE ) {
233       aPnt = p;
234       break;
235     }
236     aPnt += p / nbNode;
237   }
238
239   BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
240   if (state) *state = SC.State();
241   if ( SC.State() != TopAbs_IN || aShape.IsNull() || aShape.ShapeType() != TopAbs_SOLID) {
242     for (iShape = 0; iShape < nShape; iShape++) {
243       aShape = shape[iShape];
244       if ( !( aPnt.X() < box[iShape][0] || box[iShape][1] < aPnt.X() ||
245               aPnt.Y() < box[iShape][2] || box[iShape][3] < aPnt.Y() ||
246               aPnt.Z() < box[iShape][4] || box[iShape][5] < aPnt.Z()) ) {
247         BRepClass3d_SolidClassifier SC (aShape, aPnt, Precision::Confusion());
248         if (state) *state = SC.State();
249         if (SC.State() == TopAbs_IN)
250           break;
251       }
252     }
253   }
254   return aShape;
255 }
256
257 //=======================================================================
258 //function : readMapIntLine
259 //purpose  : 
260 //=======================================================================
261
262 static char* readMapIntLine(char* ptr, int tab[]) {
263   long int intVal;
264   std::cout << std::endl;
265
266   for ( int i=0; i<17; i++ ) {
267     intVal = strtol(ptr, &ptr, 10);
268     if ( i < 3 )
269       tab[i] = intVal;
270   }
271   return ptr;
272 }
273
274 //================================================================================
275 /*!
276  * \brief returns true if a triangle defined by the nodes is a temporary face on a
277  * side facet of pyramid and defines sub-domain inside the pyramid
278  */
279 //================================================================================
280
281 static bool isTmpFace(const SMDS_MeshNode* node1,
282                       const SMDS_MeshNode* node2,
283                       const SMDS_MeshNode* node3)
284 {
285   // find a pyramid sharing the 3 nodes
286   //const SMDS_MeshElement* pyram = 0;
287   SMDS_ElemIteratorPtr vIt1 = node1->GetInverseElementIterator(SMDSAbs_Volume);
288   while ( vIt1->more() )
289   {
290     const SMDS_MeshElement* pyram = vIt1->next();
291     if ( pyram->NbCornerNodes() != 5 ) continue;
292     int i2, i3;
293     if ( (i2 = pyram->GetNodeIndex( node2 )) >= 0 &&
294          (i3 = pyram->GetNodeIndex( node3 )) >= 0 )
295     {
296       // Triangle defines sub-domian inside the pyramid if it's
297       // normal points out of the pyram
298
299       // make i2 and i3 hold indices of base nodes of the pyram while
300       // keeping the nodes order in the triangle
301       const int iApex = 4;
302       if ( i2 == iApex )
303         i2 = i3, i3 = pyram->GetNodeIndex( node1 );
304       else if ( i3 == iApex )
305         i3 = i2, i2 = pyram->GetNodeIndex( node1 );
306
307       int i3base = (i2+1) % 4; // next index after i2 within the pyramid base
308       return ( i3base != i3 );
309     }
310   }
311   return false;
312 }
313
314 //=======================================================================
315 //function : findShapeID
316 //purpose  : find the solid corresponding to HYBRID sub-domain following
317 //           the technique proposed in GHS3D manual (available within
318 //           ghs3d installation) in chapter "B.4 Subdomain (sub-region) assignment".
319 //           In brief: normal of the triangle defined by the given nodes
320 //           points out of the domain it is associated to
321 //=======================================================================
322
323 static int findShapeID(SMESH_Mesh&          mesh,
324                        const SMDS_MeshNode* node1,
325                        const SMDS_MeshNode* node2,
326                        const SMDS_MeshNode* node3,
327                        const bool           toMeshHoles)
328 {
329   const int invalidID = 0;
330   SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
331
332   // face the nodes belong to
333   vector<const SMDS_MeshNode *> nodes(3);
334   nodes[0] = node1;
335   nodes[1] = node2;
336   nodes[2] = node3;
337   const SMDS_MeshElement * face = meshDS->FindElement( nodes, SMDSAbs_Face, /*noMedium=*/true);
338   if ( !face )
339     return isTmpFace(node1, node2, node3) ? HOLE_ID : invalidID;
340 #ifdef _DEBUG_
341   std::cout << "bnd face " << face->GetID() << " - ";
342 #endif
343   // geom face the face assigned to
344   SMESH_MeshEditor editor(&mesh);
345   int geomFaceID = editor.FindShape( face );
346   if ( !geomFaceID )
347     return isTmpFace(node1, node2, node3) ? HOLE_ID : invalidID;
348   TopoDS_Shape shape = meshDS->IndexToShape( geomFaceID );
349   if ( shape.IsNull() || shape.ShapeType() != TopAbs_FACE )
350     return invalidID;
351   TopoDS_Face geomFace = TopoDS::Face( shape );
352
353   // solids bounded by geom face
354   TopTools_IndexedMapOfShape solids, shells;
355   TopTools_ListIteratorOfListOfShape ansIt = mesh.GetAncestors(geomFace);
356   for ( ; ansIt.More(); ansIt.Next() ) {
357     switch ( ansIt.Value().ShapeType() ) {
358     case TopAbs_SOLID:
359       solids.Add( ansIt.Value() ); break;
360     case TopAbs_SHELL:
361       shells.Add( ansIt.Value() ); break;
362     default:;
363     }
364   }
365   // analyse found solids
366   if ( solids.Extent() == 0 || shells.Extent() == 0)
367     return invalidID;
368
369   const TopoDS_Solid& solid1 = TopoDS::Solid( solids(1) );
370   if ( solids.Extent() == 1 )
371   {
372     if ( toMeshHoles )
373       return meshDS->ShapeToIndex( solid1 );
374
375     // - Are we at a hole boundary face?
376     if ( shells(1).IsSame( BRepClass3d::OuterShell( solid1 )) )
377     { // - No, but maybe a hole is bound by two shapes? Does shells(1) touches another shell?
378       bool touch = false;
379       TopExp_Explorer eExp( shells(1), TopAbs_EDGE );
380       // check if any edge of shells(1) belongs to another shell
381       for ( ; eExp.More() && !touch; eExp.Next() ) {
382         ansIt = mesh.GetAncestors( eExp.Current() );
383         for ( ; ansIt.More() && !touch; ansIt.Next() ) {
384           if ( ansIt.Value().ShapeType() == TopAbs_SHELL )
385             touch = ( !ansIt.Value().IsSame( shells(1) ));
386         }
387       }
388       if (!touch)
389         return meshDS->ShapeToIndex( solid1 );
390     }
391   }
392   // find orientation of geom face within the first solid
393   TopExp_Explorer fExp( solid1, TopAbs_FACE );
394   for ( ; fExp.More(); fExp.Next() )
395     if ( geomFace.IsSame( fExp.Current() )) {
396       geomFace = TopoDS::Face( fExp.Current() );
397       break;
398     }
399   if ( !fExp.More() )
400     return invalidID; // face not found
401
402   // normale to triangle
403   gp_Pnt node1Pnt ( node1->X(), node1->Y(), node1->Z() );
404   gp_Pnt node2Pnt ( node2->X(), node2->Y(), node2->Z() );
405   gp_Pnt node3Pnt ( node3->X(), node3->Y(), node3->Z() );
406   gp_Vec vec12( node1Pnt, node2Pnt );
407   gp_Vec vec13( node1Pnt, node3Pnt );
408   gp_Vec meshNormal = vec12 ^ vec13;
409   if ( meshNormal.SquareMagnitude() < DBL_MIN )
410     return invalidID;
411
412   // get normale to geomFace at any node
413   bool geomNormalOK = false;
414   gp_Vec geomNormal;
415   SMESH_MesherHelper helper( mesh ); helper.SetSubShape( geomFace );
416   for ( int i = 0; !geomNormalOK && i < 3; ++i )
417   {
418     // find UV of i-th node on geomFace
419     const SMDS_MeshNode* nNotOnSeamEdge = 0;
420     if ( helper.IsSeamShape( nodes[i]->getshapeId() )) {
421       if ( helper.IsSeamShape( nodes[(i+1)%3]->getshapeId() ))
422         nNotOnSeamEdge = nodes[(i+2)%3];
423       else
424         nNotOnSeamEdge = nodes[(i+1)%3];
425     }
426     bool uvOK;
427     gp_XY uv = helper.GetNodeUV( geomFace, nodes[i], nNotOnSeamEdge, &uvOK );
428     // check that uv is correct
429     if (uvOK) {
430       double tol = 1e-6;
431       TopoDS_Shape nodeShape = helper.GetSubShapeByNode( nodes[i], meshDS );
432       if ( !nodeShape.IsNull() )
433         switch ( nodeShape.ShapeType() )
434         {
435         case TopAbs_FACE:   tol = BRep_Tool::Tolerance( TopoDS::Face( nodeShape )); break;
436         case TopAbs_EDGE:   tol = BRep_Tool::Tolerance( TopoDS::Edge( nodeShape )); break;
437         case TopAbs_VERTEX: tol = BRep_Tool::Tolerance( TopoDS::Vertex( nodeShape )); break;
438         default:;
439         }
440       gp_Pnt nodePnt ( nodes[i]->X(), nodes[i]->Y(), nodes[i]->Z() );
441       BRepAdaptor_Surface surface( geomFace );
442       uvOK = ( nodePnt.Distance( surface.Value( uv.X(), uv.Y() )) < 2 * tol );
443       if ( uvOK ) {
444         // normale to geomFace at UV
445         gp_Vec du, dv;
446         surface.D1( uv.X(), uv.Y(), nodePnt, du, dv );
447         geomNormal = du ^ dv;
448         if ( geomFace.Orientation() == TopAbs_REVERSED )
449           geomNormal.Reverse();
450         geomNormalOK = ( geomNormal.SquareMagnitude() > DBL_MIN * 1e3 );
451       }
452     }
453   }
454   if ( !geomNormalOK)
455     return invalidID;
456
457   // compare normals
458   bool isReverse = ( meshNormal * geomNormal ) < 0;
459   if ( !isReverse )
460     return meshDS->ShapeToIndex( solid1 );
461
462   if ( solids.Extent() == 1 )
463     return HOLE_ID; // we are inside a hole
464   else
465     return meshDS->ShapeToIndex( solids(2) );
466 }
467
468
469 //=======================================================================
470 //function : addElemInMeshGroup
471 //purpose  : Update or create groups in mesh
472 //=======================================================================
473
474 static void addElemInMeshGroup(SMESH_Mesh*             theMesh,
475                                const SMDS_MeshElement* anElem,
476                                std::string&            groupName,
477                                std::set<std::string>&  groupsToRemove)
478 {
479   if ( !anElem ) return; // issue 0021776
480
481   bool groupDone = false;
482   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
483   while (grIt->more()) {
484     SMESH_Group * group = grIt->next();
485     if ( !group ) continue;
486     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
487     if ( !groupDS ) continue;
488     if ( groupDS->GetType()==anElem->GetType() &&groupName.compare(group->GetName())==0) {
489       SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
490       aGroupDS->SMDSGroup().Add(anElem);
491       groupDone = true;
492 //       MESSAGE("Successfully added enforced element to existing group " << groupName);
493       break;
494     }
495   }
496   
497   if (!groupDone)
498   {
499     int groupId;
500     SMESH_Group* aGroup = theMesh->AddGroup(anElem->GetType(), groupName.c_str(), groupId);
501     aGroup->SetName( groupName.c_str() );
502     SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
503     aGroupDS->SMDSGroup().Add(anElem);
504 //     MESSAGE("Successfully created enforced vertex group " << groupName);
505     groupDone = true;
506   }
507   if (!groupDone)
508     throw SALOME_Exception(LOCALIZED("A given element was not added to a group"));
509 }
510
511
512 //=======================================================================
513 //function : updateMeshGroups
514 //purpose  : Update or create groups in mesh
515 //=======================================================================
516
517 static void updateMeshGroups(SMESH_Mesh* theMesh, std::set<std::string> groupsToRemove)
518 {
519   SMESH_Mesh::GroupIteratorPtr grIt = theMesh->GetGroups();
520   while (grIt->more()) {
521     SMESH_Group * group = grIt->next();
522     if ( !group ) continue;
523     SMESHDS_GroupBase* groupDS = group->GetGroupDS();
524     if ( !groupDS ) continue;
525     std::string currentGroupName = (string)group->GetName();
526     if (groupDS->IsEmpty() && groupsToRemove.find(currentGroupName) != groupsToRemove.end()) {
527       // Previous group created by enforced elements
528       MESSAGE("Delete previous group created by removed enforced elements: " << group->GetName())
529       theMesh->RemoveGroup(groupDS->GetID());
530     }
531   }
532 }
533
534 //=======================================================================
535 //function : removeEmptyGroupsOfDomains
536 //purpose  : remove empty groups named "Domain_nb" created due to
537 //           "To make groups of domains" option.
538 //=======================================================================
539
540 static void removeEmptyGroupsOfDomains(SMESH_Mesh* mesh,
541                                        bool        notEmptyAsWell = false)
542 {
543   const char* refName = theDomainGroupNamePrefix;
544   const size_t refLen = strlen( theDomainGroupNamePrefix );
545
546   std::list<int> groupIDs = mesh->GetGroupIds();
547   std::list<int>::const_iterator id = groupIDs.begin();
548   for ( ; id != groupIDs.end(); ++id )
549   {
550     SMESH_Group* group = mesh->GetGroup( *id );
551     if ( !group || ( !group->GetGroupDS()->IsEmpty() && !notEmptyAsWell ))
552       continue;
553     const char* name = group->GetName();
554     char* end;
555     // check the name
556     if ( strncmp( name, refName, refLen ) == 0 && // starts from refName;
557          isdigit( *( name + refLen )) &&          // refName is followed by a digit;
558          strtol( name + refLen, &end, 10) >= 0 && // there are only digits ...
559          *end == '\0')                            // ... till a string end.
560     {
561       mesh->RemoveGroup( *id );
562     }
563   }
564 }
565
566 //================================================================================
567 /*!
568  * \brief Create the groups corresponding to domains
569  */
570 //================================================================================
571
572 static void makeDomainGroups( std::vector< std::vector< const SMDS_MeshElement* > >& elemsOfDomain,
573                               SMESH_MesherHelper*                                    theHelper)
574 {
575   // int nbDomains = 0;
576   // for ( size_t i = 0; i < elemsOfDomain.size(); ++i )
577   //   nbDomains += ( elemsOfDomain[i].size() > 0 );
578
579   // if ( nbDomains > 1 )
580   for ( size_t iDomain = 0; iDomain < elemsOfDomain.size(); ++iDomain )
581   {
582     std::vector< const SMDS_MeshElement* > & elems = elemsOfDomain[ iDomain ];
583     if ( elems.empty() ) continue;
584
585     // find existing groups
586     std::vector< SMESH_Group* > groupOfType( SMDSAbs_NbElementTypes, (SMESH_Group*)NULL );
587     const std::string domainName = ( SMESH_Comment( theDomainGroupNamePrefix ) << iDomain );
588     SMESH_Mesh::GroupIteratorPtr groupIt = theHelper->GetMesh()->GetGroups();
589     while ( groupIt->more() )
590     {
591       SMESH_Group* group = groupIt->next();
592       if ( domainName == group->GetName() &&
593            dynamic_cast< SMESHDS_Group* >( group->GetGroupDS()) )
594         groupOfType[ group->GetGroupDS()->GetType() ] = group;
595     }
596     // create and fill the groups
597     size_t iElem = 0;
598     int groupID;
599     do
600     {
601       SMESH_Group* group = groupOfType[ elems[ iElem ]->GetType() ];
602       if ( !group )
603         group = theHelper->GetMesh()->AddGroup( elems[ iElem ]->GetType(),
604                                                 domainName.c_str(), groupID );
605       SMDS_MeshGroup& groupDS =
606         static_cast< SMESHDS_Group* >( group->GetGroupDS() )->SMDSGroup();
607
608       while ( iElem < elems.size() && groupDS.Add( elems[iElem] ))
609         ++iElem;
610
611     } while ( iElem < elems.size() );
612   }
613 }
614
615 //=======================================================================
616 //function : readGMFFile
617 //purpose  : read GMF file w/o geometry associated to mesh
618 //=======================================================================
619
620 static bool readGMFFile(const char*                     theFile,
621                         HYBRIDPlugin_HYBRID*              theAlgo,
622                         SMESH_MesherHelper*             theHelper,
623                         std::vector <const SMDS_MeshNode*> &    theNodeByHybridId,
624                         std::vector <const SMDS_MeshElement*> & theFaceByHybridId,
625                         map<const SMDS_MeshNode*,int> & theNodeToHybridIdMap,
626                         std::vector<std::string> &      aNodeGroupByHybridId,
627                         std::vector<std::string> &      anEdgeGroupByHybridId,
628                         std::vector<std::string> &      aFaceGroupByHybridId,
629                         std::set<std::string> &         groupsToRemove,
630                         bool                            toMakeGroupsOfDomains=false,
631                         bool                            toMeshHoles=true)
632 {
633   std::string tmpStr;
634   SMESHDS_Mesh* theMeshDS = theHelper->GetMeshDS();
635   const bool hasGeom = ( theHelper->GetMesh()->HasShapeToMesh() );
636
637   int nbInitialNodes = theNodeByHybridId.size();
638   int nbMeshNodes = theMeshDS->NbNodes();
639   
640   const bool isQuadMesh = 
641     theHelper->GetMesh()->NbEdges( ORDER_QUADRATIC ) ||
642     theHelper->GetMesh()->NbFaces( ORDER_QUADRATIC ) ||
643     theHelper->GetMesh()->NbVolumes( ORDER_QUADRATIC );
644     
645 #ifdef _DEBUG_
646   std::cout << "theNodeByHybridId.size(): " << nbInitialNodes << std::endl;
647   std::cout << "theHelper->GetMesh()->NbNodes(): " << nbMeshNodes << std::endl;
648   std::cout << "isQuadMesh: " << isQuadMesh << std::endl;
649 #endif
650   
651   // ---------------------------------
652   // Read generated elements and nodes
653   // ---------------------------------
654
655   int nbElem = 0, nbRef = 0;
656   int aGMFNodeID = 0;
657   const SMDS_MeshNode** GMFNode;
658 #ifdef _DEBUG_
659   std::map<int, std::set<int> > subdomainId2tetraId;
660 #endif
661   std::map <GmfKwdCod,int> tabRef;
662   const bool force3d = !hasGeom;
663   const int  noID    = 0;
664
665   tabRef[GmfVertices]       = 3; // for new nodes and enforced nodes
666   tabRef[GmfCorners]        = 1;
667   tabRef[GmfEdges]          = 2; // for enforced edges
668   tabRef[GmfRidges]         = 1;
669   tabRef[GmfTriangles]      = 3; // for enforced faces
670   tabRef[GmfQuadrilaterals] = 4;
671   tabRef[GmfTetrahedra]     = 4; // for new tetras
672   tabRef[GmfPrisms]         = 6; // for new prisms
673   tabRef[GmfHexahedra]      = 8;
674
675   int ver, dim;
676   MESSAGE("Read " << theFile << " file");
677   int InpMsh = GmfOpenMesh(theFile, GmfRead, &ver, &dim);
678   if (!InpMsh)
679     return false;
680   MESSAGE("Done ");
681
682   // Read ids of domains
683   vector< int > solidIDByDomain;
684   if ( hasGeom )
685   {
686     int solid1; // id used in case of 1 domain or some reading failure
687     if ( theHelper->GetSubShape().ShapeType() == TopAbs_SOLID )
688       solid1 = theHelper->GetSubShapeID();
689     else
690       solid1 = theMeshDS->ShapeToIndex
691         ( TopExp_Explorer( theHelper->GetSubShape(), TopAbs_SOLID ).Current() );
692
693     int nbDomains = GmfStatKwd( InpMsh, GmfSubDomainFromGeom );
694     if ( nbDomains > 1 )
695     {
696       solidIDByDomain.resize( nbDomains+1, theHelper->GetSubShapeID() );
697       int faceNbNodes, faceIndex, orientation, domainNb;
698       GmfGotoKwd( InpMsh, GmfSubDomainFromGeom );
699       for ( int i = 0; i < nbDomains; ++i )
700       {
701         faceIndex = 0;
702         GmfGetLin( InpMsh, GmfSubDomainFromGeom,
703                    &faceNbNodes, &faceIndex, &orientation, &domainNb);
704         solidIDByDomain[ domainNb ] = 1;
705         if ( 0 < faceIndex && faceIndex-1 < theFaceByHybridId.size() )
706         {
707           const SMDS_MeshElement* face = theFaceByHybridId[ faceIndex-1 ];
708           const SMDS_MeshNode* nn[3] = { face->GetNode(0),
709                                          face->GetNode(1),
710                                          face->GetNode(2) };
711           if ( orientation < 0 )
712             std::swap( nn[1], nn[2] );
713           solidIDByDomain[ domainNb ] =
714             findShapeID( *theHelper->GetMesh(), nn[0], nn[1], nn[2], toMeshHoles );
715           if ( solidIDByDomain[ domainNb ] > 0 )
716           {
717             const TopoDS_Shape& foundShape = theMeshDS->IndexToShape( solidIDByDomain[ domainNb ] );
718             if ( ! theHelper->IsSubShape( foundShape, theHelper->GetSubShape() ))
719               solidIDByDomain[ domainNb ] = HOLE_ID;
720           }
721         }
722       }
723     }
724     if ( solidIDByDomain.size() < 2 )
725       solidIDByDomain.resize( 2, solid1 );
726   }
727
728   // Issue 0020682. Avoid creating nodes and tetras at place where
729   // volumic elements already exist
730   SMESH_ElementSearcher* elemSearcher = 0;
731   std::vector< const SMDS_MeshElement* > foundVolumes;
732   if ( !hasGeom && theHelper->GetMesh()->NbVolumes() > 0 )
733     elemSearcher = SMESH_MeshAlgos::GetElementSearcher( *theMeshDS );
734   auto_ptr< SMESH_ElementSearcher > elemSearcherDeleter( elemSearcher );
735
736   // IMP 0022172: [CEA 790] create the groups corresponding to domains
737   std::vector< std::vector< const SMDS_MeshElement* > > elemsOfDomain;
738
739   int nbVertices = GmfStatKwd(InpMsh, GmfVertices) - nbInitialNodes;
740   GMFNode = new const SMDS_MeshNode*[ nbVertices + 1 ];
741
742   std::map <GmfKwdCod,int>::const_iterator it = tabRef.begin();
743   for ( ; it != tabRef.end() ; ++it)
744   {
745     if(theAlgo->computeCanceled()) {
746       GmfCloseMesh(InpMsh);
747       delete [] GMFNode;
748       return false;
749     }
750     int dummy, solidID;
751     GmfKwdCod token = it->first;
752     nbRef           = it->second;
753
754     nbElem = GmfStatKwd(InpMsh, token);
755     if (nbElem > 0) {
756       GmfGotoKwd(InpMsh, token);
757       std::cout << "Read " << nbElem;
758     }
759     else
760       continue;
761
762     std::vector<int> id (nbElem*tabRef[token]); // node ids
763     std::vector<int> domainID( nbElem ); // domain
764
765     if (token == GmfVertices) {
766       (nbElem <= 1) ? tmpStr = " vertex" : tmpStr = " vertices";
767 //       std::cout << nbInitialNodes << " from input mesh " << std::endl;
768
769       // Remove orphan nodes from previous enforced mesh which was cleared
770 //       if ( nbElem < nbMeshNodes ) {
771 //         const SMDS_MeshNode* node;
772 //         SMDS_NodeIteratorPtr nodeIt = theMeshDS->nodesIterator();
773 //         while ( nodeIt->more() )
774 //         {
775 //           node = nodeIt->next();
776 //           if (theNodeToHybridIdMap.find(node) != theNodeToHybridIdMap.end())
777 //             theMeshDS->RemoveNode(node);
778 //         }
779 //       }
780
781       
782       int aGMFID;
783
784       float VerTab_f[3];
785       double x, y, z;
786       const SMDS_MeshNode * aGMFNode;
787
788       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
789         if(theAlgo->computeCanceled()) {
790           GmfCloseMesh(InpMsh);
791           delete [] GMFNode;
792           return false;
793         }
794         if (ver == GmfFloat) {
795           GmfGetLin(InpMsh, token, &VerTab_f[0], &VerTab_f[1], &VerTab_f[2], &dummy);
796           x = VerTab_f[0];
797           y = VerTab_f[1];
798           z = VerTab_f[2];
799         }
800         else {
801           GmfGetLin(InpMsh, token, &x, &y, &z, &dummy);
802         }
803         if (iElem >= nbInitialNodes) {
804           if ( elemSearcher &&
805                 elemSearcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_Volume, foundVolumes))
806             aGMFNode = 0;
807           else
808             aGMFNode = theHelper->AddNode(x, y, z);
809           
810           aGMFID = iElem -nbInitialNodes +1;
811           GMFNode[ aGMFID ] = aGMFNode;
812           if (aGMFID-1 < aNodeGroupByHybridId.size() && !aNodeGroupByHybridId.at(aGMFID-1).empty())
813             addElemInMeshGroup(theHelper->GetMesh(), aGMFNode, aNodeGroupByHybridId.at(aGMFID-1), groupsToRemove);
814         }
815       }
816     }
817     else if (token == GmfCorners && nbElem > 0) {
818       (nbElem <= 1) ? tmpStr = " corner" : tmpStr = " corners";
819       for ( int iElem = 0; iElem < nbElem; iElem++ )
820         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
821     }
822     else if (token == GmfRidges && nbElem > 0) {
823       (nbElem <= 1) ? tmpStr = " ridge" : tmpStr = " ridges";
824       for ( int iElem = 0; iElem < nbElem; iElem++ )
825         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]]);
826     }
827     else if (token == GmfEdges && nbElem > 0) {
828       (nbElem <= 1) ? tmpStr = " edge" : tmpStr = " edges";
829       for ( int iElem = 0; iElem < nbElem; iElem++ )
830         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &domainID[iElem]);
831     }
832     else if (token == GmfTriangles && nbElem > 0) {
833       (nbElem <= 1) ? tmpStr = " triangle" : tmpStr = " triangles";
834       for ( int iElem = 0; iElem < nbElem; iElem++ )
835         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &domainID[iElem]);
836     }
837     else if (token == GmfQuadrilaterals && nbElem > 0) {
838       (nbElem <= 1) ? tmpStr = " Quadrilateral" : tmpStr = " Quadrilaterals";
839       for ( int iElem = 0; iElem < nbElem; iElem++ )
840         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
841     }
842     else if (token == GmfTetrahedra && nbElem > 0) {
843       (nbElem <= 1) ? tmpStr = " Tetrahedron" : tmpStr = " Tetrahedra";
844       for ( int iElem = 0; iElem < nbElem; iElem++ ) {
845         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3], &domainID[iElem]);
846 #ifdef _DEBUG_
847         subdomainId2tetraId[dummy].insert(iElem+1);
848 //         MESSAGE("subdomainId2tetraId["<<dummy<<"].insert("<<iElem+1<<")");
849 #endif
850       }
851     }
852     else if (token == GmfPrisms && nbElem > 0) {
853       (nbElem <= 1) ? tmpStr = " Prism" : tmpStr = " Prisms";
854       for ( int iElem = 0; iElem < nbElem; iElem++ )
855         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
856                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &domainID[iElem]);
857     }
858     else if (token == GmfHexahedra && nbElem > 0) {
859       (nbElem <= 1) ? tmpStr = " Hexahedron" : tmpStr = " Hexahedra";
860       for ( int iElem = 0; iElem < nbElem; iElem++ )
861         GmfGetLin(InpMsh, token, &id[iElem*tabRef[token]], &id[iElem*tabRef[token]+1], &id[iElem*tabRef[token]+2], &id[iElem*tabRef[token]+3],
862                   &id[iElem*tabRef[token]+4], &id[iElem*tabRef[token]+5], &id[iElem*tabRef[token]+6], &id[iElem*tabRef[token]+7], &domainID[iElem]);
863     }
864     std::cout << tmpStr << std::endl;
865     //std::cout << std::endl;
866
867     switch (token) {
868     case GmfCorners:
869     case GmfRidges:
870     case GmfEdges:
871     case GmfTriangles:
872     case GmfQuadrilaterals:
873     case GmfTetrahedra:
874     case GmfPrisms:
875     case GmfHexahedra:
876     {
877       std::vector< const SMDS_MeshNode* > node( nbRef );
878       std::vector< int >          nodeID( nbRef );
879       std::vector< SMDS_MeshNode* > enfNode( nbRef );
880       const SMDS_MeshElement* aCreatedElem;
881
882       for ( int iElem = 0; iElem < nbElem; iElem++ )
883       {
884         if(theAlgo->computeCanceled()) {
885           GmfCloseMesh(InpMsh);
886           delete [] GMFNode;
887           return false;
888         }
889         // Check if elem is already in input mesh. If yes => skip
890         bool fullyCreatedElement = false; // if at least one of the nodes was created
891         for ( int iRef = 0; iRef < nbRef; iRef++ )
892         {
893           aGMFNodeID = id[iElem*tabRef[token]+iRef]; // read nbRef aGMFNodeID
894           if (aGMFNodeID <= nbInitialNodes) // input nodes
895           {
896             aGMFNodeID--;
897             node[ iRef ] = theNodeByHybridId[aGMFNodeID];
898           }
899           else
900           {
901             fullyCreatedElement = true;
902             aGMFNodeID -= nbInitialNodes;
903             nodeID[ iRef ] = aGMFNodeID ;
904             node  [ iRef ] = GMFNode[ aGMFNodeID ];
905           }
906         }
907         aCreatedElem = 0;
908         switch (token)
909         {
910         case GmfEdges:
911           if (fullyCreatedElement) {
912             aCreatedElem = theHelper->AddEdge( node[0], node[1], noID, force3d );
913             if (anEdgeGroupByHybridId.size() && !anEdgeGroupByHybridId[iElem].empty())
914               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, anEdgeGroupByHybridId[iElem], groupsToRemove);
915           }
916           break;
917         case GmfTriangles:
918           if (fullyCreatedElement) {
919             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], noID, force3d );
920             if (aFaceGroupByHybridId.size() && !aFaceGroupByHybridId[iElem].empty())
921               addElemInMeshGroup(theHelper->GetMesh(), aCreatedElem, aFaceGroupByHybridId[iElem], groupsToRemove);
922           }
923           break;
924         case GmfQuadrilaterals:
925           if (fullyCreatedElement) {
926             aCreatedElem = theHelper->AddFace( node[0], node[1], node[2], node[3], noID, force3d );
927           }
928           break;
929         case GmfTetrahedra:
930           if ( hasGeom )
931           {
932             solidID = solidIDByDomain[ domainID[iElem]];
933             if ( solidID != HOLE_ID )
934             {
935               aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
936                                                    noID, force3d );
937               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
938               for ( int iN = 0; iN < 4; ++iN )
939                 if ( node[iN]->getshapeId() < 1 )
940                   theMeshDS->SetNodeInVolume( node[iN], solidID );
941             }
942           }
943           else
944           {
945             if ( elemSearcher ) {
946               // Issue 0020682. Avoid creating nodes and tetras at place where
947               // volumic elements already exist
948               if ( !node[1] || !node[0] || !node[2] || !node[3] )
949                 continue;
950               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
951                                                       SMESH_TNodeXYZ(node[1]) +
952                                                       SMESH_TNodeXYZ(node[2]) +
953                                                       SMESH_TNodeXYZ(node[3]) ) / 4.,
954                                                      SMDSAbs_Volume, foundVolumes ))
955                 break;
956             }
957             aCreatedElem = theHelper->AddVolume( node[1], node[0], node[2], node[3],
958                                                  noID, force3d );
959           }
960           break;
961         case GmfPrisms:
962           if ( hasGeom )
963           {
964             solidID = solidIDByDomain[ domainID[iElem]];
965             if ( solidID != HOLE_ID )
966             {
967               aCreatedElem = theHelper->AddVolume( node[0], node[2], node[1],
968                                                    node[3], node[5], node[4],
969                                                    noID, force3d );
970               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
971               for ( int iN = 0; iN < 6; ++iN )
972                 if ( node[iN]->getshapeId() < 1 )
973                   theMeshDS->SetNodeInVolume( node[iN], solidID );
974             }
975           }
976           else
977           {
978             if ( elemSearcher ) {
979               // Issue 0020682. Avoid creating nodes and tetras at place where
980               // volumic elements already exist
981               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] )
982                 continue;
983               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
984                                                       SMESH_TNodeXYZ(node[1]) +
985                                                       SMESH_TNodeXYZ(node[2]) +
986                                                       SMESH_TNodeXYZ(node[3]) +
987                                                       SMESH_TNodeXYZ(node[4]) +
988                                                       SMESH_TNodeXYZ(node[5])) / 6.,
989                                                      SMDSAbs_Volume, foundVolumes ))
990                 break;
991             }
992             aCreatedElem = theHelper->AddVolume( node[0], node[2], node[1],
993                                                  node[3], node[5], node[4],
994                                                  noID, force3d );
995           }
996           break;
997         case GmfHexahedra:
998           if ( hasGeom )
999           {
1000             solidID = solidIDByDomain[ domainID[iElem]];
1001             if ( solidID != HOLE_ID )
1002             {
1003               aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
1004                                                    node[4], node[7], node[6], node[5],
1005                                                    noID, force3d );
1006               theMeshDS->SetMeshElementOnShape( aCreatedElem, solidID );
1007               for ( int iN = 0; iN < 8; ++iN )
1008                 if ( node[iN]->getshapeId() < 1 )
1009                   theMeshDS->SetNodeInVolume( node[iN], solidID );
1010             }
1011           }
1012           else
1013           {
1014             if ( elemSearcher ) {
1015               // Issue 0020682. Avoid creating nodes and tetras at place where
1016               // volumic elements already exist
1017               if ( !node[1] || !node[0] || !node[2] || !node[3] || !node[4] || !node[5] || !node[6] || !node[7])
1018                 continue;
1019               if ( elemSearcher->FindElementsByPoint((SMESH_TNodeXYZ(node[0]) +
1020                                                       SMESH_TNodeXYZ(node[1]) +
1021                                                       SMESH_TNodeXYZ(node[2]) +
1022                                                       SMESH_TNodeXYZ(node[3]) +
1023                                                       SMESH_TNodeXYZ(node[4]) +
1024                                                       SMESH_TNodeXYZ(node[5]) +
1025                                                       SMESH_TNodeXYZ(node[6]) +
1026                                                       SMESH_TNodeXYZ(node[7])) / 8.,
1027                                                      SMDSAbs_Volume, foundVolumes ))
1028                 break;
1029             }
1030             aCreatedElem = theHelper->AddVolume( node[0], node[3], node[2], node[1],
1031                                                  node[4], node[7], node[6], node[5],
1032                                                  noID, force3d );
1033           }
1034           break;
1035         default: continue;
1036         } // switch (token)
1037
1038         if ( aCreatedElem && toMakeGroupsOfDomains )
1039         {
1040           if ( domainID[iElem] >= (int) elemsOfDomain.size() )
1041             elemsOfDomain.resize( domainID[iElem] + 1 );
1042           elemsOfDomain[ domainID[iElem] ].push_back( aCreatedElem );
1043         }
1044       } // loop on elements of one type
1045       break;
1046     } // case ...
1047     } // switch (token)
1048   } // loop on tabRef
1049
1050   // remove nodes in holes
1051   if ( hasGeom )
1052   {
1053     for ( int i = 1; i <= nbVertices; ++i )
1054       if ( GMFNode[i]->NbInverseElements() == 0 )
1055         theMeshDS->RemoveFreeNode( GMFNode[i], /*sm=*/0, /*fromGroups=*/false );
1056   }
1057
1058   GmfCloseMesh(InpMsh);
1059   delete [] GMFNode;
1060
1061   // 0022172: [CEA 790] create the groups corresponding to domains
1062   if ( toMakeGroupsOfDomains )
1063     makeDomainGroups( elemsOfDomain, theHelper );
1064
1065 #ifdef _DEBUG_
1066   MESSAGE("Nb subdomains " << subdomainId2tetraId.size());
1067   std::map<int, std::set<int> >::const_iterator subdomainIt = subdomainId2tetraId.begin();
1068   TCollection_AsciiString aSubdomainFileName = theFile;
1069   aSubdomainFileName = aSubdomainFileName + ".subdomain";
1070   ofstream aSubdomainFile  ( aSubdomainFileName.ToCString()  , ios::out);
1071
1072   aSubdomainFile << "Nb subdomains " << subdomainId2tetraId.size() << std::endl;
1073   for(;subdomainIt != subdomainId2tetraId.end() ; ++subdomainIt) {
1074     int subdomainId = subdomainIt->first;
1075     std::set<int> tetraIds = subdomainIt->second;
1076     MESSAGE("Subdomain #"<<subdomainId<<": "<<tetraIds.size()<<" tetrahedrons");
1077     std::set<int>::const_iterator tetraIdsIt = tetraIds.begin();
1078     aSubdomainFile << subdomainId << std::endl;
1079     for(;tetraIdsIt != tetraIds.end() ; ++tetraIdsIt) {
1080       aSubdomainFile << (*tetraIdsIt) << " ";
1081     }
1082     aSubdomainFile << std::endl;
1083   }
1084   aSubdomainFile.close();
1085 #endif  
1086   
1087   return true;
1088 }
1089
1090
1091 static bool writeGMFFile(const char*                                     theMeshFileName,
1092                          const char*                                     theRequiredFileName,
1093                          const char*                                     theSolFileName,
1094                          const SMESH_ProxyMesh&                          theProxyMesh,
1095                          SMESH_MesherHelper&                             theHelper,
1096                          std::vector <const SMDS_MeshNode*> &            theNodeByHybridId,
1097                          std::vector <const SMDS_MeshElement*> &         theFaceByHybridId,
1098                          std::map<const SMDS_MeshNode*,int> &            aNodeToHybridIdMap,
1099                          std::vector<std::string> &                      aNodeGroupByHybridId,
1100                          std::vector<std::string> &                      anEdgeGroupByHybridId,
1101                          std::vector<std::string> &                      aFaceGroupByHybridId,
1102                          HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap & theEnforcedNodes,
1103                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedEdges,
1104                          HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap & theEnforcedTriangles,
1105                          std::map<std::vector<double>, std::string> &    enfVerticesWithGroup,
1106                          HYBRIDPlugin_Hypothesis::THYBRIDEnforcedVertexCoordsValues & theEnforcedVertices)
1107 {
1108   //MESSAGE("writeGMFFile w/o geometry");
1109   std::cout << "!!!!!!!!!!!writeGMFFile w/o geometry 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   map<const SMDS_MeshNode*,int> anEnforcedNodeToHybridIdMap, anExistingEnforcedNodeToHybridIdMap;
1127   std::vector< const SMDS_MeshElement* > foundElems;
1128   map<const SMDS_MeshNode*,TopAbs_State> aNodeToTopAbs_StateMap;
1129   int nbFoundElems;
1130   HYBRIDPlugin_Hypothesis::TIDSortedElemGroupMap::iterator elemIt;
1131   TIDSortedElemSet::iterator elemSetIt;
1132   bool isOK;
1133   SMESH_Mesh* theMesh = theHelper.GetMesh();
1134   const bool hasGeom = theMesh->HasShapeToMesh();
1135   auto_ptr< SMESH_ElementSearcher > pntCls
1136     ( SMESH_MeshAlgos::GetElementSearcher(*theMesh->GetMeshDS()));
1137   
1138   int nbEnforcedVertices = theEnforcedVertices.size();
1139   
1140   // count faces
1141   int nbFaces = theProxyMesh.NbFaces();
1142   int nbNodes;
1143   theFaceByHybridId.reserve( nbFaces );
1144   
1145   // groups management
1146   int usedEnforcedNodes = 0;
1147   std::string gn = "";
1148
1149   if ( nbFaces == 0 )
1150     return false;
1151   
1152   idx = GmfOpenMesh(theMeshFileName, GmfWrite, GMFVERSION, GMFDIMENSION);
1153   if (!idx)
1154     return false;
1155   
1156   // ========================== FACES ==========================
1157   // TRIANGLES ==========================
1158   SMDS_ElemIteratorPtr eIt =
1159     hasGeom ? theProxyMesh.GetFaces( theHelper.GetSubShape()) : theProxyMesh.GetFaces();
1160   while ( eIt->more() )
1161   {
1162     elem = eIt->next();
1163     anElemSet.insert(elem);
1164     nodeIt = elem->nodesIterator();
1165     nbNodes = elem->NbCornerNodes();
1166     while ( nodeIt->more() && nbNodes--)
1167     {
1168       // find HYBRID ID
1169       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1170       int newId = aNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
1171       aNodeToHybridIdMap.insert( make_pair( node, newId ));
1172     }
1173   }
1174   
1175   //EDGES ==========================
1176   
1177   // Iterate over the enforced edges
1178   for(elemIt = theEnforcedEdges.begin() ; elemIt != theEnforcedEdges.end() ; ++elemIt) {
1179     elem = elemIt->first;
1180     isOK = true;
1181     nodeIt = elem->nodesIterator();
1182     nbNodes = 2;
1183     while ( nodeIt->more() && nbNodes-- ) {
1184       // find HYBRID ID
1185       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1186       // Test if point is inside shape to mesh
1187       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1188       TopAbs_State result = pntCls->GetPointState( myPoint );
1189       if ( result == TopAbs_OUT ) {
1190         isOK = false;
1191         break;
1192       }
1193       aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1194     }
1195     if (isOK) {
1196       nodeIt = elem->nodesIterator();
1197       nbNodes = 2;
1198       int newId = -1;
1199       while ( nodeIt->more() && nbNodes-- ) {
1200         // find HYBRID ID
1201         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1202         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1203         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1204 #ifdef _DEBUG_
1205         std::cout << "Node at "<<node->X()<<", "<<node->Y()<<", "<<node->Z()<<std::endl;
1206         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1207 #endif
1208         if (nbFoundElems ==0) {
1209           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1210             newId = aNodeToHybridIdMap.size() + anEnforcedNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
1211             anEnforcedNodeToHybridIdMap.insert( make_pair( node, newId ));
1212           }
1213         }
1214         else if (nbFoundElems ==1) {
1215           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1216           newId = (*aNodeToHybridIdMap.find(existingNode)).second;
1217           anExistingEnforcedNodeToHybridIdMap.insert( make_pair( node, newId ));
1218         }
1219         else
1220           isOK = false;
1221 #ifdef _DEBUG_
1222         std::cout << "HYBRID node ID: "<<newId<<std::endl;
1223 #endif
1224       }
1225       if (isOK)
1226         theKeptEnforcedEdges.insert(elem);
1227     }
1228   }
1229   
1230   //ENFORCED TRIANGLES ==========================
1231   
1232   // Iterate over the enforced triangles
1233   for(elemIt = theEnforcedTriangles.begin() ; elemIt != theEnforcedTriangles.end() ; ++elemIt) {
1234     elem = elemIt->first;
1235     isOK = true;
1236     nodeIt = elem->nodesIterator();
1237     nbNodes = 3;
1238     while ( nodeIt->more() && nbNodes--) {
1239       // find HYBRID ID
1240       const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1241       // Test if point is inside shape to mesh
1242       gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1243       TopAbs_State result = pntCls->GetPointState( myPoint );
1244       if ( result == TopAbs_OUT ) {
1245         isOK = false;
1246         break;
1247       }
1248       aNodeToTopAbs_StateMap.insert( make_pair( node, result ));
1249     }
1250     if (isOK) {
1251       nodeIt = elem->nodesIterator();
1252       nbNodes = 3;
1253       int newId = -1;
1254       while ( nodeIt->more() && nbNodes--) {
1255         // find HYBRID ID
1256         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1257         gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1258         nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1259 #ifdef _DEBUG_
1260         std::cout << "Nb nodes found : "<<nbFoundElems<<std::endl;
1261 #endif
1262         if (nbFoundElems ==0) {
1263           if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1264             newId = aNodeToHybridIdMap.size() + anEnforcedNodeToHybridIdMap.size() + 1; // hybrid ids count from 1
1265             anEnforcedNodeToHybridIdMap.insert( make_pair( node, newId ));
1266           }
1267         }
1268         else if (nbFoundElems ==1) {
1269           const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1270           newId = (*aNodeToHybridIdMap.find(existingNode)).second;
1271           anExistingEnforcedNodeToHybridIdMap.insert( make_pair( node, newId ));
1272         }
1273         else
1274           isOK = false;
1275 #ifdef _DEBUG_
1276         std::cout << "HYBRID node ID: "<<newId<<std::endl;
1277 #endif
1278       }
1279       if (isOK)
1280         theKeptEnforcedTriangles.insert(elem);
1281     }
1282   }
1283   
1284   // put nodes to theNodeByHybridId vector
1285 #ifdef _DEBUG_
1286   std::cout << "aNodeToHybridIdMap.size(): "<<aNodeToHybridIdMap.size()<<std::endl;
1287 #endif
1288   theNodeByHybridId.resize( aNodeToHybridIdMap.size() );
1289   map<const SMDS_MeshNode*,int>::const_iterator n2id = aNodeToHybridIdMap.begin();
1290   for ( ; n2id != aNodeToHybridIdMap.end(); ++ n2id)
1291   {
1292 //     std::cout << "n2id->first: "<<n2id->first<<std::endl;
1293     theNodeByHybridId[ n2id->second - 1 ] = n2id->first; // hybrid ids count from 1
1294   }
1295
1296   // put nodes to anEnforcedNodeToHybridIdMap vector
1297 #ifdef _DEBUG_
1298   std::cout << "anEnforcedNodeToHybridIdMap.size(): "<<anEnforcedNodeToHybridIdMap.size()<<std::endl;
1299 #endif
1300   theEnforcedNodeByHybridId.resize( anEnforcedNodeToHybridIdMap.size());
1301   n2id = anEnforcedNodeToHybridIdMap.begin();
1302   for ( ; n2id != anEnforcedNodeToHybridIdMap.end(); ++ n2id)
1303   {
1304     if (n2id->second > aNodeToHybridIdMap.size()) {
1305       theEnforcedNodeByHybridId[ n2id->second - aNodeToHybridIdMap.size() - 1 ] = n2id->first; // hybrid ids count from 1
1306     }
1307   }
1308   
1309   
1310   //========================== NODES ==========================
1311   vector<const SMDS_MeshNode*> theOrderedNodes, theRequiredNodes;
1312   std::set< std::vector<double> > nodesCoords;
1313   vector<const SMDS_MeshNode*>::const_iterator hybridNodeIt = theNodeByHybridId.begin();
1314   vector<const SMDS_MeshNode*>::const_iterator after  = theNodeByHybridId.end();
1315   
1316   (theNodeByHybridId.size() <= 1) ? tmpStr = " node" : " nodes";
1317   std::cout << theNodeByHybridId.size() << tmpStr << " from mesh ..." << std::endl;
1318   for ( ; hybridNodeIt != after; ++hybridNodeIt )
1319   {
1320     const SMDS_MeshNode* node = *hybridNodeIt;
1321     std::vector<double> coords;
1322     coords.push_back(node->X());
1323     coords.push_back(node->Y());
1324     coords.push_back(node->Z());
1325     nodesCoords.insert(coords);
1326     theOrderedNodes.push_back(node);
1327   }
1328   
1329   // Iterate over the enforced nodes given by enforced elements
1330   hybridNodeIt = theEnforcedNodeByHybridId.begin();
1331   after  = theEnforcedNodeByHybridId.end();
1332   (theEnforcedNodeByHybridId.size() <= 1) ? tmpStr = " node" : " nodes";
1333   std::cout << theEnforcedNodeByHybridId.size() << tmpStr << " from enforced elements ..." << std::endl;
1334   for ( ; hybridNodeIt != after; ++hybridNodeIt )
1335   {
1336     const SMDS_MeshNode* node = *hybridNodeIt;
1337     std::vector<double> coords;
1338     coords.push_back(node->X());
1339     coords.push_back(node->Y());
1340     coords.push_back(node->Z());
1341 #ifdef _DEBUG_
1342     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1343 #endif
1344     
1345     if (nodesCoords.find(coords) != nodesCoords.end()) {
1346       // node already exists in original mesh
1347 #ifdef _DEBUG_
1348       std::cout << " found" << std::endl;
1349 #endif
1350       continue;
1351     }
1352     
1353     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1354       // node already exists in enforced vertices
1355 #ifdef _DEBUG_
1356       std::cout << " found" << std::endl;
1357 #endif
1358       continue;
1359     }
1360     
1361 //     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1362 //     nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1363 //     if (nbFoundElems ==0) {
1364 //       std::cout << " not found" << std::endl;
1365 //       if ((*aNodeToTopAbs_StateMap.find(node)).second == TopAbs_IN) {
1366 //         nodesCoords.insert(coords);
1367 //         theOrderedNodes.push_back(node);
1368 //       }
1369 //     }
1370 //     else {
1371 //       std::cout << " found in initial mesh" << std::endl;
1372 //       const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1373 //       nodesCoords.insert(coords);
1374 //       theOrderedNodes.push_back(existingNode);
1375 //     }
1376     
1377 #ifdef _DEBUG_
1378     std::cout << " not found" << std::endl;
1379 #endif
1380     
1381     nodesCoords.insert(coords);
1382     theOrderedNodes.push_back(node);
1383 //     theRequiredNodes.push_back(node);
1384   }
1385   
1386   
1387   // Iterate over the enforced nodes
1388   HYBRIDPlugin_Hypothesis::TIDSortedNodeGroupMap::const_iterator enfNodeIt;
1389   (theEnforcedNodes.size() <= 1) ? tmpStr = " node" : " nodes";
1390   std::cout << theEnforcedNodes.size() << tmpStr << " from enforced nodes ..." << std::endl;
1391   for(enfNodeIt = theEnforcedNodes.begin() ; enfNodeIt != theEnforcedNodes.end() ; ++enfNodeIt)
1392   {
1393     const SMDS_MeshNode* node = enfNodeIt->first;
1394     std::vector<double> coords;
1395     coords.push_back(node->X());
1396     coords.push_back(node->Y());
1397     coords.push_back(node->Z());
1398 #ifdef _DEBUG_
1399     std::cout << "Node at " << node->X()<<", " <<node->Y()<<", " <<node->Z();
1400 #endif
1401     
1402     // Test if point is inside shape to mesh
1403     gp_Pnt myPoint(node->X(),node->Y(),node->Z());
1404     TopAbs_State result = pntCls->GetPointState( myPoint );
1405     if ( result == TopAbs_OUT ) {
1406 #ifdef _DEBUG_
1407       std::cout << " out of volume" << std::endl;
1408 #endif
1409       continue;
1410     }
1411     
1412     if (nodesCoords.find(coords) != nodesCoords.end()) {
1413 #ifdef _DEBUG_
1414       std::cout << " found in nodesCoords" << std::endl;
1415 #endif
1416 //       theRequiredNodes.push_back(node);
1417       continue;
1418     }
1419
1420     if (theEnforcedVertices.find(coords) != theEnforcedVertices.end()) {
1421 #ifdef _DEBUG_
1422       std::cout << " found in theEnforcedVertices" << std::endl;
1423 #endif
1424       continue;
1425     }
1426     
1427 //     nbFoundElems = pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems);
1428 //     if (nbFoundElems ==0) {
1429 //       std::cout << " not found" << std::endl;
1430 //       if (result == TopAbs_IN) {
1431 //         nodesCoords.insert(coords);
1432 //         theRequiredNodes.push_back(node);
1433 //       }
1434 //     }
1435 //     else {
1436 //       std::cout << " found in initial mesh" << std::endl;
1437 //       const SMDS_MeshNode* existingNode = (SMDS_MeshNode*) foundElems.at(0);
1438 // //       nodesCoords.insert(coords);
1439 //       theRequiredNodes.push_back(existingNode);
1440 //     }
1441 //     
1442 //     
1443 //     
1444 //     if (pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems) == 0)
1445 //       continue;
1446
1447 //     if ( result != TopAbs_IN )
1448 //       continue;
1449     
1450 #ifdef _DEBUG_
1451     std::cout << " not found" << std::endl;
1452 #endif
1453     nodesCoords.insert(coords);
1454 //     theOrderedNodes.push_back(node);
1455     theRequiredNodes.push_back(node);
1456   }
1457   int requiredNodes = theRequiredNodes.size();
1458   
1459   int solSize = 0;
1460   std::vector<std::vector<double> > ReqVerTab;
1461   if (nbEnforcedVertices) {
1462 //    ReqVerTab.clear();
1463     (nbEnforcedVertices <= 1) ? tmpStr = " node" : " nodes";
1464     std::cout << nbEnforcedVertices << tmpStr << " from enforced vertices ..." << std::endl;
1465     // Iterate over the enforced vertices
1466     for(vertexIt = theEnforcedVertices.begin() ; vertexIt != theEnforcedVertices.end() ; ++vertexIt) {
1467       double x = vertexIt->first[0];
1468       double y = vertexIt->first[1];
1469       double z = vertexIt->first[2];
1470       // Test if point is inside shape to mesh
1471       gp_Pnt myPoint(x,y,z);
1472       TopAbs_State result = pntCls->GetPointState( myPoint );
1473       if ( result == TopAbs_OUT )
1474         continue;
1475       //if (pntCls->FindElementsByPoint(myPoint, SMDSAbs_Node, foundElems) == 0)
1476       //continue;
1477
1478 //       if ( result != TopAbs_IN )
1479 //         continue;
1480       std::vector<double> coords;
1481       coords.push_back(x);
1482       coords.push_back(y);
1483       coords.push_back(z);
1484       ReqVerTab.push_back(coords);
1485       enfVertexSizes.push_back(vertexIt->second);
1486       solSize++;
1487     }
1488   }
1489   
1490   
1491   // GmfVertices
1492   std::cout << "Begin 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         map< const SMDS_MeshNode*,int >::iterator it = anEnforcedNodeToHybridIdMap.find(node);
1567         if (it == anEnforcedNodeToHybridIdMap.end()) {
1568           it = anExistingEnforcedNodeToHybridIdMap.find(node);
1569           if (it == anEnforcedNodeToHybridIdMap.end())
1570             throw "Node not found";
1571         }
1572         nedge[index] = it->second;
1573         index++;
1574       }
1575       GmfSetLin(idx, GmfEdges, nedge[0], nedge[1], dummyint4);
1576       anEdgeGroupByHybridId[usedEnforcedEdges] = theEnforcedEdges.find(elem)->second;
1577 //      GmfSetLin(idxRequired, GmfEdges, nedge[0], nedge[1], dummyint);
1578       usedEnforcedEdges++;
1579     }
1580 //    GmfCloseMesh(idxRequired);
1581   }
1582
1583
1584   if (usedEnforcedEdges) {
1585     GmfSetKwd(idx, GmfRequiredEdges, usedEnforcedEdges);
1586     for (int enfID=1;enfID<=usedEnforcedEdges;enfID++) {
1587       GmfSetLin(idx, GmfRequiredEdges, enfID);
1588     }
1589   }
1590
1591   // GmfTriangles
1592   int usedEnforcedTriangles = 0;
1593   if (anElemSet.size()+theKeptEnforcedTriangles.size()) {
1594     aFaceGroupByHybridId.resize( anElemSet.size()+theKeptEnforcedTriangles.size() );
1595     GmfSetKwd(idx, GmfTriangles, anElemSet.size()+theKeptEnforcedTriangles.size());
1596     int k=0;
1597     for(elemSetIt = anElemSet.begin() ; elemSetIt != anElemSet.end() ; ++elemSetIt,++k) {
1598       elem = (*elemSetIt);
1599       theFaceByHybridId.push_back( elem );
1600       nodeIt = elem->nodesIterator();
1601       int index=0;
1602       for ( int j = 0; j < 3; ++j ) {
1603         // find HYBRID ID
1604         const SMDS_MeshNode* node = castToNode( nodeIt->next() );
1605         map< const SMDS_MeshNode*,int >::iterator it = aNodeToHybridIdMap.find(node);
1606         if (it == aNodeToHybridIdMap.end())
1607           throw "Node not found";
1608         ntri[index] = it->second;
1609         index++;
1610       }
1611       GmfSetLin(idx, GmfTriangles, ntri[0], ntri[1], ntri[2], dummyint5);
1612       aFaceGroupByHybridId[k] = "";
1613     }
1614     
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           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( 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( make_pair( node->GetID(), aHybridID ));
1757 //     theHybridIdToNodeMap.insert( 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( 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( 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( 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 map <int,int> &   theSmdsToHybridIdMap,
2107                         const 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   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                          map <int,int> &                  theSmdsToHybridIdMap,
2305                          map <int,int> &                  theEnforcedNodeIdToHybridIdMap,
2306                          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     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( 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( make_pair( node->GetID(), aHybridID ));
2410     theHybridIdToNodeMap.insert( 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( 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( 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                            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   map <int,const SMDS_MeshNode*>::iterator itOnNode;
2555   SMDS_MeshElement* aTet;
2556 #ifdef _DEBUG_
2557   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(), 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   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 ( 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(make_pair(enfVertex->coords,enfVertex->size));
2954       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
2955 //       MESSAGE("enfVerticesWithGroup.insert(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(make_pair(coords,enfVertex->size));
2971 //           enfVerticesWithGroup.insert(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(make_pair(coords,enfVertex->size));
2987               enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
2988 //               MESSAGE("enfVerticesWithGroup.insert(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       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   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(make_pair(enfVertex->coords,enfVertex->size));
3260       enfVerticesWithGroup.insert(make_pair(enfVertex->coords,enfVertex->groupName));
3261 //       MESSAGE("enfVerticesWithGroup.insert(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(make_pair(coords,enfVertex->size));
3277 //           enfVerticesWithGroup.insert(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(make_pair(coords,enfVertex->size));
3293               enfVerticesWithGroup.insert(make_pair(coords,enfVertex->groupName));
3294 //               MESSAGE("enfVerticesWithGroup.insert(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(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, 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   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   set<string> foundErrorStr; // to avoid reporting same error several times
3542   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     list<const SMDS_MeshElement*> badElems;
3549     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         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         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         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( 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       list<const SMDS_MeshElement*>::iterator elem = badElems.begin();
3725       for ( ; elem != badElems.end(); ++elem )
3726         addBadInputElement( *elem );
3727       //}
3728
3729     // make error text
3730     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 ( search( &buf[0], bufEnd, msgLic1, msgLic1 + strlen(msgLic1)) != bufEnd ||
3743          search( &buf[0], bufEnd, msgLic2, msgLic2 + strlen(msgLic2)) != bufEnd )
3744       errDescription << "Licence problems.";
3745     else
3746     {
3747       char msg2[] = "SEGMENTATION FAULT";
3748       if ( 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 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 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 vector<int>& ghsNodes) const
3790 {
3791   size_t nbNodes = ghsNodes.size();
3792   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       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 > _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 }