Salome HOME
405ef09fb2d542ccabe8b5f1e04e46ff6ff7167c
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPlugin_BLSURF.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // ---
21 // File    : BLSURFPlugin_BLSURF.cxx
22 // Authors : Francis KLOSS (OCC) & Patrick LAUG (INRIA) & Lioka RAZAFINDRAZAKA (CEA)
23 //           & Aurelien ALLEAUME (DISTENE)
24 //           Size maps developement: Nicolas GEIMER (OCC) & Gilles DAVID (EURIWARE)
25 // ---
26
27 #include "BLSURFPlugin_BLSURF.hxx"
28 #include "BLSURFPlugin_Hypothesis.hxx"
29 #include "BLSURFPlugin_Attractor.hxx"
30
31 extern "C"{
32 #include <meshgems/meshgems.h>
33 #include <meshgems/cadsurf.h>
34 }
35
36 #include <structmember.h>
37
38
39 #include <Basics_Utils.hxx>
40
41 #include <SMDS_EdgePosition.hxx>
42 #include <SMESHDS_Group.hxx>
43 #include <SMESH_Gen.hxx>
44 #include <SMESH_Group.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MeshEditor.hxx>
47 #include <SMESH_MesherHelper.hxx>
48 #include <StdMeshers_FaceSide.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
50 #include <SMESH_File.hxx>
51
52 #include <utilities.h>
53
54 #include <limits>
55 #include <list>
56 #include <vector>
57 #include <set>
58 #include <cstdlib>
59
60 // OPENCASCADE includes
61 #include <BRepBuilderAPI_MakeFace.hxx>
62 #include <BRepBuilderAPI_MakePolygon.hxx>
63 #include <BRepBuilderAPI_MakeWire.hxx>
64 #include <BRepGProp.hxx>
65 #include <BRepTools.hxx>
66 #include <BRep_Builder.hxx>
67 #include <BRep_Tool.hxx>
68 #include <GProp_GProps.hxx>
69 #include <Geom2d_Curve.hxx>
70 #include <Geom2d_Line.hxx>
71 #include <GeomAPI_ProjectPointOnCurve.hxx>
72 #include <GeomAPI_ProjectPointOnSurf.hxx>
73 #include <Geom_Curve.hxx>
74 #include <Geom_Surface.hxx>
75 #include <NCollection_DataMap.hxx>
76 #include <NCollection_Map.hxx>
77 #include <Standard_ErrorHandler.hxx>
78 #include <TopExp.hxx>
79 #include <TopExp_Explorer.hxx>
80 #include <TopTools_DataMapOfShapeInteger.hxx>
81 #include <TopTools_IndexedMapOfShape.hxx>
82 #include <TopTools_MapOfShape.hxx>
83 #include <TopoDS.hxx>
84 #include <TopoDS_Compound.hxx>
85 #include <TopoDS_Edge.hxx>
86 #include <TopoDS_Face.hxx>
87 #include <TopoDS_Shape.hxx>
88 #include <TopoDS_Vertex.hxx>
89 #include <TopoDS_Wire.hxx>
90 #include <gp_Pnt.hxx>
91 #include <gp_Pnt2d.hxx>
92 #include <gp_XY.hxx>
93 #include <gp_XYZ.hxx>
94
95 #ifndef WIN32
96 #include <fenv.h>
97 #endif
98
99 using namespace std;
100
101 /* ==================================
102  * ===========  PYTHON ==============
103  * ==================================*/
104
105 namespace
106 {
107   typedef struct {
108     PyObject_HEAD
109     int softspace;
110     std::string *out;
111     } PyStdOut;
112
113   static void
114   PyStdOut_dealloc(PyStdOut *self)
115   {
116     PyObject_Del(self);
117   }
118
119   static PyObject *
120   PyStdOut_write(PyStdOut *self, PyObject *args)
121   {
122     char *c;
123     int l;
124     if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
125       return NULL;
126
127     *(self->out)=*(self->out)+c;
128
129     Py_INCREF(Py_None);
130     return Py_None;
131   }
132
133   static PyMethodDef PyStdOut_methods[] = {
134     {"write",  (PyCFunction)PyStdOut_write,  METH_VARARGS,
135       PyDoc_STR("write(string) -> None")},
136     {NULL,    NULL}   /* sentinel */
137   };
138
139   static PyMemberDef PyStdOut_memberlist[] = {
140     {(char*)"softspace", T_INT,  offsetof(PyStdOut, softspace), 0,
141      (char*)"flag indicating that a space needs to be printed; used by print"},
142     {NULL} /* Sentinel */
143   };
144
145   static PyTypeObject PyStdOut_Type = {
146     /* The ob_type field must be initialized in the module init function
147      * to be portable to Windows without using C++. */
148     PyObject_HEAD_INIT(NULL)
149     0,                            /*ob_size*/
150     "PyOut",                      /*tp_name*/
151     sizeof(PyStdOut),             /*tp_basicsize*/
152     0,                            /*tp_itemsize*/
153     /* methods */
154     (destructor)PyStdOut_dealloc, /*tp_dealloc*/
155     0,                            /*tp_print*/
156     0,                            /*tp_getattr*/
157     0,                            /*tp_setattr*/
158     0,                            /*tp_compare*/
159     0,                            /*tp_repr*/
160     0,                            /*tp_as_number*/
161     0,                            /*tp_as_sequence*/
162     0,                            /*tp_as_mapping*/
163     0,                            /*tp_hash*/
164     0,                            /*tp_call*/
165     0,                            /*tp_str*/
166     PyObject_GenericGetAttr,      /*tp_getattro*/
167     /* softspace is writable:  we must supply tp_setattro */
168     PyObject_GenericSetAttr,      /* tp_setattro */
169     0,                            /*tp_as_buffer*/
170     Py_TPFLAGS_DEFAULT,           /*tp_flags*/
171     0,                            /*tp_doc*/
172     0,                            /*tp_traverse*/
173     0,                            /*tp_clear*/
174     0,                            /*tp_richcompare*/
175     0,                            /*tp_weaklistoffset*/
176     0,                            /*tp_iter*/
177     0,                            /*tp_iternext*/
178     PyStdOut_methods,             /*tp_methods*/
179     PyStdOut_memberlist,          /*tp_members*/
180     0,                            /*tp_getset*/
181     0,                            /*tp_base*/
182     0,                            /*tp_dict*/
183     0,                            /*tp_descr_get*/
184     0,                            /*tp_descr_set*/
185     0,                            /*tp_dictoffset*/
186     0,                            /*tp_init*/
187     0,                            /*tp_alloc*/
188     0,                            /*tp_new*/
189     0,                            /*tp_free*/
190     0,                            /*tp_is_gc*/
191   };
192
193   PyObject * newPyStdOut( std::string& out )
194   {
195     PyStdOut* self = PyObject_New(PyStdOut, &PyStdOut_Type);
196     if (self) {
197       self->softspace = 0;
198       self->out=&out;
199     }
200     return (PyObject*)self;
201   }
202 }
203
204
205 ////////////////////////END PYTHON///////////////////////////
206
207 //////////////////MY MAPS////////////////////////////////////////
208 namespace {
209 TopTools_IndexedMapOfShape FacesWithSizeMap;
210 std::map<int,string> FaceId2SizeMap;
211 TopTools_IndexedMapOfShape EdgesWithSizeMap;
212 std::map<int,string> EdgeId2SizeMap;
213 TopTools_IndexedMapOfShape VerticesWithSizeMap;
214 std::map<int,string> VertexId2SizeMap;
215
216 std::map<int,PyObject*> FaceId2PythonSmp;
217 std::map<int,PyObject*> EdgeId2PythonSmp;
218 std::map<int,PyObject*> VertexId2PythonSmp;
219
220 typedef std::map<int, std::vector< BLSURFPlugin_Attractor* > > TId2ClsAttractorVec;
221 TId2ClsAttractorVec FaceId2ClassAttractor;
222 TId2ClsAttractorVec FaceIndex2ClassAttractor;
223 std::map<int,std::vector<double> > FaceId2AttractorCoords;
224 int theNbAttractors;
225
226 TopTools_IndexedMapOfShape FacesWithEnforcedVertices;
227 std::map< int, BLSURFPlugin_Hypothesis::TEnfVertexCoordsList > FaceId2EnforcedVertexCoords;
228 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexCoords > EnfVertexCoords2ProjVertex;
229 std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList > EnfVertexCoords2EnfVertexList;
230 SMESH_MesherHelper* theHelper;
231
232 bool HasSizeMapOnFace=false;
233 bool HasSizeMapOnEdge=false;
234 bool HasSizeMapOnVertex=false;
235 //bool HasAttractorOnFace=false;
236 }
237 //=============================================================================
238 /*!
239  *
240  */
241 //=============================================================================
242
243 BLSURFPlugin_BLSURF::BLSURFPlugin_BLSURF(int        hypId,
244                                          int        studyId,
245                                          SMESH_Gen* gen,
246                                          bool       theHasGEOM)
247   : SMESH_2D_Algo(hypId, studyId, gen)
248 {
249   _name = theHasGEOM ? "MG-CADSurf" : "MG-CADSurf_NOGEOM";//"BLSURF";
250   _shapeType = (1 << TopAbs_FACE); // 1 bit /shape type
251   _compatibleHypothesis.push_back(BLSURFPlugin_Hypothesis::GetHypType(theHasGEOM));
252   if ( theHasGEOM )
253     _compatibleHypothesis.push_back(StdMeshers_ViscousLayers2D::GetHypType());
254   _requireDiscreteBoundary = false;
255   _onlyUnaryInput = false;
256   _hypothesis = NULL;
257   _supportSubmeshes = true;
258   _requireShape = theHasGEOM;
259
260   smeshGen_i = SMESH_Gen_i::GetSMESHGen();
261   CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager");
262   SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject);
263
264   myStudy = NULL;
265   myStudy = aStudyMgr->GetStudyByID(_studyId);
266
267   /* Initialize the Python interpreter */
268   assert(Py_IsInitialized());
269   PyGILState_STATE gstate;
270   gstate = PyGILState_Ensure();
271
272   main_mod = NULL;
273   main_mod = PyImport_AddModule("__main__");
274
275   main_dict = NULL;
276   main_dict = PyModule_GetDict(main_mod);
277
278   PyRun_SimpleString("from math import *");
279   PyGILState_Release(gstate);
280
281   FacesWithSizeMap.Clear();
282   FaceId2SizeMap.clear();
283   EdgesWithSizeMap.Clear();
284   EdgeId2SizeMap.clear();
285   VerticesWithSizeMap.Clear();
286   VertexId2SizeMap.clear();
287   FaceId2PythonSmp.clear();
288   EdgeId2PythonSmp.clear();
289   VertexId2PythonSmp.clear();
290   FaceId2AttractorCoords.clear();
291   FaceId2ClassAttractor.clear();
292   FaceIndex2ClassAttractor.clear();
293   FacesWithEnforcedVertices.Clear();
294   FaceId2EnforcedVertexCoords.clear();
295   EnfVertexCoords2ProjVertex.clear();
296   EnfVertexCoords2EnfVertexList.clear();
297
298   _compute_canceled = false;
299 }
300
301 //=============================================================================
302 /*!
303  *
304  */
305 //=============================================================================
306
307 BLSURFPlugin_BLSURF::~BLSURFPlugin_BLSURF()
308 {
309 }
310
311
312 //=============================================================================
313 /*!
314  *
315  */
316 //=============================================================================
317
318 bool BLSURFPlugin_BLSURF::CheckHypothesis
319                          (SMESH_Mesh&                          aMesh,
320                           const TopoDS_Shape&                  aShape,
321                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
322 {
323   _hypothesis        = NULL;
324   _haveViscousLayers = false;
325
326   list<const SMESHDS_Hypothesis*>::const_iterator itl;
327   const SMESHDS_Hypothesis* theHyp;
328
329   const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape,
330                                                                   /*ignoreAuxiliary=*/false);
331   aStatus = SMESH_Hypothesis::HYP_OK;
332   if ( hyps.empty() )
333   {
334     return true;  // can work with no hypothesis
335   }
336
337   for ( itl = hyps.begin(); itl != hyps.end() && ( aStatus == HYP_OK ); ++itl )
338   {
339     theHyp = *itl;
340     string hypName = theHyp->GetName();
341     if ( hypName == BLSURFPlugin_Hypothesis::GetHypType(true) ||
342          hypName == BLSURFPlugin_Hypothesis::GetHypType(false) )
343     {
344       _hypothesis = static_cast<const BLSURFPlugin_Hypothesis*> (theHyp);
345       ASSERT(_hypothesis);
346       if ( _hypothesis->GetPhysicalMesh() == BLSURFPlugin_Hypothesis::DefaultSize &&
347            _hypothesis->GetGeometricMesh() == BLSURFPlugin_Hypothesis::DefaultGeom )
348         //  hphy_flag = 0 and hgeo_flag = 0 is not allowed (spec)
349         aStatus = SMESH_Hypothesis::HYP_BAD_PARAMETER;
350     }
351     else if ( hypName == StdMeshers_ViscousLayers2D::GetHypType() )
352     {
353       if ( !_haveViscousLayers )
354       {
355         if ( error( StdMeshers_ViscousLayers2D::CheckHypothesis( aMesh, aShape, aStatus )))
356           _haveViscousLayers = true;
357       }
358     }
359     else
360     {
361       aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
362     }
363   }
364   return aStatus == SMESH_Hypothesis::HYP_OK;
365 }
366
367 //=============================================================================
368 /*!
369  * Pass parameters to MG-CADSurf
370  */
371 //=============================================================================
372
373 inline std::string val_to_string(double d)
374 {
375    std::ostringstream o;
376    o << d;
377    return o.str();
378 }
379
380 inline std::string val_to_string_rel(double d)
381 {
382    std::ostringstream o;
383    o << d;
384    o << 'r';
385    return o.str();
386 }
387
388 inline std::string val_to_string(int i)
389 {
390    std::ostringstream o;
391    o << i;
392    return o.str();
393 }
394
395 inline std::string val_to_string_rel(int i)
396 {
397    std::ostringstream o;
398    o << i;
399    o << 'r';
400    return o.str();
401 }
402
403 double _smp_phy_size;
404 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data);
405 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data);
406 status_t size_on_vertex(integer vertex_id, real *size, void *user_data);
407
408 typedef struct {
409         gp_XY uv;
410         gp_XYZ xyz;
411 } projectionPoint;
412
413 /////////////////////////////////////////////////////////
414
415 projectionPoint getProjectionPoint(TopoDS_Face& theFace, const gp_Pnt& thePoint)
416 {
417   projectionPoint myPoint;
418
419   if ( theFace.IsNull() )
420   {
421     TopoDS_Shape foundFace, myShape = theHelper->GetSubShape();
422     TopTools_MapOfShape checkedFaces;
423     std::map< double, std::pair< TopoDS_Face, gp_Pnt2d > > dist2face;
424
425     for ( TopExp_Explorer exp ( myShape, TopAbs_FACE ); exp.More(); exp.Next())
426     {
427       const TopoDS_Face& face = TopoDS::Face( exp.Current() );
428       if ( !checkedFaces.Add( face )) continue;
429
430       // check distance to face
431       Handle(ShapeAnalysis_Surface) surface = theHelper->GetSurface( face );
432       gp_Pnt2d uv = surface->ValueOfUV( thePoint, Precision::Confusion());
433       double distance = surface->Gap();
434       if ( distance > Precision::Confusion() )
435       {
436         // the face is far, store for future analysis
437         dist2face.insert( std::make_pair( distance, std::make_pair( face, uv )));
438       }
439       else
440       {
441         // check location on the face
442         BRepClass_FaceClassifier FC( face, uv, BRep_Tool::Tolerance( face ));
443         if ( FC.State() == TopAbs_IN )
444         {
445           if ( !foundFace.IsNull() )
446             return myPoint; // thePoint seems to be TopAbs_ON
447           foundFace   = face;
448           myPoint.uv  = uv.XY();
449           myPoint.xyz = surface->Value( uv ).XYZ();
450           // break;
451         }
452         if ( FC.State() == TopAbs_ON )
453           return myPoint;
454       }
455     }
456     if ( foundFace.IsNull() )
457     {
458       // find the closest face
459       std::map< double, std::pair< TopoDS_Face, gp_Pnt2d > >::iterator d2f = dist2face.begin();
460       for ( ; d2f != dist2face.end(); ++d2f )
461       {
462         const TopoDS_Face& face = d2f->second.first;
463         const gp_Pnt2d &     uv = d2f->second.second;
464         BRepClass_FaceClassifier FC( face, uv, Precision::Confusion());
465         if ( FC.State() == TopAbs_IN )
466         {
467           foundFace   = face;
468           myPoint.uv  = uv.XY();
469           myPoint.xyz = theHelper->GetSurface( face )->Value( uv ).XYZ();
470           break;
471         }
472       }
473     }
474     // set the resultShape
475     // if ( foundFace.IsNull() )
476     //   throw SMESH_ComputeError(COMPERR_BAD_PARMETERS,
477     //                            "getProjectionPoint: can't find a face by a vertex");
478     theFace = TopoDS::Face( foundFace );
479   }
480   else
481   {
482     Handle(Geom_Surface) surface = BRep_Tool::Surface( theFace );
483     GeomAPI_ProjectPointOnSurf projector( thePoint, surface );
484     if ( !projector.IsDone() || projector.NbPoints()==0 )
485       throw SMESH_ComputeError(COMPERR_BAD_PARMETERS,
486                                "getProjectionPoint: can't project a vertex to a face");
487
488     Standard_Real u,v;
489     projector.LowerDistanceParameters(u,v);
490     myPoint.uv = gp_XY(u,v);
491     gp_Pnt aPnt = projector.NearestPoint();
492     myPoint.xyz = gp_XYZ(aPnt.X(),aPnt.Y(),aPnt.Z());
493
494     BRepClass_FaceClassifier FC( theFace, myPoint.uv, Precision::Confusion());
495     if ( FC.State() != TopAbs_IN )
496       theFace.Nullify();
497   }
498
499   return myPoint;
500 }
501
502 /////////////////////////////////////////////////////////
503 TopoDS_Shape BLSURFPlugin_BLSURF::entryToShape(std::string entry)
504 {
505   TopoDS_Shape S;
506   if ( !entry.empty() )
507   {
508     GEOM::GEOM_Object_var aGeomObj;
509     SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() );
510     if (!aSObj->_is_nil()) {
511       CORBA::Object_var obj = aSObj->GetObject();
512       aGeomObj = GEOM::GEOM_Object::_narrow(obj);
513       aSObj->UnRegister();
514     }
515     if ( !aGeomObj->_is_nil() )
516       S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
517   }
518   return S;
519 }
520
521 void _createEnforcedVertexOnFace(TopoDS_Face faceShape, gp_Pnt aPnt, BLSURFPlugin_Hypothesis::TEnfVertex *enfVertex)
522 {
523   BLSURFPlugin_Hypothesis::TEnfVertexCoords enf_coords, coords, s_coords;
524
525   // Find the face and get the (u,v) values of the enforced vertex on the face
526   projectionPoint myPoint = getProjectionPoint(faceShape,aPnt);
527   if ( faceShape.IsNull() )
528     return;
529
530   enf_coords.push_back(aPnt.X());
531   enf_coords.push_back(aPnt.Y());
532   enf_coords.push_back(aPnt.Z());
533
534   coords.push_back(myPoint.uv.X());
535   coords.push_back(myPoint.uv.Y());
536   coords.push_back(myPoint.xyz.X());
537   coords.push_back(myPoint.xyz.Y());
538   coords.push_back(myPoint.xyz.Z());
539
540   s_coords.push_back(myPoint.xyz.X());
541   s_coords.push_back(myPoint.xyz.Y());
542   s_coords.push_back(myPoint.xyz.Z());
543
544   // Save pair projected vertex / enf vertex
545   EnfVertexCoords2ProjVertex[s_coords] = enf_coords;
546   pair<BLSURFPlugin_Hypothesis::TEnfVertexList::iterator,bool> ret;
547   BLSURFPlugin_Hypothesis::TEnfVertexList::iterator it;
548   ret = EnfVertexCoords2EnfVertexList[s_coords].insert(enfVertex);
549   if (ret.second == false) {
550     it = ret.first;
551     (*it)->grpName = enfVertex->grpName;
552   }
553
554   int key = 0;
555   if (! FacesWithEnforcedVertices.Contains(faceShape)) {
556     key = FacesWithEnforcedVertices.Add(faceShape);
557   }
558   else {
559     key = FacesWithEnforcedVertices.FindIndex(faceShape);
560   }
561
562   // If a node is already created by an attractor, do not create enforced vertex
563   int attractorKey = FacesWithSizeMap.FindIndex(faceShape);
564   bool sameAttractor = false;
565   if (attractorKey >= 0)
566     if (FaceId2AttractorCoords.count(attractorKey) > 0)
567       if (FaceId2AttractorCoords[attractorKey] == coords)
568         sameAttractor = true;
569
570   if (FaceId2EnforcedVertexCoords.find(key) != FaceId2EnforcedVertexCoords.end()) {
571     if (! sameAttractor)
572       FaceId2EnforcedVertexCoords[key].insert(coords); // there should be no redondant coords here (see std::set management)
573   }
574   else {
575     if (! sameAttractor) {
576       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList ens;
577       ens.insert(coords);
578       FaceId2EnforcedVertexCoords[key] = ens;
579     }
580   }
581 }
582   
583 /////////////////////////////////////////////////////////
584 void BLSURFPlugin_BLSURF::createEnforcedVertexOnFace(TopoDS_Shape faceShape, BLSURFPlugin_Hypothesis::TEnfVertexList enfVertexList)
585 {
586   BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex;
587   gp_Pnt aPnt;
588
589   BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfVertexListIt = enfVertexList.begin();
590
591   for( ; enfVertexListIt != enfVertexList.end() ; ++enfVertexListIt ) {
592     enfVertex = *enfVertexListIt;
593     // Case of manual coords
594     if (enfVertex->coords.size() != 0) {
595       aPnt.SetCoord(enfVertex->coords[0],enfVertex->coords[1],enfVertex->coords[2]);
596       _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
597     }
598
599     // Case of geom vertex coords
600     if (enfVertex->geomEntry != "") {
601       TopoDS_Shape GeomShape = entryToShape(enfVertex->geomEntry);
602       TopAbs_ShapeEnum GeomType  = GeomShape.ShapeType();
603        if (GeomType == TopAbs_VERTEX)
604        {
605          enfVertex->vertex = TopoDS::Vertex( GeomShape );
606          aPnt = BRep_Tool::Pnt( enfVertex->vertex );
607          _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
608        }
609        // Group Management
610        if (GeomType == TopAbs_COMPOUND)
611        {
612          for (TopoDS_Iterator it (GeomShape); it.More(); it.Next())
613            if (it.Value().ShapeType() == TopAbs_VERTEX)
614            {
615              enfVertex->vertex = TopoDS::Vertex( it.Value() );
616              aPnt = BRep_Tool::Pnt( enfVertex->vertex );
617              _createEnforcedVertexOnFace( TopoDS::Face(faceShape),  aPnt, enfVertex);
618            }
619        }
620     }
621   }
622 }
623
624 /////////////////////////////////////////////////////////
625 void createAttractorOnFace(TopoDS_Shape GeomShape, std::string AttractorFunction, double defaultSize)
626 {
627   double xa, ya, za; // Coordinates of attractor point
628   double a, b;       // Attractor parameter
629   double d = 0.;
630   bool createNode=false; // To create a node on attractor projection
631   size_t pos1, pos2;
632   const char *sep = ";";
633   // atIt->second has the following pattern:
634   // ATTRACTOR(xa;ya;za;a;b;True|False;d)
635   // where:
636   // xa;ya;za : coordinates of  attractor
637   // a        : desired size on attractor
638   // b        : distance of influence of attractor
639   // d        : distance until which the size remains constant
640   //
641   // We search the parameters in the string
642   // xa
643   pos1 = AttractorFunction.find(sep);
644   if (pos1!=string::npos)
645   xa = atof(AttractorFunction.substr(10, pos1-10).c_str());
646   // ya
647   pos2 = AttractorFunction.find(sep, pos1+1);
648   if (pos2!=string::npos) {
649   ya = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
650   pos1 = pos2;
651   }
652   // za
653   pos2 = AttractorFunction.find(sep, pos1+1);
654   if (pos2!=string::npos) {
655   za = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
656   pos1 = pos2;
657   }
658   // a
659   pos2 = AttractorFunction.find(sep, pos1+1);
660   if (pos2!=string::npos) {
661   a = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
662   pos1 = pos2;
663   }
664   // b
665   pos2 = AttractorFunction.find(sep, pos1+1);
666   if (pos2!=string::npos) {
667   b = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
668   pos1 = pos2;
669   }
670   // createNode
671   pos2 = AttractorFunction.find(sep, pos1+1);
672   if (pos2!=string::npos) {
673     string createNodeStr = AttractorFunction.substr(pos1+1, pos2-pos1-1);
674     createNode = (AttractorFunction.substr(pos1+1, pos2-pos1-1) == "True");
675     pos1=pos2;
676   }
677   // d
678   pos2 = AttractorFunction.find(")");
679   if (pos2!=string::npos) {
680   d = atof(AttractorFunction.substr(pos1+1, pos2-pos1-1).c_str());
681   }
682
683   // Get the (u,v) values of the attractor on the face
684   projectionPoint myPoint = getProjectionPoint(TopoDS::Face(GeomShape),gp_Pnt(xa,ya,za));
685   gp_XY uvPoint = myPoint.uv;
686   gp_XYZ xyzPoint = myPoint.xyz;
687   Standard_Real u0 = uvPoint.X();
688   Standard_Real v0 = uvPoint.Y();
689   Standard_Real x0 = xyzPoint.X();
690   Standard_Real y0 = xyzPoint.Y();
691   Standard_Real z0 = xyzPoint.Z();
692   std::vector<double> coords;
693   coords.push_back(u0);
694   coords.push_back(v0);
695   coords.push_back(x0);
696   coords.push_back(y0);
697   coords.push_back(z0);
698   // We construct the python function
699   ostringstream attractorFunctionStream;
700   attractorFunctionStream << "def f(u,v): return ";
701   attractorFunctionStream << defaultSize << "-(" << defaultSize <<"-" << a << ")";
702   //attractorFunctionStream << "*exp(-((u-("<<u0<<"))*(u-("<<u0<<"))+(v-("<<v0<<"))*(v-("<<v0<<")))/(" << b << "*" << b <<"))";
703   // rnc: make possible to keep the size constant until
704   // a defined distance. Distance is expressed as the positiv part
705   // of r-d where r is the distance to (u0,v0)
706   attractorFunctionStream << "*exp(-(0.5*(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"+abs(sqrt((u-"<<u0<<")**2+(v-"<<v0<<")**2)-"<<d<<"))/(" << b << "))**2)";
707
708   int key;
709   if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
710     key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
711   }
712   else {
713     key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
714   }
715   FaceId2SizeMap[key] =attractorFunctionStream.str();
716   if (createNode) {
717     FaceId2AttractorCoords[key] = coords;
718   }
719 //   // Test for new attractors
720 //   gp_Pnt myP(xyzPoint);
721 //   TopoDS_Vertex myV = BRepBuilderAPI_MakeVertex(myP);
722 //   BLSURFPlugin_Attractor myAttractor(TopoDS::Face(GeomShape),myV,200);
723 //   myAttractor.SetParameters(a, defaultSize, b, d);
724 //   myAttractor.SetType(1);
725 //   FaceId2ClassAttractor[key] = myAttractor;
726 //   if(FaceId2ClassAttractor[key].GetFace().IsNull()){
727 //   }
728 }
729
730 // One sub-shape to get ids from
731 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(const TopoDS_Shape& theMainShape,
732                                                            const TopoDS_Shape& theSubShape,
733                                                            TopAbs_ShapeEnum    theShapeType)
734 {
735   BLSURFPlugin_BLSURF::TListOfIDs face_ids;
736
737   TopTools_MapOfShape subShapes;
738   TopTools_IndexedMapOfShape anIndices;
739   TopExp::MapShapes(theMainShape, theShapeType, anIndices);
740
741   for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
742   {
743     if ( subShapes.Add( face_iter.Current() )) // issue 23416
744     {
745       int face_id = anIndices.FindIndex( face_iter.Current() );
746       if ( face_id == 0 )
747         throw SALOME_Exception( "Periodicity: sub_shape not found in main_shape");
748       face_ids.push_back( face_id );
749     }
750   }
751   return face_ids;
752 }
753
754 BLSURFPlugin_BLSURF::TListOfIDs _getSubShapeIDsInMainShape(SMESH_Mesh*      theMesh,
755                                                            TopoDS_Shape     theSubShape,
756                                                            TopAbs_ShapeEnum theShapeType)
757 {
758   BLSURFPlugin_BLSURF::TListOfIDs face_ids;
759
760   for (TopExp_Explorer face_iter(theSubShape,theShapeType);face_iter.More();face_iter.Next())
761   {
762     int face_id = theMesh->GetMeshDS()->ShapeToIndex(face_iter.Current());
763     if (face_id == 0)
764       throw SALOME_Exception ( "Periodicity: sub_shape not found in main_shape");
765     face_ids.push_back(face_id);
766   }
767
768   return face_ids;
769 }
770
771 void BLSURFPlugin_BLSURF::addCoordsFromVertices(const std::vector<std::string> &theVerticesEntries, std::vector<double> &theVerticesCoords)
772 {
773   for (std::vector<std::string>::const_iterator it = theVerticesEntries.begin(); it != theVerticesEntries.end(); it++)
774   {
775     BLSURFPlugin_Hypothesis::TEntry theVertexEntry = *it;
776     addCoordsFromVertex(theVertexEntry, theVerticesCoords);
777   }
778 }
779
780
781 void BLSURFPlugin_BLSURF::addCoordsFromVertex(BLSURFPlugin_Hypothesis::TEntry theVertexEntry, std::vector<double> &theVerticesCoords)
782 {
783   if (theVertexEntry!="")
784   {
785     TopoDS_Shape aShape = entryToShape(theVertexEntry);
786
787     gp_Pnt aPnt = BRep_Tool::Pnt( TopoDS::Vertex( aShape ) );
788     double theX, theY, theZ;
789     theX = aPnt.X();
790     theY = aPnt.Y();
791     theZ = aPnt.Z();
792
793     theVerticesCoords.push_back(theX);
794     theVerticesCoords.push_back(theY);
795     theVerticesCoords.push_back(theZ);
796   }
797 }
798
799 /////////////////////////////////////////////////////////
800 void BLSURFPlugin_BLSURF::createPreCadFacesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
801 {
802   TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
803   TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
804
805   TListOfIDs theFace1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_FACE);
806   TListOfIDs theFace2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_FACE);
807
808   TPreCadPeriodicityIDs preCadFacesPeriodicityIDs;
809   preCadFacesPeriodicityIDs.shape1IDs = theFace1_ids;
810   preCadFacesPeriodicityIDs.shape2IDs = theFace2_ids;
811
812   addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadFacesPeriodicityIDs.theSourceVerticesCoords);
813   addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadFacesPeriodicityIDs.theTargetVerticesCoords);
814
815   _preCadFacesIDsPeriodicityVector.push_back(preCadFacesPeriodicityIDs);
816 }
817
818 /////////////////////////////////////////////////////////
819 void BLSURFPlugin_BLSURF::createPreCadEdgesPeriodicity(TopoDS_Shape theGeomShape, const BLSURFPlugin_Hypothesis::TPreCadPeriodicity &preCadPeriodicity)
820 {
821   TopoDS_Shape geomShape1 = entryToShape(preCadPeriodicity.shape1Entry);
822   TopoDS_Shape geomShape2 = entryToShape(preCadPeriodicity.shape2Entry);
823
824   TListOfIDs theEdge1_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape1, TopAbs_EDGE);
825   TListOfIDs theEdge2_ids = _getSubShapeIDsInMainShape(theGeomShape, geomShape2, TopAbs_EDGE);
826
827   TPreCadPeriodicityIDs preCadEdgesPeriodicityIDs;
828   preCadEdgesPeriodicityIDs.shape1IDs = theEdge1_ids;
829   preCadEdgesPeriodicityIDs.shape2IDs = theEdge2_ids;
830
831   addCoordsFromVertices(preCadPeriodicity.theSourceVerticesEntries, preCadEdgesPeriodicityIDs.theSourceVerticesCoords);
832   addCoordsFromVertices(preCadPeriodicity.theTargetVerticesEntries, preCadEdgesPeriodicityIDs.theTargetVerticesCoords);
833
834   _preCadEdgesIDsPeriodicityVector.push_back(preCadEdgesPeriodicityIDs);
835 }
836
837
838 /////////////////////////////////////////////////////////
839
840 void BLSURFPlugin_BLSURF::SetParameters(const BLSURFPlugin_Hypothesis* hyp,
841                                         cadsurf_session_t *            css,
842                                         const TopoDS_Shape&            theGeomShape)
843 {
844   // rnc : Bug 1457
845   // Clear map so that it is not stored in the algorithm with old enforced vertices in it
846   FacesWithSizeMap.Clear();
847   FaceId2SizeMap.clear();
848   EdgesWithSizeMap.Clear();
849   EdgeId2SizeMap.clear();
850   VerticesWithSizeMap.Clear();
851   VertexId2SizeMap.clear();
852   FaceId2PythonSmp.clear();
853   EdgeId2PythonSmp.clear();
854   VertexId2PythonSmp.clear();
855   FaceId2AttractorCoords.clear();
856   FaceId2ClassAttractor.clear();
857   FaceIndex2ClassAttractor.clear();
858   FacesWithEnforcedVertices.Clear();
859   FaceId2EnforcedVertexCoords.clear();
860   EnfVertexCoords2ProjVertex.clear();
861   EnfVertexCoords2EnfVertexList.clear();
862
863   double diagonal               = SMESH_Mesh::GetShapeDiagonalSize( theGeomShape );
864   double bbSegmentation         = _gen->GetBoundaryBoxSegmentation();
865   int    _physicalMesh          = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
866   int    _geometricMesh         = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
867   double _phySize               = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
868   bool   _phySizeRel            = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
869   double _minSize               = BLSURFPlugin_Hypothesis::GetDefaultMinSize(diagonal);
870   bool   _minSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMinSizeRel();
871   double _maxSize               = BLSURFPlugin_Hypothesis::GetDefaultMaxSize(diagonal);
872   bool   _maxSizeRel            = BLSURFPlugin_Hypothesis::GetDefaultMaxSizeRel();
873   double _use_gradation         = BLSURFPlugin_Hypothesis::GetDefaultUseGradation();
874   double _gradation             = BLSURFPlugin_Hypothesis::GetDefaultGradation();
875   double _use_volume_gradation  = BLSURFPlugin_Hypothesis::GetDefaultUseVolumeGradation();
876   double _volume_gradation      = BLSURFPlugin_Hypothesis::GetDefaultVolumeGradation();
877   BLSURFPlugin_Hypothesis::ElementType _elementType = BLSURFPlugin_Hypothesis::GetDefaultElementType();
878   double _angleMesh             = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
879   double _chordalError          = BLSURFPlugin_Hypothesis::GetDefaultChordalError(diagonal);
880   bool   _anisotropic           = BLSURFPlugin_Hypothesis::GetDefaultAnisotropic();
881   double _anisotropicRatio      = BLSURFPlugin_Hypothesis::GetDefaultAnisotropicRatio();
882   bool   _removeTinyEdges       = BLSURFPlugin_Hypothesis::GetDefaultRemoveTinyEdges();
883   double _tinyEdgeLength        = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeLength(diagonal);
884   bool   _optimiseTinyEdges     = BLSURFPlugin_Hypothesis::GetDefaultOptimiseTinyEdges();
885   double _tinyEdgeOptimisLength = BLSURFPlugin_Hypothesis::GetDefaultTinyEdgeOptimisationLength(diagonal);
886   bool   _correctSurfaceIntersec= BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersection();
887   double _corrSurfaceIntersCost = BLSURFPlugin_Hypothesis::GetDefaultCorrectSurfaceIntersectionMaxCost();
888   bool   _badElementRemoval     = BLSURFPlugin_Hypothesis::GetDefaultBadElementRemoval();
889   double _badElementAspectRatio = BLSURFPlugin_Hypothesis::GetDefaultBadElementAspectRatio();
890   bool   _optimizeMesh          = BLSURFPlugin_Hypothesis::GetDefaultOptimizeMesh();
891   bool   _quadraticMesh         = BLSURFPlugin_Hypothesis::GetDefaultQuadraticMesh();
892   int    _verb                  = BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
893   //int    _topology              = BLSURFPlugin_Hypothesis::GetDefaultTopology();
894
895   // PreCAD
896   //int _precadMergeEdges         = BLSURFPlugin_Hypothesis::GetDefaultPreCADMergeEdges();
897   //int _precadRemoveDuplicateCADFaces = BLSURFPlugin_Hypothesis::GetDefaultPreCADRemoveDuplicateCADFaces();
898   //int _precadProcess3DTopology  = BLSURFPlugin_Hypothesis::GetDefaultPreCADProcess3DTopology();
899   //int _precadDiscardInput       = BLSURFPlugin_Hypothesis::GetDefaultPreCADDiscardInput();
900
901   const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadFacesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadFacesPeriodicityVector(hyp);
902
903   if (hyp) {
904     _physicalMesh  = (int) hyp->GetPhysicalMesh();
905     _geometricMesh = (int) hyp->GetGeometricMesh();
906     if (hyp->GetPhySize() > 0) {
907       _phySize       = hyp->GetPhySize();
908       // if user size is not explicitly specified, "relative" flag is ignored
909       _phySizeRel    = hyp->IsPhySizeRel();
910     }
911     if (hyp->GetMinSize() > 0) {
912       _minSize       = hyp->GetMinSize();
913       // if min size is not explicitly specified, "relative" flag is ignored
914       _minSizeRel    = hyp->IsMinSizeRel();
915     }
916     if (hyp->GetMaxSize() > 0) {
917       _maxSize       = hyp->GetMaxSize();
918       // if max size is not explicitly specified, "relative" flag is ignored
919       _maxSizeRel    = hyp->IsMaxSizeRel();
920     }
921     _use_gradation = hyp->GetUseGradation();
922     if (hyp->GetGradation() > 0 && _use_gradation)
923       _gradation     = hyp->GetGradation();
924     _use_volume_gradation    = hyp->GetUseVolumeGradation();
925     if (hyp->GetVolumeGradation() > 0 && _use_volume_gradation )
926       _volume_gradation      = hyp->GetVolumeGradation();
927     _elementType     = hyp->GetElementType();
928     if (hyp->GetAngleMesh() > 0)
929       _angleMesh     = hyp->GetAngleMesh();
930     if (hyp->GetChordalError() > 0)
931       _chordalError          = hyp->GetChordalError();
932     _anisotropic             = hyp->GetAnisotropic();
933     if (hyp->GetAnisotropicRatio() >= 0)
934       _anisotropicRatio      = hyp->GetAnisotropicRatio();
935     _removeTinyEdges         = hyp->GetRemoveTinyEdges();
936     if (hyp->GetTinyEdgeLength() > 0)
937       _tinyEdgeLength        = hyp->GetTinyEdgeLength();
938     _optimiseTinyEdges       = hyp->GetOptimiseTinyEdges();
939     if (hyp->GetTinyEdgeOptimisationLength() > 0)
940       _tinyEdgeOptimisLength = hyp->GetTinyEdgeOptimisationLength();
941     _correctSurfaceIntersec  = hyp->GetCorrectSurfaceIntersection();
942     if (hyp->GetCorrectSurfaceIntersectionMaxCost() > 0)
943       _corrSurfaceIntersCost = hyp->GetCorrectSurfaceIntersectionMaxCost();
944     _badElementRemoval       = hyp->GetBadElementRemoval();
945     if (hyp->GetBadElementAspectRatio() >= 0)
946       _badElementAspectRatio = hyp->GetBadElementAspectRatio();
947     _optimizeMesh  = hyp->GetOptimizeMesh();
948     _quadraticMesh = hyp->GetQuadraticMesh();
949     _verb          = hyp->GetVerbosity();
950     //_topology      = (int) hyp->GetTopology();
951     // PreCAD
952     //_precadMergeEdges        = hyp->GetPreCADMergeEdges();
953     //_precadRemoveDuplicateCADFaces = hyp->GetPreCADRemoveDuplicateCADFaces();
954     //_precadProcess3DTopology = hyp->GetPreCADProcess3DTopology();
955     //_precadDiscardInput      = hyp->GetPreCADDiscardInput();
956
957     const BLSURFPlugin_Hypothesis::TOptionValues& opts = hyp->GetOptionValues();
958     BLSURFPlugin_Hypothesis::TOptionValues::const_iterator opIt;
959     for ( opIt = opts.begin(); opIt != opts.end(); ++opIt ){
960       MESSAGE("OptionValue: " << opIt->first.c_str() << ", value: " << opIt->second.c_str());
961       if ( !opIt->second.empty() ) {
962         // With MeshGems 2.4-5, there are issues with periodicity and multithread
963         // => As a temporary workaround, we enforce to use only one thread if periodicity is used.
964         if (opIt->first == "max_number_of_threads" && opIt->second != "1" && ! preCadFacesPeriodicityVector.empty()){
965           std::cout << "INFO: Disabling multithread to avoid periodicity issues" << std::endl;
966           set_param(css, opIt->first.c_str(), "1");
967         }
968         else
969           set_param(css, opIt->first.c_str(), opIt->second.c_str());
970       }
971     }
972
973     const BLSURFPlugin_Hypothesis::TOptionValues& custom_opts = hyp->GetCustomOptionValues();
974     for ( opIt = custom_opts.begin(); opIt != custom_opts.end(); ++opIt )
975       if ( !opIt->second.empty() ) {
976         set_param(css, opIt->first.c_str(), opIt->second.c_str());
977       }
978
979     const BLSURFPlugin_Hypothesis::TOptionValues& preCADopts = hyp->GetPreCADOptionValues();
980     for ( opIt = preCADopts.begin(); opIt != preCADopts.end(); ++opIt )
981       if ( !opIt->second.empty() ) {
982         set_param(css, opIt->first.c_str(), opIt->second.c_str());
983       }
984   }
985
986   if ( BLSURFPlugin_Hypothesis::HasPreCADOptions( hyp ))
987   {
988     cadsurf_set_param(css, "use_precad", "yes" ); // for old versions
989   }
990   // PreProcessor (formerly PreCAD) -- commented params are preCADoptions (since 0023307)
991   //set_param(css, "merge_edges",            _precadMergeEdges ? "yes" : "no");
992   //set_param(css, "remove_duplicate_cad_faces", _precadRemoveDuplicateCADFaces ? "yes" : "no");
993   //set_param(css, "process_3d_topology",    _precadProcess3DTopology ? "1" : "0");
994   //set_param(css, "discard_input_topology", _precadDiscardInput ? "1" : "0");
995   //set_param(css, "max_number_of_points_per_patch", "1000000");
996   
997    bool useGradation = false;
998    switch (_physicalMesh)
999    {
1000      case BLSURFPlugin_Hypothesis::PhysicalGlobalSize:
1001        set_param(css, "physical_size_mode", "global");
1002        set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1003        break;
1004      case BLSURFPlugin_Hypothesis::PhysicalLocalSize:
1005        set_param(css, "physical_size_mode", "local");
1006        set_param(css, "global_physical_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1007        useGradation = true;
1008        break;
1009      default:
1010        set_param(css, "physical_size_mode", "none");
1011    }
1012
1013    switch (_geometricMesh)
1014    {
1015      case BLSURFPlugin_Hypothesis::GeometricalGlobalSize:
1016        set_param(css, "geometric_size_mode", "global");
1017        set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
1018        set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
1019        useGradation = true;
1020        break;
1021      case BLSURFPlugin_Hypothesis::GeometricalLocalSize:
1022        set_param(css, "geometric_size_mode", "local");
1023        set_param(css, "geometric_approximation", val_to_string(_angleMesh).c_str());
1024        set_param(css, "chordal_error", val_to_string(_chordalError).c_str());
1025        useGradation = true;
1026        break;
1027      default:
1028        set_param(css, "geometric_size_mode", "none");
1029    }
1030
1031    if ( hyp && hyp->GetPhySize() > 0 ) {
1032      // user size is explicitly specified via hypothesis parameters
1033      // min and max sizes should be compared with explicitly specified user size
1034      // - compute absolute min size
1035      double mins = _minSizeRel ? _minSize * diagonal : _minSize;
1036      // - min size should not be greater than user size
1037      if ( _phySize < mins )
1038        set_param(css, "min_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1039      else
1040        set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1041      // - compute absolute max size
1042      double maxs = _maxSizeRel ? _maxSize * diagonal : _maxSize;
1043      // - max size should not be less than user size
1044      if ( _phySize > maxs )
1045        set_param(css, "max_size", _phySizeRel ? val_to_string_rel(_phySize).c_str() : val_to_string(_phySize).c_str());
1046      else
1047        set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1048    }
1049    else {
1050      // user size is not explicitly specified
1051      // - if minsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1052      set_param(css, "min_size", _minSizeRel ? val_to_string_rel(_minSize).c_str() : val_to_string(_minSize).c_str());
1053      // - if maxsize is not explicitly specified, we pass default value computed automatically, in this case "relative" flag is ignored
1054      set_param(css, "max_size", _maxSizeRel ? val_to_string_rel(_maxSize).c_str() : val_to_string(_maxSize).c_str());
1055    }
1056    // anisotropic and quadrangle mesh requires disabling gradation
1057    if ( _anisotropic && _elementType != BLSURFPlugin_Hypothesis::Triangles )
1058      useGradation = false; // limitation of V1.3
1059    if ( useGradation && _use_gradation )
1060      set_param(css, "gradation",                       val_to_string(_gradation).c_str());
1061    if ( useGradation && _use_volume_gradation )
1062      set_param(css, "volume_gradation",                val_to_string(_volume_gradation).c_str());
1063
1064    // New since MeshGems 2.5: add full_quad
1065    const char * element_generation = "";
1066    switch ( _elementType )
1067    {
1068      case BLSURFPlugin_Hypothesis::Triangles:
1069        element_generation = "triangle";
1070        break;
1071      case BLSURFPlugin_Hypothesis::QuadrangleDominant:
1072        element_generation = "quad_dominant";
1073        break;
1074      case BLSURFPlugin_Hypothesis::Quadrangles:
1075        element_generation = "full_quad";
1076        break;
1077      default: ;
1078    }
1079    set_param(css, "element_generation",                element_generation);
1080
1081
1082    set_param(css, "metric",                            _anisotropic ? "anisotropic" : "isotropic");
1083    if ( _anisotropic )
1084      set_param(css, "anisotropic_ratio",                 val_to_string(_anisotropicRatio).c_str());
1085    set_param(css, "remove_tiny_edges",                 _removeTinyEdges ? "1" : "0");
1086    if ( _removeTinyEdges )
1087      set_param(css, "tiny_edge_length",                  val_to_string(_tinyEdgeLength).c_str());
1088    set_param(css, "optimise_tiny_edges",               _optimiseTinyEdges ? "1" : "0");
1089    if ( _optimiseTinyEdges )
1090      set_param(css, "tiny_edge_optimisation_length",   val_to_string(_tinyEdgeOptimisLength).c_str());
1091    set_param(css, "correct_surface_intersections",     _correctSurfaceIntersec ? "1" : "0");
1092    if ( _correctSurfaceIntersec )
1093      set_param(css, "surface_intersections_processing_max_cost", val_to_string(_corrSurfaceIntersCost ).c_str());
1094    set_param(css, "force_bad_surface_element_removal", _badElementRemoval ? "1" : "0");
1095    if ( _badElementRemoval )
1096      set_param(css, "bad_surface_element_aspect_ratio",  val_to_string(_badElementAspectRatio).c_str());
1097    set_param(css, "optimisation",                      _optimizeMesh ? "yes" : "no");
1098    set_param(css, "element_order",                     _quadraticMesh ? "quadratic" : "linear");
1099    set_param(css, "verbose",                           val_to_string(_verb).c_str());
1100
1101    _smp_phy_size = _phySizeRel ? _phySize*diagonal : _phySize;
1102    if ( _verb > 0 )
1103      std::cout << "_smp_phy_size = " << _smp_phy_size << std::endl;
1104
1105    if (_physicalMesh == BLSURFPlugin_Hypothesis::PhysicalLocalSize)
1106    {
1107     TopoDS_Shape GeomShape;
1108     TopoDS_Shape AttShape;
1109     TopAbs_ShapeEnum GeomType;
1110     //
1111     // Standard Size Maps
1112     //
1113     const BLSURFPlugin_Hypothesis::TSizeMap sizeMaps = BLSURFPlugin_Hypothesis::GetSizeMapEntries(hyp);
1114     BLSURFPlugin_Hypothesis::TSizeMap::const_iterator smIt = sizeMaps.begin();
1115     for ( ; smIt != sizeMaps.end(); ++smIt ) {
1116       if ( !smIt->second.empty() ) {
1117         GeomShape = entryToShape(smIt->first);
1118         GeomType  = GeomShape.ShapeType();
1119         int key = -1;
1120         // Group Management
1121         if (GeomType == TopAbs_COMPOUND) {
1122           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1123             // Group of faces
1124             if (it.Value().ShapeType() == TopAbs_FACE){
1125               HasSizeMapOnFace = true;
1126               if (! FacesWithSizeMap.Contains(TopoDS::Face(it.Value()))) {
1127                 key = FacesWithSizeMap.Add(TopoDS::Face(it.Value()));
1128               }
1129               else {
1130                 key = FacesWithSizeMap.FindIndex(TopoDS::Face(it.Value()));
1131               }
1132               FaceId2SizeMap[key] = smIt->second;
1133             }
1134             // Group of edges
1135             if (it.Value().ShapeType() == TopAbs_EDGE){
1136               HasSizeMapOnEdge = true;
1137               HasSizeMapOnFace = true;
1138               if (! EdgesWithSizeMap.Contains(TopoDS::Edge(it.Value()))) {
1139                 key = EdgesWithSizeMap.Add(TopoDS::Edge(it.Value()));
1140               }
1141               else {
1142                 key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(it.Value()));
1143               }
1144               EdgeId2SizeMap[key] = smIt->second;
1145             }
1146             // Group of vertices
1147             if (it.Value().ShapeType() == TopAbs_VERTEX){
1148               HasSizeMapOnVertex = true;
1149               HasSizeMapOnEdge = true;
1150               HasSizeMapOnFace = true;
1151               if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(it.Value()))) {
1152                 key = VerticesWithSizeMap.Add(TopoDS::Vertex(it.Value()));
1153               }
1154               else {
1155                 key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(it.Value()));
1156               }
1157               VertexId2SizeMap[key] = smIt->second;
1158             }
1159           }
1160         }
1161         // Single face
1162         if (GeomType == TopAbs_FACE){
1163           HasSizeMapOnFace = true;
1164           if (! FacesWithSizeMap.Contains(TopoDS::Face(GeomShape))) {
1165             key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape));
1166           }
1167           else {
1168             key = FacesWithSizeMap.FindIndex(TopoDS::Face(GeomShape));
1169           }
1170           FaceId2SizeMap[key] = smIt->second;
1171         }
1172         // Single edge
1173         if (GeomType == TopAbs_EDGE){
1174           HasSizeMapOnEdge = true;
1175           HasSizeMapOnFace = true;
1176           if (! EdgesWithSizeMap.Contains(TopoDS::Edge(GeomShape))) {
1177             key = EdgesWithSizeMap.Add(TopoDS::Edge(GeomShape));
1178           }
1179           else {
1180             key = EdgesWithSizeMap.FindIndex(TopoDS::Edge(GeomShape));
1181           }
1182           EdgeId2SizeMap[key] = smIt->second;
1183         }
1184         // Single vertex
1185         if (GeomType == TopAbs_VERTEX){
1186           HasSizeMapOnVertex = true;
1187           HasSizeMapOnEdge   = true;
1188           HasSizeMapOnFace   = true;
1189           if (! VerticesWithSizeMap.Contains(TopoDS::Vertex(GeomShape))) {
1190             key = VerticesWithSizeMap.Add(TopoDS::Vertex(GeomShape));
1191           }
1192           else {
1193             key = VerticesWithSizeMap.FindIndex(TopoDS::Vertex(GeomShape));
1194           }
1195           VertexId2SizeMap[key] = smIt->second;
1196         }
1197       }
1198     }
1199
1200     //
1201     // Attractors
1202     //
1203     // TODO appeler le constructeur des attracteurs directement ici
1204 //     if ( !_phySizeRel ) {
1205       const BLSURFPlugin_Hypothesis::TSizeMap attractors = BLSURFPlugin_Hypothesis::GetAttractorEntries(hyp);
1206       BLSURFPlugin_Hypothesis::TSizeMap::const_iterator atIt = attractors.begin();
1207       for ( ; atIt != attractors.end(); ++atIt ) {
1208         if ( !atIt->second.empty() ) {
1209           GeomShape = entryToShape(atIt->first);
1210           GeomType  = GeomShape.ShapeType();
1211           // Group Management
1212           if (GeomType == TopAbs_COMPOUND){
1213             for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1214               if (it.Value().ShapeType() == TopAbs_FACE){
1215                 HasSizeMapOnFace = true;
1216                 createAttractorOnFace(it.Value(), atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1217               }
1218             }
1219           }
1220
1221           if (GeomType == TopAbs_FACE){
1222             HasSizeMapOnFace = true;
1223             createAttractorOnFace(GeomShape, atIt->second, _phySizeRel ? _phySize*diagonal : _phySize);
1224           }
1225   /*
1226           if (GeomType == TopAbs_EDGE){
1227             HasSizeMapOnEdge = true;
1228             HasSizeMapOnFace = true;
1229           EdgeId2SizeMap[TopoDS::Edge(GeomShape).HashCode(IntegerLast())] = atIt->second;
1230           }
1231           if (GeomType == TopAbs_VERTEX){
1232             HasSizeMapOnVertex = true;
1233             HasSizeMapOnEdge   = true;
1234             HasSizeMapOnFace   = true;
1235           VertexId2SizeMap[TopoDS::Vertex(GeomShape).HashCode(IntegerLast())] = atIt->second;
1236           }
1237   */
1238         }
1239       }
1240 //     }
1241
1242     // Class Attractors
1243     // temporary commented out for testing
1244     // TODO
1245     //  - Fill in the BLSURFPlugin_Hypothesis::TAttractorMap map in the hypothesis
1246     //  - Uncomment and complete this part to construct the attractors from the attractor shape and the passed parameters on each face of the map
1247     //  - To do this use the public methodss: SetParameters(several double parameters) and SetType(int type)
1248     //  OR, even better:
1249     //  - Construct the attractors with an empty dist. map in the hypothesis
1250     //  - build the map here for each face with an attractor set and only if the attractor shape as changed since the last call to _buildmap()
1251     //  -> define a bool _mapbuilt in the class that is set to false by default and set to true when calling _buildmap()  OK
1252
1253       theNbAttractors = 0;
1254     const BLSURFPlugin_Hypothesis::TAttractorMap class_attractors = BLSURFPlugin_Hypothesis::GetClassAttractorEntries(hyp);
1255     int key=-1;
1256     BLSURFPlugin_Hypothesis::TAttractorMap::const_iterator AtIt = class_attractors.begin();
1257     for ( ; AtIt != class_attractors.end(); ++AtIt ) {
1258       if ( !AtIt->second->Empty() ) {
1259         GeomShape = entryToShape(AtIt->first);
1260         if ( !SMESH_MesherHelper::IsSubShape( GeomShape, theGeomShape ))
1261           continue;
1262         AttShape = AtIt->second->GetAttractorShape();
1263         GeomType  = GeomShape.ShapeType();
1264         // Group Management
1265 //         if (GeomType == TopAbs_COMPOUND){
1266 //           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1267 //             if (it.Value().ShapeType() == TopAbs_FACE){
1268 //               HasAttractorOnFace = true;
1269 //               myAttractor = BLSURFPluginAttractor(GeomShape, AttShape);
1270 //             }
1271 //           }
1272 //         }
1273
1274         if (GeomType == TopAbs_FACE
1275           && (AttShape.ShapeType() == TopAbs_VERTEX
1276            || AttShape.ShapeType() == TopAbs_EDGE
1277            || AttShape.ShapeType() == TopAbs_WIRE
1278            || AttShape.ShapeType() == TopAbs_COMPOUND) ){
1279             HasSizeMapOnFace = true;
1280
1281             key = FacesWithSizeMap.Add(TopoDS::Face(GeomShape) );
1282
1283             FaceId2ClassAttractor[key].push_back( AtIt->second );
1284             ++theNbAttractors;
1285         }
1286         else{
1287           MESSAGE("Wrong shape type !!")
1288         }
1289
1290       }
1291     }
1292
1293
1294     //
1295     // Enforced Vertices
1296     //
1297     const BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap entryEnfVertexListMap = BLSURFPlugin_Hypothesis::GetAllEnforcedVerticesByFace(hyp);
1298     BLSURFPlugin_Hypothesis::TFaceEntryEnfVertexListMap::const_iterator enfIt = entryEnfVertexListMap.begin();
1299     for ( ; enfIt != entryEnfVertexListMap.end(); ++enfIt ) {
1300       if ( !enfIt->second.empty() ) {
1301         GeomShape = entryToShape(enfIt->first);
1302         if ( GeomShape.IsNull() )
1303         {
1304           createEnforcedVertexOnFace( GeomShape, enfIt->second );
1305         }
1306         // Group Management
1307         else if ( GeomShape.ShapeType() == TopAbs_COMPOUND)
1308         {
1309           for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()){
1310             if (it.Value().ShapeType() == TopAbs_FACE){
1311               HasSizeMapOnFace = true;
1312               createEnforcedVertexOnFace(it.Value(), enfIt->second);
1313             }
1314           }
1315         }
1316         else if ( GeomShape.ShapeType() == TopAbs_FACE)
1317         {
1318           HasSizeMapOnFace = true;
1319           createEnforcedVertexOnFace(GeomShape, enfIt->second);
1320         }
1321       }
1322     }
1323
1324     // Internal vertices
1325     bool useInternalVertexAllFaces = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFaces(hyp);
1326     if (useInternalVertexAllFaces) {
1327       std::string grpName = BLSURFPlugin_Hypothesis::GetInternalEnforcedVertexAllFacesGroup(hyp);
1328       gp_Pnt aPnt;
1329       TopExp_Explorer exp (theGeomShape, TopAbs_FACE);
1330       for (; exp.More(); exp.Next()){
1331         TopExp_Explorer exp_face (exp.Current(), TopAbs_VERTEX, TopAbs_EDGE);
1332         for (; exp_face.More(); exp_face.Next())
1333         {
1334           // Get coords of vertex
1335           // Check if current coords is already in enfVertexList
1336           // If coords not in enfVertexList, add new enfVertex
1337           aPnt = BRep_Tool::Pnt(TopoDS::Vertex(exp_face.Current()));
1338           BLSURFPlugin_Hypothesis::TEnfVertex* enfVertex = new BLSURFPlugin_Hypothesis::TEnfVertex();
1339           enfVertex->coords.push_back(aPnt.X());
1340           enfVertex->coords.push_back(aPnt.Y());
1341           enfVertex->coords.push_back(aPnt.Z());
1342           enfVertex->name = "";
1343           enfVertex->faceEntries.clear();
1344           enfVertex->geomEntry = "";
1345           enfVertex->grpName = grpName;
1346           enfVertex->vertex = TopoDS::Vertex( exp_face.Current() );
1347           _createEnforcedVertexOnFace( TopoDS::Face(exp.Current()),  aPnt, enfVertex);
1348           HasSizeMapOnFace = true;
1349         }
1350       }
1351     }
1352
1353     cadsurf_set_sizemap_iso_cad_face(css, size_on_surface, &_smp_phy_size);
1354
1355     if (HasSizeMapOnEdge){
1356       cadsurf_set_sizemap_iso_cad_edge(css, size_on_edge, &_smp_phy_size);
1357     }
1358     if (HasSizeMapOnVertex){
1359       cadsurf_set_sizemap_iso_cad_point(css, size_on_vertex, &_smp_phy_size);
1360     }
1361   }
1362
1363   // PERIODICITY
1364
1365    // reset vectors
1366    _preCadFacesIDsPeriodicityVector.clear();
1367    _preCadEdgesIDsPeriodicityVector.clear();
1368
1369   for (std::size_t i = 0; i<preCadFacesPeriodicityVector.size(); i++){
1370     createPreCadFacesPeriodicity(theGeomShape, preCadFacesPeriodicityVector[i]);
1371   }
1372
1373   const BLSURFPlugin_Hypothesis::TPreCadPeriodicityVector preCadEdgesPeriodicityVector = BLSURFPlugin_Hypothesis::GetPreCadEdgesPeriodicityVector(hyp);
1374
1375   for (std::size_t i = 0; i<preCadEdgesPeriodicityVector.size(); i++){
1376     createPreCadEdgesPeriodicity(theGeomShape, preCadEdgesPeriodicityVector[i]);
1377   }
1378 }
1379
1380 //================================================================================
1381 /*!
1382  * \brief Throws an exception if a parameter name is wrong
1383  */
1384 //================================================================================
1385
1386 void BLSURFPlugin_BLSURF::set_param(cadsurf_session_t *css,
1387                                     const char *       option_name,
1388                                     const char *       option_value)
1389 {
1390   status_t status = cadsurf_set_param(css, option_name, option_value );
1391
1392   if ( _hypothesis && _hypothesis->GetVerbosity() > _hypothesis->GetDefaultVerbosity() )
1393     cout << option_name << " = " << option_value << endl;
1394
1395   if ( status != MESHGEMS_STATUS_OK )
1396   {
1397     if ( status == MESHGEMS_STATUS_UNKNOWN_PARAMETER ) {
1398       throw SALOME_Exception
1399         ( SMESH_Comment("Invalid name of CADSURF parameter: ") << option_name );
1400     }
1401     else if ( status == MESHGEMS_STATUS_NOLICENSE )
1402       throw SALOME_Exception
1403         ( "No valid license available" );
1404     else
1405       throw SALOME_Exception
1406         ( SMESH_Comment("Either wrong name or unacceptable value of CADSURF parameter '")
1407           << option_name << "': " << option_value);
1408   }
1409 }
1410
1411 namespace
1412 {
1413   // --------------------------------------------------------------------------
1414   /*!
1415    * \brief Class correctly terminating usage of MG-CADSurf library at destruction
1416    */
1417   struct BLSURF_Cleaner
1418   {
1419     context_t *        _ctx;
1420     cadsurf_session_t* _css;
1421     cad_t *            _cad;
1422     dcad_t *           _dcad;
1423
1424     BLSURF_Cleaner(context_t *        ctx,
1425                    cadsurf_session_t* css=0,
1426                    cad_t *            cad=0,
1427                    dcad_t *           dcad=0)
1428       : _ctx ( ctx  ),
1429         _css ( css  ),
1430         _cad ( cad  ),
1431         _dcad( dcad )
1432     {
1433     }
1434     ~BLSURF_Cleaner()
1435     {
1436       Clean( /*exceptContext=*/false );
1437     }
1438     void Clean(const bool exceptContext)
1439     {
1440       if ( _css )
1441       {
1442         cadsurf_session_delete(_css); _css = 0;
1443
1444         // #if BLSURF_VERSION_LONG >= "3.1.1"
1445         // //     if(geo_sizemap_e)
1446         // //       distene_sizemap_delete(geo_sizemap_e);
1447         // //     if(geo_sizemap_f)
1448         // //       distene_sizemap_delete(geo_sizemap_f);
1449         //     if(iso_sizemap_p)
1450         //       distene_sizemap_delete(iso_sizemap_p);
1451         //     if(iso_sizemap_e)
1452         //       distene_sizemap_delete(iso_sizemap_e);
1453         //     if(iso_sizemap_f)
1454         //       distene_sizemap_delete(iso_sizemap_f);
1455         // 
1456         // //     if(clean_geo_sizemap_e)
1457         // //       distene_sizemap_delete(clean_geo_sizemap_e);
1458         // //     if(clean_geo_sizemap_f)
1459         // //       distene_sizemap_delete(clean_geo_sizemap_f);
1460         //     if(clean_iso_sizemap_p)
1461         //       distene_sizemap_delete(clean_iso_sizemap_p);
1462         //     if(clean_iso_sizemap_e)
1463         //       distene_sizemap_delete(clean_iso_sizemap_e);
1464         //     if(clean_iso_sizemap_f)
1465         //       distene_sizemap_delete(clean_iso_sizemap_f);
1466         // #endif
1467
1468         cad_delete(_cad); _cad = 0;
1469         dcad_delete(_dcad); _dcad = 0;
1470         if ( !exceptContext )
1471         {
1472           context_delete(_ctx); _ctx = 0;
1473         }
1474       }
1475     }
1476   };
1477
1478   // --------------------------------------------------------------------------
1479   // comparator to sort nodes and sub-meshes
1480   struct ShapeTypeCompare
1481   {
1482     // sort nodes by position in the following order:
1483     // SMDS_TOP_FACE=2, SMDS_TOP_EDGE=1, SMDS_TOP_VERTEX=0, SMDS_TOP_3DSPACE=3
1484     bool operator()( const SMDS_MeshNode* n1, const SMDS_MeshNode* n2 ) const
1485     {
1486       // NEW ORDER: nodes earlier added to sub-mesh are considered "less"
1487       return n1->getIdInShape() < n2->getIdInShape();
1488       // SMDS_TypeOfPosition pos1 = n1->GetPosition()->GetTypeOfPosition();
1489       // SMDS_TypeOfPosition pos2 = n2->GetPosition()->GetTypeOfPosition();
1490       // if ( pos1 == pos2 ) return 0;
1491       // if ( pos1 < pos2 || pos1 == SMDS_TOP_3DSPACE ) return 1;
1492       // return -1;
1493     }
1494     // sort sub-meshes in order: EDGE, VERTEX
1495     bool operator()( const SMESHDS_SubMesh* s1, const SMESHDS_SubMesh* s2 ) const
1496     {
1497       int isVertex1 = ( s1 && s1->NbElements() == 0 );
1498       int isVertex2 = ( s2 && s2->NbElements() == 0 );
1499       if ( isVertex1 == isVertex2 )
1500         return s1 < s2;
1501       return isVertex1 < isVertex2;
1502     }
1503   };
1504
1505   //================================================================================
1506   /*!
1507    * \brief Fills groups of nodes to be merged
1508    */
1509   //================================================================================
1510
1511   void getNodeGroupsToMerge( const SMESHDS_SubMesh*                smDS,
1512                              const TopoDS_Shape&                   shape,
1513                              SMESH_MeshEditor::TListOfListOfNodes& nodeGroupsToMerge)
1514   {
1515     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1516     switch ( shape.ShapeType() )
1517     {
1518     case TopAbs_VERTEX: {
1519       std::list< const SMDS_MeshNode* > nodes;
1520       while ( nIt->more() )
1521         nodes.push_back( nIt->next() );
1522       if ( nodes.size() > 1 )
1523         nodeGroupsToMerge.push_back( nodes );
1524       break;
1525     }
1526     case TopAbs_EDGE: {
1527       std::multimap< double, const SMDS_MeshNode* > u2node;
1528       const SMDS_EdgePosition* ePos;
1529       while ( nIt->more() )
1530       {
1531         const SMDS_MeshNode* n = nIt->next();
1532         if (( ePos = dynamic_cast< const SMDS_EdgePosition* >( n->GetPosition() )))
1533           u2node.insert( make_pair( ePos->GetUParameter(), n ));
1534       }
1535       if ( u2node.size() < 2 ) return;
1536
1537       //double tol = (( u2node.rbegin()->first - u2node.begin()->first ) / 20.) / u2node.size();
1538       Standard_Real f,l;
1539       BRep_Tool::Range( TopoDS::Edge( shape ), f,l );
1540       double tol = (( l - f ) / 20.) / u2node.size();
1541
1542       std::multimap< double, const SMDS_MeshNode* >::iterator un2, un1;
1543       for ( un2 = u2node.begin(), un1 = un2++; un2 != u2node.end(); un1 = un2++ )
1544       {
1545         if (( un2->first - un1->first ) <= tol )
1546         {
1547           std::list< const SMDS_MeshNode* > nodes;
1548           nodes.push_back( un1->second );
1549           while (( un2->first - un1->first ) <= tol )
1550           {
1551             nodes.push_back( un2->second );
1552             if ( ++un2 == u2node.end()) {
1553               --un2;
1554               break;
1555             }
1556           }
1557           // make nodes created on the boundary of viscous layer replace nodes created
1558           // by MG-CADSurf as their SMDS_Position is more correct
1559           nodes.sort( ShapeTypeCompare() );
1560           nodeGroupsToMerge.push_back( nodes );
1561         }
1562       }
1563       break;
1564     }
1565     default: ;
1566     }
1567     // SMESH_MeshEditor::TListOfListOfNodes::const_iterator nll = nodeGroupsToMerge.begin();
1568     // for ( ; nll != nodeGroupsToMerge.end(); ++nll )
1569     // {
1570     //   cout << "Merge ";
1571     //   const std::list< const SMDS_MeshNode* >& nl = *nll;
1572     //   std::list< const SMDS_MeshNode* >::const_iterator nIt = nl.begin();
1573     //   for ( ; nIt != nl.end(); ++nIt )
1574     //     cout << (*nIt) << " ";
1575     //   cout << endl;
1576     // }
1577     // cout << endl;
1578   }
1579
1580   //================================================================================
1581   /*!
1582    * \brief A temporary mesh used to compute mesh on a proxy FACE
1583    */
1584   //================================================================================
1585
1586   struct TmpMesh: public SMESH_Mesh
1587   {
1588     typedef std::map<const SMDS_MeshNode*, const SMDS_MeshNode*, TIDCompare > TN2NMap;
1589     TN2NMap     _tmp2origNN;
1590     TopoDS_Face _proxyFace;
1591
1592     TmpMesh()
1593     {
1594       _myMeshDS = new SMESHDS_Mesh( _id, true );
1595     }
1596     //--------------------------------------------------------------------------------
1597     /*!
1598      * \brief Creates a FACE bound by viscous layers and mesh each its EDGE with 1 segment
1599      */
1600     //--------------------------------------------------------------------------------
1601
1602     const TopoDS_Face& makeProxyFace( SMESH_ProxyMesh::Ptr& viscousMesh,
1603                                       const TopoDS_Face&    origFace)
1604     {
1605       SMESH_Mesh* origMesh = viscousMesh->GetMesh();
1606
1607       SMESH_MesherHelper helper( *origMesh );
1608       helper.SetSubShape( origFace );
1609       const bool hasSeam = helper.HasRealSeam();
1610
1611       // get data of nodes on inner boundary of viscous layers
1612       TError err;
1613       TSideVector wireVec = StdMeshers_FaceSide::GetFaceWires(origFace, *origMesh,
1614                                                               /*skipMediumNodes = */true,
1615                                                               err, &helper, viscousMesh );
1616       if ( err && err->IsKO() )
1617         throw *err.get(); // it should be caught at SMESH_subMesh
1618
1619       // proxy nodes and corresponding tmp VERTEXes
1620       std::vector<const SMDS_MeshNode*> origNodes;
1621       std::vector<TopoDS_Vertex>        tmpVertex;
1622
1623       // create a proxy FACE
1624       TopoDS_Face origFaceCopy = TopoDS::Face( origFace.EmptyCopied() );
1625       BRepBuilderAPI_MakeFace newFace( origFaceCopy );
1626       bool hasPCurves = false;
1627       for ( size_t iW = 0; iW != wireVec.size(); ++iW )
1628       {
1629         StdMeshers_FaceSidePtr& wireData = wireVec[iW];
1630         const UVPtStructVec&  wirePoints = wireData->GetUVPtStruct();
1631         if ( wirePoints.size() < 3 )
1632           continue;
1633
1634         BRepBuilderAPI_MakePolygon polygon;
1635         const size_t i0 = tmpVertex.size();
1636         for ( size_t iN = 0; iN < wirePoints.size(); ++iN )
1637         {
1638           polygon.Add( SMESH_TNodeXYZ( wirePoints[ iN ].node ));
1639           origNodes.push_back( wirePoints[ iN ].node );
1640           tmpVertex.push_back( polygon.LastVertex() );
1641
1642           // check presence of a pcurve
1643           checkPCurve( polygon, origFaceCopy, hasPCurves, &wirePoints[ iN-1 ] );
1644         }
1645         tmpVertex[ i0 ] = polygon.FirstVertex(); // polygon.LastVertex()==NULL for 1 vertex in wire
1646         polygon.Close();
1647         if ( !polygon.IsDone() )
1648           throw SALOME_Exception("BLSURFPlugin_BLSURF: BRepBuilderAPI_MakePolygon failed");
1649         TopoDS_Wire wire = polygon;
1650         if ( hasSeam )
1651           wire = updateSeam( wire, origNodes );
1652         newFace.Add( wire );
1653       }
1654       _proxyFace = newFace;
1655
1656       // set a new shape to mesh
1657       TopoDS_Compound auxCompoundToMesh;
1658       BRep_Builder shapeBuilder;
1659       shapeBuilder.MakeCompound( auxCompoundToMesh );
1660       shapeBuilder.Add( auxCompoundToMesh, _proxyFace );
1661       shapeBuilder.Add( auxCompoundToMesh, origMesh->GetShapeToMesh() );
1662
1663       ShapeToMesh( auxCompoundToMesh );
1664
1665
1666       // Make input mesh for MG-CADSurf: segments on EDGE's of newFace
1667
1668       // make nodes and fill in _tmp2origNN
1669       //
1670       SMESHDS_Mesh* tmpMeshDS = GetMeshDS();
1671       for ( size_t i = 0; i < origNodes.size(); ++i )
1672       {
1673         GetSubMesh( tmpVertex[i] )->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1674         if ( const SMDS_MeshNode* tmpN = SMESH_Algo::VertexNode( tmpVertex[i], tmpMeshDS ))
1675           _tmp2origNN.insert( _tmp2origNN.end(), make_pair( tmpN, origNodes[i] ));
1676         // else -- it can be a seam vertex replaced by updateSeam()
1677         //   throw SALOME_Exception("BLSURFPlugin_BLSURF: a proxy vertex not meshed");
1678       }
1679
1680       // make segments
1681       TopoDS_Vertex v1, v2;
1682       for ( TopExp_Explorer edge( _proxyFace, TopAbs_EDGE ); edge.More(); edge.Next() )
1683       {
1684         const TopoDS_Edge& E = TopoDS::Edge( edge.Current() );
1685         TopExp::Vertices( E, v1, v2 );
1686         const SMDS_MeshNode* n1 = SMESH_Algo::VertexNode( v1, tmpMeshDS );
1687         const SMDS_MeshNode* n2 = SMESH_Algo::VertexNode( v2, tmpMeshDS );
1688
1689         if ( SMDS_MeshElement* seg = tmpMeshDS->AddEdge( n1, n2 ))
1690           tmpMeshDS->SetMeshElementOnShape( seg, E );
1691       }
1692
1693       return _proxyFace;
1694     }
1695
1696     //--------------------------------------------------------------------------------
1697     /*!
1698      * \brief Add pcurve to the last edge of a wire
1699      */
1700     //--------------------------------------------------------------------------------
1701
1702     void checkPCurve( BRepBuilderAPI_MakePolygon& wire,
1703                       const TopoDS_Face&          face,
1704                       bool &                      hasPCurves,
1705                       const uvPtStruct *          wirePoints )
1706     {
1707       if ( hasPCurves )
1708         return;
1709       TopoDS_Edge edge = wire.Edge();
1710       if ( edge.IsNull() ) return;
1711       double f,l;
1712       if ( BRep_Tool::CurveOnSurface(edge, face, f, l))
1713       {
1714         hasPCurves = true;
1715         return;
1716       }
1717       gp_XY p1 = wirePoints[ 0 ].UV(), p2 = wirePoints[ 1 ].UV();
1718       Handle(Geom2d_Line) pcurve = new Geom2d_Line( p1, gp_Dir2d( p2 - p1 ));
1719       BRep_Builder().UpdateEdge( edge, Handle(Geom_Curve)(), Precision::Confusion() );
1720       BRep_Builder().UpdateEdge( edge, pcurve, face, Precision::Confusion() );
1721       BRep_Builder().Range( edge, 0, ( p2 - p1 ).Modulus() );
1722       // cout << "n1 = mesh.AddNode( " << p1.X()*10 << ", " << p1.Y() << ", 0 )" << endl
1723       //      << "n2 = mesh.AddNode( " << p2.X()*10 << ", " << p2.Y() << ", 0 )" << endl
1724       //      << "mesh.AddEdge( [ n1, n2 ] )" << endl;
1725     }
1726
1727     //--------------------------------------------------------------------------------
1728     /*!
1729      * \brief Replace coincident EDGEs with reversed copies.
1730      */
1731     //--------------------------------------------------------------------------------
1732
1733     TopoDS_Wire updateSeam( const TopoDS_Wire&                       wire,
1734                             const std::vector<const SMDS_MeshNode*>& nodesOfVertices )
1735     {
1736       BRepBuilderAPI_MakeWire newWire;
1737
1738       typedef NCollection_DataMap<SMESH_TLink, TopoDS_Edge, SMESH_TLink > TSeg2EdgeMap;
1739       TSeg2EdgeMap seg2EdgeMap;
1740
1741       TopoDS_Iterator edgeIt( wire );
1742       for ( int iSeg = 1; edgeIt.More(); edgeIt.Next(), ++iSeg )
1743       {
1744         SMESH_TLink link( nodesOfVertices[ iSeg-1 ], nodesOfVertices[ iSeg ]);
1745         TopoDS_Edge edge( TopoDS::Edge( edgeIt.Value() ));
1746
1747         TopoDS_Edge* edgeInMap = seg2EdgeMap.Bound( link, edge );
1748         bool            isSeam = ( *edgeInMap != edge );
1749         if ( isSeam )
1750         {
1751           edgeInMap->Reverse();
1752           edge = *edgeInMap;
1753         }
1754         newWire.Add( edge );
1755       }
1756       return newWire;
1757     }
1758
1759     //--------------------------------------------------------------------------------
1760     /*!
1761      * \brief Fill in the origMesh with faces computed by MG-CADSurf in this tmp mesh
1762      */
1763     //--------------------------------------------------------------------------------
1764
1765     void FillInOrigMesh( SMESH_Mesh&        origMesh,
1766                          const TopoDS_Face& origFace )
1767     {
1768       SMESH_MesherHelper helper( origMesh );
1769       helper.SetSubShape( origFace );
1770       helper.SetElementsOnShape( true );
1771
1772       SMESH_MesherHelper tmpHelper( *this );
1773       tmpHelper.SetSubShape( _proxyFace );
1774
1775       // iterate over tmp faces and copy them in origMesh
1776       const SMDS_MeshNode* nodes[27];
1777       const SMDS_MeshNode* nullNode = 0;
1778       double xyz[3];
1779       SMDS_FaceIteratorPtr fIt = GetMeshDS()->facesIterator(/*idInceasingOrder=*/true);
1780       while ( fIt->more() )
1781       {
1782         const SMDS_MeshElement* f = fIt->next();
1783         SMDS_ElemIteratorPtr nIt = f->nodesIterator();
1784         int nbN = 0;
1785         for ( ; nIt->more(); ++nbN )
1786         {
1787           const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
1788           TN2NMap::iterator n2nIt =
1789             _tmp2origNN.insert( _tmp2origNN.end(), make_pair( n, nullNode ));
1790           if ( !n2nIt->second ) {
1791             n->GetXYZ( xyz );
1792             gp_XY uv = tmpHelper.GetNodeUV( _proxyFace, n );
1793             n2nIt->second = helper.AddNode( xyz[0], xyz[1], xyz[2], uv.X(), uv.Y() );
1794           }
1795           nodes[ nbN ] = n2nIt->second;
1796         }
1797         switch( nbN ) {
1798         case 3: helper.AddFace( nodes[0], nodes[1], nodes[2] ); break;
1799           // case 6: helper.AddFace( nodes[0], nodes[1], nodes[2],
1800           //                         nodes[3], nodes[4], nodes[5]); break;
1801         case 4: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3] ); break;
1802         // case 9: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1803         //                         nodes[4], nodes[5], nodes[6], nodes[7], nodes[8]); break;
1804         // case 8: helper.AddFace( nodes[0], nodes[1], nodes[2], nodes[3],
1805         //                         nodes[4], nodes[5], nodes[6], nodes[7]); break;
1806         }
1807       }
1808     }
1809   };
1810
1811   /*!
1812    * \brief A structure holding an error description and a verbisity level
1813    */
1814   struct message_cb_user_data
1815   {
1816     std::string * _error;
1817     int           _verbosity;
1818     double *      _progress;
1819   };
1820
1821 } // namespace
1822
1823 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data);
1824 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
1825                   real *duu, real *duv, real *dvv, void *user_data);
1826 status_t message_cb(message_t *msg, void *user_data);
1827 status_t interrupt_cb(integer *interrupt_status, void *user_data);
1828
1829 //=============================================================================
1830 /*!
1831  *
1832  */
1833 //=============================================================================
1834
1835 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh& aMesh, const TopoDS_Shape& aShape)
1836 {
1837   // Fix problem with locales
1838   Kernel_Utils::Localizer aLocalizer;
1839
1840   this->SMESH_Algo::_progress = 1e-3; // prevent progress advancment while computing attractors
1841
1842   bool viscousLayersMade =
1843     ( aShape.ShapeType() == TopAbs_FACE &&
1844       StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( aShape ), aMesh ));
1845
1846   if ( !viscousLayersMade )
1847     if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1848       return false;
1849
1850   if ( _haveViscousLayers || viscousLayersMade )
1851   {
1852     // Compute viscous layers
1853
1854     TopTools_MapOfShape map;
1855     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1856     {
1857       const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1858       if ( !map.Add( F )) continue;
1859       SMESH_ProxyMesh::Ptr viscousMesh = StdMeshers_ViscousLayers2D::Compute( aMesh, F );
1860       if ( !viscousMesh )
1861         return false; // error in StdMeshers_ViscousLayers2D::Compute()
1862
1863       // Compute MG-CADSurf mesh on viscous layers
1864
1865       if ( viscousMesh->NbProxySubMeshes() > 0 )
1866       {
1867         TmpMesh tmpMesh;
1868         const TopoDS_Face& proxyFace = tmpMesh.makeProxyFace( viscousMesh, F );
1869         if ( !compute( tmpMesh, proxyFace, /*allowSubMeshClearing=*/false ))
1870           return false;
1871         tmpMesh.FillInOrigMesh( aMesh, F );
1872       }
1873     }
1874
1875     // Re-compute MG-CADSurf mesh on the rest faces if the mesh was cleared
1876
1877     for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
1878     {
1879       const TopoDS_Face& F = TopoDS::Face(face_iter.Current());
1880       SMESH_subMesh* fSM = aMesh.GetSubMesh( F );
1881       if ( fSM->IsMeshComputed() ) continue;
1882
1883       if ( !compute( aMesh, aShape, /*allowSubMeshClearing=*/true ))
1884         return false;
1885       break;
1886     }
1887   }
1888   return true;
1889 }
1890
1891 //=============================================================================
1892 /*!
1893  *
1894  */
1895 //=============================================================================
1896
1897 bool BLSURFPlugin_BLSURF::compute(SMESH_Mesh&         aMesh,
1898                                   const TopoDS_Shape& aShape,
1899                                   bool                allowSubMeshClearing)
1900 {
1901   /* create a distene context (generic object) */
1902   status_t status = STATUS_ERROR;
1903
1904   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
1905   SMESH_MesherHelper helper( aMesh ), helperWithShape( aMesh );
1906   myHelper = theHelper = & helperWithShape;
1907   // do not call helper.IsQuadraticSubMesh() because sub-meshes
1908   // may be cleaned and helper.myTLinkNodeMap gets invalid in such a case
1909   bool haveQuadraticSubMesh = helperWithShape.IsQuadraticSubMesh( aShape );
1910   bool quadraticSubMeshAndViscousLayer = false;
1911   bool needMerge = false;
1912   typedef set< SMESHDS_SubMesh*, ShapeTypeCompare > TSubMeshSet;
1913   TSubMeshSet edgeSubmeshes;
1914   TSubMeshSet& mergeSubmeshes = edgeSubmeshes;
1915
1916   TopTools_IndexedMapOfShape pmap, emap, fmap;
1917
1918   TopTools_IndexedDataMapOfShapeListOfShape e2ffmap;
1919   TopExp::MapShapesAndAncestors( aShape, TopAbs_EDGE, TopAbs_FACE, e2ffmap );
1920
1921   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
1922 #ifndef WIN32
1923   feclearexcept( FE_ALL_EXCEPT );
1924   int oldFEFlags = fedisableexcept( FE_ALL_EXCEPT );
1925 #endif
1926
1927   context_t *ctx =  context_new();
1928
1929   /* Set the message callback in the working context */
1930   message_cb_user_data mcud;
1931   mcud._error     = & this->SMESH_Algo::_comment;
1932   mcud._progress  = & this->SMESH_Algo::_progress;
1933   mcud._verbosity =
1934     _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
1935   context_set_message_callback(ctx, message_cb, &mcud);
1936
1937   /* set the interruption callback */
1938   _compute_canceled = false;
1939   context_set_interrupt_callback(ctx, interrupt_cb, this);
1940
1941   /* create the CAD object we will work on. It is associated to the context ctx. */
1942   cad_t *c     = cad_new(ctx);
1943   dcad_t *dcad = dcad_new(c);
1944
1945   // To enable multithreading
1946   cad_set_thread_safety(c, 1);
1947
1948   /* Now fill the CAD object with data from your CAD
1949    * environement. This is the most complex part of a successfull
1950    * integration.
1951    */
1952
1953   // PreCAD
1954
1955   cadsurf_session_t *css = cadsurf_session_new(ctx);
1956
1957   // an object that correctly deletes all cadsurf objects at destruction
1958   BLSURF_Cleaner cleaner( ctx,css,c,dcad );
1959
1960   SetParameters(_hypothesis, css, aShape);
1961
1962   haveQuadraticSubMesh = haveQuadraticSubMesh || (_hypothesis != NULL && _hypothesis->GetQuadraticMesh());
1963   helper.SetIsQuadratic( haveQuadraticSubMesh );
1964
1965   // To remove as soon as quadratic mesh is allowed - BEGIN
1966   // GDD: Viscous layer is not allowed with quadratic mesh
1967   if (_haveViscousLayers && haveQuadraticSubMesh ) {
1968     quadraticSubMeshAndViscousLayer = true;
1969     _haveViscousLayers = !haveQuadraticSubMesh;
1970     _comment += "Warning: Viscous layer is not possible with a quadratic mesh, it is ignored.";
1971     error(COMPERR_WARNING, _comment);
1972   }
1973   // To remove as soon as quadratic mesh is allowed - END
1974
1975   // needed to prevent the opencascade memory managmement from freeing things
1976   vector<Handle(Geom2d_Curve)> curves;
1977   vector<Handle(Geom_Surface)> surfaces;
1978
1979   emap.Clear();
1980   pmap.Clear();
1981   FaceId2PythonSmp.clear();
1982   EdgeId2PythonSmp.clear();
1983   VertexId2PythonSmp.clear();
1984
1985   /****************************************************************************************
1986                                           FACES
1987   *****************************************************************************************/
1988   int iface = 0;
1989   string bad_end = "return";
1990   int faceKey = -1;
1991   TopTools_IndexedMapOfShape _map;
1992   TopExp::MapShapes(aShape,TopAbs_VERTEX,_map);
1993   int ienf = _map.Extent();
1994
1995   assert(Py_IsInitialized());
1996   PyGILState_STATE gstate;
1997
1998   string theSizeMapStr;
1999
2000   for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2001   {
2002     TopoDS_Face f = TopoDS::Face(face_iter.Current());
2003
2004     SMESH_subMesh* fSM = aMesh.GetSubMesh( f );
2005     if ( !fSM->IsEmpty() ) continue; // skip already meshed FACE with viscous layers
2006
2007     // make INTERNAL face oriented FORWARD (issue 0020993)
2008     if (f.Orientation() != TopAbs_FORWARD && f.Orientation() != TopAbs_REVERSED )
2009       f.Orientation(TopAbs_FORWARD);
2010
2011     iface = fmap.Add(f);
2012
2013     surfaces.push_back(BRep_Tool::Surface(f));
2014
2015     /* create an object representing the face for cadsurf */
2016     /* where face_id is an integer identifying the face.
2017      * surf_function is the function that defines the surface
2018      * (For this face, it will be called by cadsurf with your_face_object_ptr
2019      * as last parameter.
2020      */
2021     cad_face_t *fce = cad_face_new(c, iface, surf_fun, surfaces.back().get());
2022
2023     /* by default a face has no tag (color).
2024        The following call sets it to the same value as the Geom module ID : */
2025     int faceTag = meshDS->ShapeToIndex(f);
2026     faceTag = BLSURFPlugin_Hypothesis::GetHyperPatchTag( faceTag, _hypothesis );
2027     cad_face_set_tag(fce, faceTag);
2028
2029     /* Set face orientation (optional if you want a well oriented output mesh)*/
2030     if(f.Orientation() != TopAbs_FORWARD)
2031       cad_face_set_orientation(fce, CAD_ORIENTATION_REVERSED);
2032     else
2033       cad_face_set_orientation(fce, CAD_ORIENTATION_FORWARD);
2034
2035     if (HasSizeMapOnFace /*&& !use_precad*/) //22903: use_precad seems not to interfere
2036     {
2037       // -----------------
2038       // Classic size map
2039       // -----------------
2040       faceKey = FacesWithSizeMap.FindIndex(f);
2041
2042
2043       if (FaceId2SizeMap.find(faceKey)!=FaceId2SizeMap.end())
2044       {
2045         theSizeMapStr = FaceId2SizeMap[faceKey];
2046         // check if function ends with "return"
2047         if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2048           continue;
2049         // Expr To Python function, verification is performed at validation in GUI
2050         gstate = PyGILState_Ensure();
2051         PyObject * obj = NULL;
2052         obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2053         Py_DECREF(obj);
2054         PyObject * func = NULL;
2055         func = PyObject_GetAttrString(main_mod, "f");
2056         FaceId2PythonSmp[iface]=func;
2057         FaceId2SizeMap.erase(faceKey);
2058         PyGILState_Release(gstate);
2059       }
2060
2061       // Specific size map = Attractor
2062       std::map<int,std::vector<double> >::iterator attractor_iter = FaceId2AttractorCoords.begin();
2063
2064       for (; attractor_iter != FaceId2AttractorCoords.end(); ++attractor_iter) {
2065         if (attractor_iter->first == faceKey)
2066         {
2067           double xyzCoords[3]  = {attractor_iter->second[2],
2068                                   attractor_iter->second[3],
2069                                   attractor_iter->second[4]};
2070
2071           gp_Pnt P(xyzCoords[0],xyzCoords[1],xyzCoords[2]);
2072           BRepClass_FaceClassifier scl(f,P,1e-7);
2073           scl.Perform(f, P, 1e-7);
2074           TopAbs_State result = scl.State();
2075           if ( result == TopAbs_OUT )
2076             MESSAGE("Point is out of face: node is not created");
2077           if ( result == TopAbs_UNKNOWN )
2078             MESSAGE("Point position on face is unknown: node is not created");
2079           if ( result == TopAbs_ON )
2080             MESSAGE("Point is on border of face: node is not created");
2081           if ( result == TopAbs_IN )
2082           {
2083             // Point is inside face and not on border
2084             double uvCoords[2] = {attractor_iter->second[0],attractor_iter->second[1]};
2085             ienf++;
2086             cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2087             cad_point_set_tag(point_p, ienf);
2088           }
2089           FaceId2AttractorCoords.erase(faceKey);
2090         }
2091       }
2092
2093       // -----------------
2094       // Class Attractors
2095       // -----------------
2096       TId2ClsAttractorVec::iterator clAttractor_iter = FaceId2ClassAttractor.find(faceKey);
2097       if (clAttractor_iter != FaceId2ClassAttractor.end()){
2098         std::vector< BLSURFPlugin_Attractor* > & attVec = clAttractor_iter->second;
2099         for ( size_t i = 0; i < attVec.size(); ++i )
2100           if ( !attVec[i]->IsMapBuilt() ) {
2101             std::cout<<"Compute " << theNbAttractors-- << "-th attractor" <<std::endl;
2102             attVec[i]->BuildMap();
2103           }
2104         FaceIndex2ClassAttractor[iface].swap( attVec );
2105         FaceId2ClassAttractor.erase(clAttractor_iter);
2106       }
2107     } // if (HasSizeMapOnFace && !use_precad)
2108
2109     // ------------------
2110     // Enforced Vertices
2111     // ------------------
2112     faceKey = FacesWithEnforcedVertices.FindIndex(f);
2113     std::map<int,BLSURFPlugin_Hypothesis::TEnfVertexCoordsList >::const_iterator evmIt = FaceId2EnforcedVertexCoords.find(faceKey);
2114     if (evmIt != FaceId2EnforcedVertexCoords.end())
2115     {
2116       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList evl = evmIt->second;
2117       BLSURFPlugin_Hypothesis::TEnfVertexCoordsList::const_iterator evlIt = evl.begin();
2118       for (; evlIt != evl.end(); ++evlIt)
2119       {
2120         double uvCoords[2] = { evlIt->at(0), evlIt->at(1) };
2121         ienf++;
2122         cad_point_t* point_p = cad_point_new(fce, ienf, uvCoords);
2123         int tag = 0;
2124         BLSURFPlugin_Hypothesis::TEnfVertexCoords xyzCoords;
2125         xyzCoords.push_back(evlIt->at(2));
2126         xyzCoords.push_back(evlIt->at(3));
2127         xyzCoords.push_back(evlIt->at(4));
2128         std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(xyzCoords);
2129         if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end() &&
2130             !enfCoordsIt->second.empty() )
2131         {
2132           // to merge nodes of an INTERNAL vertex belonging to several faces
2133           TopoDS_Vertex     v = (*enfCoordsIt->second.begin() )->vertex;
2134           if ( v.IsNull() ) v = (*enfCoordsIt->second.rbegin())->vertex;
2135           if ( !v.IsNull() && meshDS->ShapeToIndex( v ) > 0 )
2136           {
2137             tag = pmap.Add( v );
2138             SMESH_subMesh* vSM = aMesh.GetSubMesh( v );
2139             vSM->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2140             mergeSubmeshes.insert( vSM->GetSubMeshDS() );
2141             // //if ( tag != pmap.Extent() )
2142             // needMerge = true;
2143           }
2144         }
2145         if ( tag == 0 ) tag = ienf;
2146         cad_point_set_tag(point_p, tag);
2147       }
2148       FaceId2EnforcedVertexCoords.erase(faceKey);
2149
2150     }
2151
2152     /****************************************************************************************
2153                                            EDGES
2154                         now create the edges associated to this face
2155     *****************************************************************************************/
2156     int edgeKey = -1;
2157     for (TopExp_Explorer edge_iter(f,TopAbs_EDGE);edge_iter.More();edge_iter.Next())
2158     {
2159       TopoDS_Edge e = TopoDS::Edge(edge_iter.Current());
2160       int ic = emap.FindIndex(e);
2161       if (ic <= 0)
2162         ic = emap.Add(e);
2163
2164       double tmin,tmax;
2165       curves.push_back(BRep_Tool::CurveOnSurface(e, f, tmin, tmax));
2166
2167       if (HasSizeMapOnEdge){
2168         edgeKey = EdgesWithSizeMap.FindIndex(e);
2169         if (EdgeId2SizeMap.find(edgeKey)!=EdgeId2SizeMap.end())
2170         {
2171           theSizeMapStr = EdgeId2SizeMap[edgeKey];
2172           if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2173             continue;
2174           // Expr To Python function, verification is performed at validation in GUI
2175           gstate = PyGILState_Ensure();
2176           PyObject * obj = NULL;
2177           obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2178           Py_DECREF(obj);
2179           PyObject * func = NULL;
2180           func = PyObject_GetAttrString(main_mod, "f");
2181           EdgeId2PythonSmp[ic]=func;
2182           EdgeId2SizeMap.erase(edgeKey);
2183           PyGILState_Release(gstate);
2184         }
2185       }
2186       /* data of nodes existing on the edge */
2187       StdMeshers_FaceSidePtr nodeData;
2188       SMESH_subMesh* sm = aMesh.GetSubMesh( e );
2189       if ( !sm->IsEmpty() )
2190       {
2191         // SMESH_subMeshIteratorPtr subsmIt = sm->getDependsOnIterator( /*includeSelf=*/true,
2192         //                                                              /*complexFirst=*/false);
2193         // while ( subsmIt->more() )
2194         //   edgeSubmeshes.insert( subsmIt->next()->GetSubMeshDS() );
2195         edgeSubmeshes.insert( sm->GetSubMeshDS() );
2196
2197         nodeData.reset( new StdMeshers_FaceSide( f, e, &aMesh, /*isForwrd = */true,
2198                                                  /*ignoreMedium=*/haveQuadraticSubMesh));
2199         if ( nodeData->MissVertexNode() )
2200           return error(COMPERR_BAD_INPUT_MESH,"No node on vertex");
2201
2202         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2203         if ( !nodeDataVec.empty() )
2204         {
2205           if ( Abs( nodeDataVec[0].param - tmin ) > Abs( nodeDataVec.back().param - tmin ))
2206           {
2207             nodeData->Reverse();
2208             nodeData->GetUVPtStruct(); // nodeData recomputes nodeDataVec
2209           }
2210           // tmin and tmax can change in case of viscous layer on an adjacent edge
2211           tmin = nodeDataVec.front().param;
2212           tmax = nodeDataVec.back().param;
2213         }
2214         else
2215         {
2216           cout << "---------------- Invalid nodeData" << endl;
2217           nodeData.reset();
2218         }
2219       }
2220
2221       /* attach the edge to the current cadsurf face */
2222       cad_edge_t *edg = cad_edge_new(fce, ic, tmin, tmax, curv_fun, curves.back().get());
2223
2224       /* by default an edge has no tag (color).
2225          The following call sets it to the same value as the edge_id : */
2226       // IMP23368. Do not set tag to an EDGE shared by FACEs of a hyper-patch
2227       bool isInHyperPatch = false;
2228       {
2229         std::set< int > faceTags, faceIDs;
2230         TopTools_ListIteratorOfListOfShape fIt( e2ffmap.FindFromKey( e ));
2231         for ( ; fIt.More(); fIt.Next() )
2232         {
2233           int faceTag = meshDS->ShapeToIndex( fIt.Value() );
2234           if ( !faceIDs.insert( faceTag ).second )
2235             continue; // a face encounters twice for a seam edge
2236           int hpTag   = BLSURFPlugin_Hypothesis::GetHyperPatchTag( faceTag, _hypothesis );
2237           if ( !faceTags.insert( hpTag ).second )
2238           {
2239             isInHyperPatch = true;
2240             break;
2241           }
2242         }
2243       }
2244       if ( !isInHyperPatch )
2245         cad_edge_set_tag(edg, ic);
2246
2247       /* by default, an edge does not necessalry appear in the resulting mesh,
2248          unless the following property is set :
2249       */
2250       cad_edge_set_property(edg, EDGE_PROPERTY_SOFT_REQUIRED);
2251
2252       /* by default an edge is a boundary edge */
2253       if (e.Orientation() == TopAbs_INTERNAL)
2254         cad_edge_set_property(edg, EDGE_PROPERTY_INTERNAL);
2255
2256       // pass existing nodes of sub-meshes to MG-CADSurf
2257       if ( nodeData )
2258       {
2259         const std::vector<UVPtStruct>& nodeDataVec = nodeData->GetUVPtStruct();
2260         const int                      nbNodes     = nodeDataVec.size();
2261
2262         dcad_edge_discretization_t *dedge;
2263         dcad_get_edge_discretization(dcad, edg, &dedge);
2264         dcad_edge_discretization_set_vertex_count( dedge, nbNodes );
2265
2266         // cout << endl << " EDGE " << ic << endl;
2267         // cout << "tmin = "<<tmin << ", tmax = "<< tmax << endl;
2268         for ( int iN = 0; iN < nbNodes; ++iN )
2269         {
2270           const UVPtStruct& nData = nodeDataVec[ iN ];
2271           double t                = nData.param;
2272           real uv[2]              = { nData.u, nData.v };
2273           SMESH_TNodeXYZ nXYZ( nData.node );
2274           // cout << "\tt = " << t
2275           //      << "\t uv = ( " << uv[0] << ","<< uv[1] << " ) "
2276           //      << "\t u = " << nData.param
2277           //      << "\t ID = " << nData.node->GetID() << endl;
2278           dcad_edge_discretization_set_vertex_coordinates( dedge, iN+1, t, uv, nXYZ.ChangeData() );
2279         }
2280         TopoDS_Shape v = helper.GetSubShapeByNode( nodeDataVec[0].node, meshDS );
2281         if ( !v.IsNull() && v.ShapeType() == TopAbs_VERTEX )
2282           dcad_edge_discretization_set_vertex_tag( dedge, 1, pmap.Add( v ));
2283
2284         v = helper.GetSubShapeByNode( nodeDataVec.back().node, meshDS );
2285         if ( !v.IsNull() && v.ShapeType() == TopAbs_VERTEX )
2286           dcad_edge_discretization_set_vertex_tag( dedge, nbNodes, pmap.Add( v ));
2287
2288         dcad_edge_discretization_set_property(dedge, DISTENE_DCAD_PROPERTY_REQUIRED);
2289       }
2290
2291       /****************************************************************************************
2292                                       VERTICES
2293       *****************************************************************************************/
2294
2295       int npts = 0;
2296       int ip1, ip2, *ip;
2297       gp_Pnt2d e0 = curves.back()->Value(tmin);
2298       gp_Pnt ee0 = surfaces.back()->Value(e0.X(), e0.Y());
2299       Standard_Real d1=0,d2=0;
2300
2301       int vertexKey = -1;
2302       for (TopExp_Explorer ex_edge(e ,TopAbs_VERTEX); ex_edge.More(); ex_edge.Next()) {
2303         TopoDS_Vertex v = TopoDS::Vertex(ex_edge.Current());
2304         ++npts;
2305         if (npts == 1){
2306           ip = &ip1;
2307           d1 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2308         } else {
2309           ip = &ip2;
2310           d2 = ee0.SquareDistance(BRep_Tool::Pnt(v));
2311         }
2312         *ip = pmap.FindIndex(v);
2313         if(*ip <= 0) {
2314           *ip = pmap.Add(v);
2315           // SMESH_subMesh* sm = aMesh.GetSubMesh(v);
2316           // if ( sm->IsMeshComputed() )
2317           //   edgeSubmeshes.insert( sm->GetSubMeshDS() );
2318         }
2319
2320 //        std::string aFileName = "fmap_vertex_";
2321 //        aFileName.append(val_to_string(*ip));
2322 //        aFileName.append(".brep");
2323 //        BRepTools::Write(v,aFileName.c_str());
2324
2325         if (HasSizeMapOnVertex){
2326           vertexKey = VerticesWithSizeMap.FindIndex(v);
2327           if (VertexId2SizeMap.find(vertexKey)!=VertexId2SizeMap.end()){
2328             theSizeMapStr = VertexId2SizeMap[vertexKey];
2329             if (theSizeMapStr.find(bad_end) == (theSizeMapStr.size()-bad_end.size()-1))
2330               continue;
2331             // Expr To Python function, verification is performed at validation in GUI
2332             gstate = PyGILState_Ensure();
2333             PyObject * obj = NULL;
2334             obj= PyRun_String(theSizeMapStr.c_str(), Py_file_input, main_dict, NULL);
2335             Py_DECREF(obj);
2336             PyObject * func = NULL;
2337             func = PyObject_GetAttrString(main_mod, "f");
2338             VertexId2PythonSmp[*ip]=func;
2339             VertexId2SizeMap.erase(vertexKey);   // do not erase if using a vector
2340             PyGILState_Release(gstate);
2341           }
2342         }
2343       }
2344       if (npts != 2) {
2345         // should not happen
2346         MESSAGE("An edge does not have 2 extremities.");
2347       } else {
2348         if (d1 < d2) {
2349           // This defines the curves extremity connectivity
2350           cad_edge_set_extremities(edg, ip1, ip2);
2351           /* set the tag (color) to the same value as the extremity id : */
2352           cad_edge_set_extremities_tag(edg, ip1, ip2);
2353         }
2354         else {
2355           cad_edge_set_extremities(edg, ip2, ip1);
2356           cad_edge_set_extremities_tag(edg, ip2, ip1);
2357         }
2358       }
2359     } // for edge
2360   } //for face
2361
2362   // Clear mesh from already meshed edges if possible else
2363   // remember that merge is needed
2364   TSubMeshSet::iterator smIt = edgeSubmeshes.begin();
2365   for ( ; smIt != edgeSubmeshes.end(); ++smIt ) // loop on already meshed EDGEs
2366   {
2367     SMESHDS_SubMesh* smDS = *smIt;
2368     if ( !smDS ) continue;
2369     SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2370     if ( nIt->more() )
2371     {
2372       const SMDS_MeshNode* n = nIt->next();
2373       if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
2374       {
2375         needMerge = true; // to correctly sew with viscous mesh
2376         // add existing medium nodes to helper
2377         if ( aMesh.NbEdges( ORDER_QUADRATIC ) > 0 )
2378         {
2379           SMDS_ElemIteratorPtr edgeIt = smDS->GetElements();
2380           while ( edgeIt->more() )
2381             helper.AddTLinks( static_cast<const SMDS_MeshEdge*>(edgeIt->next()));
2382         }
2383         continue;
2384       }
2385     }
2386     if ( allowSubMeshClearing )
2387     {
2388       SMDS_ElemIteratorPtr eIt = smDS->GetElements();
2389       while ( eIt->more() ) meshDS->RemoveFreeElement( eIt->next(), 0 );
2390       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2391       while ( nIt->more() ) meshDS->RemoveFreeNode( nIt->next(), 0 );
2392       smDS->Clear();
2393     }
2394     else
2395     {
2396       needMerge = true;
2397     }
2398   }
2399
2400   ///////////////////////
2401   // PERIODICITY       //
2402   ///////////////////////
2403
2404   if (! _preCadFacesIDsPeriodicityVector.empty())
2405   {
2406     for (std::size_t i=0; i < _preCadFacesIDsPeriodicityVector.size(); i++){
2407       std::vector<int> theFace1_ids = _preCadFacesIDsPeriodicityVector[i].shape1IDs;
2408       std::vector<int> theFace2_ids = _preCadFacesIDsPeriodicityVector[i].shape2IDs;
2409       int* theFace1_ids_c = &theFace1_ids[0];
2410       int* theFace2_ids_c = &theFace2_ids[0];
2411       std::ostringstream o;
2412       o << "_preCadFacesIDsPeriodicityVector[" << i << "] = [";
2413       for (std::size_t j=0; j < theFace1_ids.size(); j++)
2414         o << theFace1_ids[j] << ", ";
2415       o << "], [";
2416       for (std::size_t j=0; j < theFace2_ids.size(); j++)
2417         o << theFace2_ids[j] << ", ";
2418       o << "]";
2419       // if ( _hypothesis->GetVerbosity() > _hypothesis->GetDefaultVerbosity() )
2420       //   cout << o.str() << endl;
2421       if (_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2422       {
2423         // If no source points, call periodicity without transformation function
2424         meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2425         status = cad_add_face_multiple_periodicity_with_transformation_function(c, theFace1_ids_c, theFace1_ids.size(),
2426                                                                                 theFace2_ids_c, theFace2_ids.size(), periodicity_transformation, NULL);
2427         if(status != STATUS_OK)
2428           cout << "cad_add_face_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2429       }
2430       else
2431       {
2432         // get the transformation vertices
2433         double* theSourceVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2434         double* theTargetVerticesCoords_c = &_preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2435         int nbSourceVertices = _preCadFacesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2436         int nbTargetVertices = _preCadFacesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2437
2438         status = cad_add_face_multiple_periodicity_with_transformation_function_by_points(c, theFace1_ids_c, theFace1_ids.size(),
2439                                                                                           theFace2_ids_c, theFace2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2440         if(status != STATUS_OK)
2441           cout << "cad_add_face_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2442       }
2443     }
2444   }
2445
2446   if (! _preCadEdgesIDsPeriodicityVector.empty())
2447   {
2448     for (std::size_t i=0; i < _preCadEdgesIDsPeriodicityVector.size(); i++){
2449       std::vector<int> theEdge1_ids = _preCadEdgesIDsPeriodicityVector[i].shape1IDs;
2450       std::vector<int> theEdge2_ids = _preCadEdgesIDsPeriodicityVector[i].shape2IDs;
2451       // Use the address of the first element of the vector to initialize the array
2452       int* theEdge1_ids_c = &theEdge1_ids[0];
2453       int* theEdge2_ids_c = &theEdge2_ids[0];
2454
2455       std::ostringstream o;
2456       o << "_preCadEdgesIDsPeriodicityVector[" << i << "] = [";
2457       for (std::size_t j=0; j < theEdge1_ids.size(); j++)
2458         o << theEdge1_ids[j] << ", ";
2459       o << "], [";
2460       for (std::size_t j=0; j < theEdge2_ids.size(); j++)
2461         o << theEdge2_ids[j] << ", ";
2462       o << "]";
2463       // if ( _hypothesis->GetVerbosity() > _hypothesis->GetDefaultVerbosity() )
2464       //   cout << o.str() << endl;
2465
2466       if (_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.empty())
2467       {
2468         // If no source points, call periodicity without transformation function
2469         meshgems_cad_periodicity_transformation_t periodicity_transformation = NULL;
2470         status = cad_add_edge_multiple_periodicity_with_transformation_function(c, theEdge1_ids_c, theEdge1_ids.size(),
2471                                                                                 theEdge2_ids_c, theEdge2_ids.size(), periodicity_transformation, NULL);
2472         if(status != STATUS_OK)
2473           cout << "cad_add_edge_multiple_periodicity_with_transformation_function failed with error code " << status << "\n";
2474       }
2475       else
2476       {
2477         // get the transformation vertices
2478         double* theSourceVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords[0];
2479         double* theTargetVerticesCoords_c = &_preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords[0];
2480         int nbSourceVertices = _preCadEdgesIDsPeriodicityVector[i].theSourceVerticesCoords.size()/3;
2481         int nbTargetVertices = _preCadEdgesIDsPeriodicityVector[i].theTargetVerticesCoords.size()/3;
2482
2483         status = cad_add_edge_multiple_periodicity_with_transformation_function_by_points(c, theEdge1_ids_c, theEdge1_ids.size(),
2484                                                                                           theEdge2_ids_c, theEdge2_ids.size(), theSourceVerticesCoords_c, nbSourceVertices, theTargetVerticesCoords_c, nbTargetVertices);
2485         if(status != STATUS_OK)
2486           cout << "cad_add_edge_multiple_periodicity_with_transformation_function_by_points failed with error code " << status << "\n";
2487       }
2488     }
2489   }
2490
2491   
2492   // TODO: be able to use a mesh in input.
2493   // See imsh usage in Products/templates/mg-cadsurf_template_common.cpp
2494   // => cadsurf_set_mesh
2495     
2496   // Use the original dcad
2497   cadsurf_set_dcad(css, dcad);
2498
2499   // Use the original cad
2500   cadsurf_set_cad(css, c);
2501
2502   std::cout << std::endl;
2503   std::cout << "Beginning of Surface Mesh generation" << std::endl;
2504   std::cout << std::endl;
2505
2506   try {
2507     OCC_CATCH_SIGNALS;
2508
2509     status = cadsurf_compute_mesh(css);
2510
2511   }
2512   catch ( std::exception& exc ) {
2513     _comment += exc.what();
2514   }
2515   catch (Standard_Failure& ex) {
2516     _comment += ex.DynamicType()->Name();
2517     if ( ex.GetMessageString() && strlen( ex.GetMessageString() )) {
2518       _comment += ": ";
2519       _comment += ex.GetMessageString();
2520     }
2521   }
2522   catch (...) {
2523     if ( _comment.empty() )
2524       _comment = "Exception in cadsurf_compute_mesh()";
2525   }
2526
2527   std::cout << std::endl;
2528   std::cout << "End of Surface Mesh generation" << std::endl;
2529   std::cout << std::endl;
2530
2531   mesh_t *msh = NULL;
2532   cadsurf_get_mesh(css, &msh);
2533   if(!msh){
2534     /* release the mesh object */
2535     cadsurf_regain_mesh(css, msh);
2536     return error(_comment);
2537   }
2538
2539   std::string GMFFileName = BLSURFPlugin_Hypothesis::GetDefaultGMFFile();
2540   if (_hypothesis)
2541     GMFFileName = _hypothesis->GetGMFFile();
2542   if (GMFFileName != "") {
2543     bool asciiFound  = (GMFFileName.find(".mesh", GMFFileName.length()-5) != std::string::npos);
2544     bool binaryFound = (GMFFileName.find(".meshb",GMFFileName.length()-6) != std::string::npos);
2545     if (!asciiFound && !binaryFound)
2546       GMFFileName.append(".mesh");
2547     mesh_write_mesh(msh, GMFFileName.c_str());
2548   }
2549
2550   /* retrieve mesh data (see meshgems/mesh.h) */
2551   integer nv, ne, nt, nq, vtx[4], tag, nb_tag;
2552   integer *evedg, *evtri, *evquad, *tags_buff, type;
2553   real xyz[3];
2554
2555   mesh_get_vertex_count(msh, &nv);
2556   mesh_get_edge_count(msh, &ne);
2557   mesh_get_triangle_count(msh, &nt);
2558   mesh_get_quadrangle_count(msh, &nq);
2559
2560   evedg  = (integer *)mesh_calloc_generic_buffer(msh);
2561   evtri  = (integer *)mesh_calloc_generic_buffer(msh);
2562   evquad = (integer *)mesh_calloc_generic_buffer(msh);
2563   tags_buff = (integer*)mesh_calloc_generic_buffer(msh);
2564
2565   std::vector<const SMDS_MeshNode*> nodes(nv+1);
2566   std::vector<bool>                  tags(nv+1);
2567
2568   /* enumerated vertices */
2569   for(int iv=1;iv<=nv;iv++) {
2570     mesh_get_vertex_coordinates(msh, iv, xyz);
2571     mesh_get_vertex_tag(msh, iv, &tag);
2572     // Issue 0020656. Use vertex coordinates
2573     nodes[iv] = NULL;
2574     if ( tag > 0 && tag <= pmap.Extent() ) {
2575       TopoDS_Vertex v = TopoDS::Vertex(pmap(tag));
2576       double tol = BRep_Tool::Tolerance( v );
2577       gp_Pnt p = BRep_Tool::Pnt( v );
2578       if ( p.IsEqual( gp_Pnt( xyz[0], xyz[1], xyz[2]), 2*tol))
2579         xyz[0] = p.X(), xyz[1] = p.Y(), xyz[2] = p.Z();
2580       else
2581         tag = 0; // enforced or attracted vertex
2582       nodes[iv] = SMESH_Algo::VertexNode( v, meshDS );
2583     }
2584     if ( !nodes[iv] )
2585       nodes[iv] = meshDS->AddNode(xyz[0], xyz[1], xyz[2]);
2586
2587     // Create group of enforced vertices if requested
2588     BLSURFPlugin_Hypothesis::TEnfVertexCoords projVertex;
2589     projVertex.clear();
2590     projVertex.push_back((double)xyz[0]);
2591     projVertex.push_back((double)xyz[1]);
2592     projVertex.push_back((double)xyz[2]);
2593     std::map< BLSURFPlugin_Hypothesis::TEnfVertexCoords, BLSURFPlugin_Hypothesis::TEnfVertexList >::const_iterator enfCoordsIt = EnfVertexCoords2EnfVertexList.find(projVertex);
2594     if (enfCoordsIt != EnfVertexCoords2EnfVertexList.end())
2595     {
2596       BLSURFPlugin_Hypothesis::TEnfVertexList::const_iterator enfListIt = enfCoordsIt->second.begin();
2597       BLSURFPlugin_Hypothesis::TEnfVertex *currentEnfVertex;
2598       for (; enfListIt != enfCoordsIt->second.end(); ++enfListIt) {
2599         currentEnfVertex = (*enfListIt);
2600         if (currentEnfVertex->grpName != "") {
2601           bool groupDone = false;
2602           SMESH_Mesh::GroupIteratorPtr grIt = aMesh.GetGroups();
2603           while (grIt->more()) {
2604             SMESH_Group * group = grIt->next();
2605             if ( !group ) continue;
2606             SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2607             if ( !groupDS ) continue;
2608             if ( groupDS->GetType()==SMDSAbs_Node && currentEnfVertex->grpName.compare(group->GetName())==0) {
2609               SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( groupDS );
2610               aGroupDS->SMDSGroup().Add(nodes[iv]);
2611               // How can I inform the hypothesis ?
2612               //                 _hypothesis->AddEnfVertexNodeID(currentEnfVertex->grpName,nodes[iv]->GetID());
2613               groupDone = true;
2614               break;
2615             }
2616           }
2617           if (!groupDone)
2618           {
2619             int groupId;
2620             SMESH_Group* aGroup = aMesh.AddGroup(SMDSAbs_Node, currentEnfVertex->grpName.c_str(), groupId);
2621             aGroup->SetName( currentEnfVertex->grpName.c_str() );
2622             SMESHDS_Group* aGroupDS = static_cast<SMESHDS_Group*>( aGroup->GetGroupDS() );
2623             aGroupDS->SMDSGroup().Add(nodes[iv]);
2624             groupDone = true;
2625           }
2626           if (!groupDone)
2627             throw SALOME_Exception(LOCALIZED("An enforced vertex node was not added to a group"));
2628         }
2629         else
2630           MESSAGE("Group name is empty: '"<<currentEnfVertex->grpName<<"' => group is not created");
2631       }
2632     }
2633
2634     // internal points are tagged to zero
2635     if(tag > 0 && tag <= pmap.Extent() ){
2636       meshDS->SetNodeOnVertex(nodes[iv], TopoDS::Vertex(pmap(tag)));
2637       tags[iv] = false;
2638     } else {
2639       tags[iv] = true;
2640     }
2641   }
2642
2643   /* enumerate edges */
2644   for(int it=1;it<=ne;it++) {
2645     SMDS_MeshEdge* edg;
2646     mesh_get_edge_vertices(msh, it, vtx);
2647     mesh_get_edge_extra_vertices(msh, it, &type, evedg);
2648     mesh_get_edge_tag(msh, it, &tag);
2649
2650     // If PreCAD performed some cleaning operations (remove tiny edges,
2651     // merge edges ...) an output tag can indeed represent several original tags.
2652     // Get the initial tags corresponding to the output tag and redefine the tag as 
2653     // the last of the two initial tags (else the output tag is out of emap and hasn't any meaning)
2654     mesh_get_composite_tag_definition(msh, tag, &nb_tag, tags_buff);
2655     if(nb_tag > 1)  
2656       tag=tags_buff[nb_tag-1];
2657     if ( tag < 1 || tag > emap.Extent() )
2658     {
2659       std::cerr << "MG-CADSurf BUG:::: Edge tag " << tag
2660                 << " does not point to a CAD edge (nb edges " << emap.Extent() << ")" << std::endl;
2661       continue;
2662     }
2663     if (tags[vtx[0]]) {
2664       Set_NodeOnEdge(meshDS, nodes[vtx[0]], emap(tag));
2665       tags[vtx[0]] = false;
2666     };
2667     if (tags[vtx[1]]) {
2668       Set_NodeOnEdge(meshDS, nodes[vtx[1]], emap(tag));
2669       tags[vtx[1]] = false;
2670     };
2671     if (type == MESHGEMS_MESH_ELEMENT_TYPE_EDGE3) {
2672       // QUADRATIC EDGE
2673       if (tags[evedg[0]]) {
2674         Set_NodeOnEdge(meshDS, nodes[evedg[0]], emap(tag));
2675         tags[evedg[0]] = false;
2676       }
2677       edg = meshDS->AddEdge(nodes[vtx[0]], nodes[vtx[1]], nodes[evedg[0]]);
2678     }
2679     else {
2680       edg = helper.AddEdge(nodes[vtx[0]], nodes[vtx[1]]);
2681     }
2682     meshDS->SetMeshElementOnShape(edg, TopoDS::Edge(emap(tag)));
2683   }
2684
2685   /* enumerate triangles */
2686   for(int it=1;it<=nt;it++) {
2687     SMDS_MeshFace* tri;
2688     mesh_get_triangle_vertices(msh, it, vtx);
2689     mesh_get_triangle_extra_vertices(msh, it, &type, evtri);
2690     mesh_get_triangle_tag(msh, it, &tag);
2691     if (tags[vtx[0]]) {
2692       meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2693       tags[vtx[0]] = false;
2694     };
2695     if (tags[vtx[1]]) {
2696       meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2697       tags[vtx[1]] = false;
2698     };
2699     if (tags[vtx[2]]) {
2700       meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2701       tags[vtx[2]] = false;
2702     };
2703     if (type == MESHGEMS_MESH_ELEMENT_TYPE_TRIA6) {
2704       // QUADRATIC TRIANGLE
2705       if (tags[evtri[0]]) {
2706         meshDS->SetNodeOnFace(nodes[evtri[0]], tag);
2707         tags[evtri[0]] = false;
2708       }
2709       if (tags[evtri[1]]) {
2710         meshDS->SetNodeOnFace(nodes[evtri[1]], tag);
2711         tags[evtri[1]] = false;
2712       }
2713       if (tags[evtri[2]]) {
2714         meshDS->SetNodeOnFace(nodes[evtri[2]], tag);
2715         tags[evtri[2]] = false;
2716       }
2717       tri = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]],
2718                             nodes[evtri[0]], nodes[evtri[1]], nodes[evtri[2]]);
2719     }
2720     else {
2721       tri = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]]);
2722     }
2723     meshDS->SetMeshElementOnShape(tri, tag);
2724   }
2725
2726   /* enumerate quadrangles */
2727   for(int it=1;it<=nq;it++) {
2728     SMDS_MeshFace* quad;
2729     mesh_get_quadrangle_vertices(msh, it, vtx);
2730     mesh_get_quadrangle_extra_vertices(msh, it, &type, evquad);
2731     mesh_get_quadrangle_tag(msh, it, &tag);
2732     if (tags[vtx[0]]) {
2733       meshDS->SetNodeOnFace(nodes[vtx[0]], tag);
2734       tags[vtx[0]] = false;
2735     };
2736     if (tags[vtx[1]]) {
2737       meshDS->SetNodeOnFace(nodes[vtx[1]], tag);
2738       tags[vtx[1]] = false;
2739     };
2740     if (tags[vtx[2]]) {
2741       meshDS->SetNodeOnFace(nodes[vtx[2]], tag);
2742       tags[vtx[2]] = false;
2743     };
2744     if (tags[vtx[3]]) {
2745       meshDS->SetNodeOnFace(nodes[vtx[3]], tag);
2746       tags[vtx[3]] = false;
2747     };
2748     if (type == MESHGEMS_MESH_ELEMENT_TYPE_QUAD9) {
2749       // QUADRATIC QUADRANGLE
2750       std::cout << "This is a quadratic quadrangle" << std::endl;
2751       if (tags[evquad[0]]) {
2752         meshDS->SetNodeOnFace(nodes[evquad[0]], tag);
2753         tags[evquad[0]] = false;
2754       }
2755       if (tags[evquad[1]]) {
2756         meshDS->SetNodeOnFace(nodes[evquad[1]], tag);
2757         tags[evquad[1]] = false;
2758       }
2759       if (tags[evquad[2]]) {
2760         meshDS->SetNodeOnFace(nodes[evquad[2]], tag);
2761         tags[evquad[2]] = false;
2762       }
2763       if (tags[evquad[3]]) {
2764         meshDS->SetNodeOnFace(nodes[evquad[3]], tag);
2765         tags[evquad[3]] = false;
2766       }
2767       if (tags[evquad[4]]) {
2768         meshDS->SetNodeOnFace(nodes[evquad[4]], tag);
2769         tags[evquad[4]] = false;
2770       }
2771       quad = meshDS->AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]],
2772                              nodes[evquad[0]], nodes[evquad[1]], nodes[evquad[2]], nodes[evquad[3]],
2773                              nodes[evquad[4]]);
2774     }
2775     else {
2776       quad = helper.AddFace(nodes[vtx[0]], nodes[vtx[1]], nodes[vtx[2]], nodes[vtx[3]]);
2777     }
2778     meshDS->SetMeshElementOnShape(quad, tag);
2779   }
2780
2781   /* release the mesh object, the rest is released by cleaner */
2782   cadsurf_regain_mesh(css, msh);
2783
2784
2785   // Remove free nodes that can appear e.g. if "remove tiny edges"(IPAL53235)
2786   for(int iv=1;iv<=nv;iv++)
2787     if ( nodes[iv] && nodes[iv]->NbInverseElements() == 0 )
2788       meshDS->RemoveFreeNode( nodes[iv], 0, /*fromGroups=*/false );
2789
2790
2791   if ( needMerge ) // sew mesh computed by MG-CADSurf with pre-existing mesh
2792   {
2793     SMESH_MeshEditor editor( &aMesh );
2794     SMESH_MeshEditor::TListOfListOfNodes nodeGroupsToMerge;
2795     TIDSortedElemSet segementsOnEdge;
2796     TSubMeshSet::iterator smIt;
2797     SMESHDS_SubMesh* smDS;
2798
2799     // merge nodes on EDGE's with ones computed by MG-CADSurf
2800     for ( smIt = mergeSubmeshes.begin(); smIt != mergeSubmeshes.end(); ++smIt )
2801     {
2802       if (! (smDS = *smIt) ) continue;
2803       getNodeGroupsToMerge( smDS, meshDS->IndexToShape((*smIt)->GetID()), nodeGroupsToMerge );
2804
2805       SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2806       while ( segIt->more() )
2807         segementsOnEdge.insert( segIt->next() );
2808     }
2809     // merge nodes
2810     editor.MergeNodes( nodeGroupsToMerge );
2811
2812     // merge segments
2813     SMESH_MeshEditor::TListOfListOfElementsID equalSegments;
2814     editor.FindEqualElements( segementsOnEdge, equalSegments );
2815     editor.MergeElements( equalSegments );
2816
2817     // remove excess segments created on the boundary of viscous layers
2818     const SMDS_TypeOfPosition onFace = SMDS_TOP_FACE;
2819     for ( int i = 1; i <= emap.Extent(); ++i )
2820     {
2821       if ( SMESHDS_SubMesh* smDS = meshDS->MeshElements( emap( i )))
2822       {
2823         SMDS_ElemIteratorPtr segIt = smDS->GetElements();
2824         while ( segIt->more() )
2825         {
2826           const SMDS_MeshElement* seg = segIt->next();
2827           if ( seg->GetNode(0)->GetPosition()->GetTypeOfPosition() == onFace ||
2828                seg->GetNode(1)->GetPosition()->GetTypeOfPosition() == onFace )
2829             meshDS->RemoveFreeElement( seg, smDS );
2830         }
2831       }
2832     }
2833   }
2834
2835
2836   // SetIsAlwaysComputed( true ) to sub-meshes of EDGEs w/o mesh
2837   for (int i = 1; i <= emap.Extent(); i++)
2838     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( emap( i )))
2839       sm->SetIsAlwaysComputed( true );
2840   for (int i = 1; i <= pmap.Extent(); i++)
2841     if ( SMESH_subMesh* sm = aMesh.GetSubMeshContaining( pmap( i )))
2842       if ( !sm->IsMeshComputed() )
2843         sm->SetIsAlwaysComputed( true );
2844
2845   // Set error to FACE's w/o elements
2846   SMESH_ComputeErrorName err = COMPERR_ALGO_FAILED;
2847   if ( _comment.empty() && status == STATUS_OK )
2848   {
2849     err      = COMPERR_WARNING;
2850     _comment = "No mesh elements assigned to a face";
2851   }
2852   bool badFaceFound = false;
2853   for (TopExp_Explorer face_iter(aShape,TopAbs_FACE);face_iter.More();face_iter.Next())
2854   {
2855     TopoDS_Face f = TopoDS::Face(face_iter.Current());
2856     SMESH_subMesh* sm = aMesh.GetSubMesh( f );
2857     if ( !sm->GetSubMeshDS() || sm->GetSubMeshDS()->NbElements() == 0 )
2858     {
2859       int faceTag = sm->GetId();
2860       if ( faceTag != BLSURFPlugin_Hypothesis::GetHyperPatchTag( faceTag, _hypothesis ))
2861       {
2862         // triangles are assigned to the first face of hyper-patch
2863         sm->SetIsAlwaysComputed( true );
2864       }
2865       else
2866       {
2867         sm->GetComputeError().reset( new SMESH_ComputeError( err, _comment, this ));
2868         badFaceFound = true;
2869       }
2870     }
2871   }
2872   if ( err == COMPERR_WARNING )
2873   {
2874     _comment.clear();
2875   }
2876   if ( status != STATUS_OK && !badFaceFound ) {
2877     error(_comment);
2878   }
2879
2880   // Issue 0019864. On DebianSarge, FE signals do not obey to OSD::SetSignal(false)
2881 #ifndef WIN32
2882   if ( oldFEFlags > 0 )
2883     feenableexcept( oldFEFlags );
2884   feclearexcept( FE_ALL_EXCEPT );
2885 #endif
2886
2887   /*
2888     std::cout << "FacesWithSizeMap" << std::endl;
2889     FacesWithSizeMap.Statistics(std::cout);
2890     std::cout << "EdgesWithSizeMap" << std::endl;
2891     EdgesWithSizeMap.Statistics(std::cout);
2892     std::cout << "VerticesWithSizeMap" << std::endl;
2893     VerticesWithSizeMap.Statistics(std::cout);
2894     std::cout << "FacesWithEnforcedVertices" << std::endl;
2895     FacesWithEnforcedVertices.Statistics(std::cout);
2896   */
2897
2898   return ( status == STATUS_OK && !quadraticSubMeshAndViscousLayer );
2899 }
2900
2901 //================================================================================
2902 /*!
2903  * \brief Compute a mesh basing on discrete CAD description
2904  */
2905 //================================================================================
2906
2907 bool BLSURFPlugin_BLSURF::Compute(SMESH_Mesh & aMesh, SMESH_MesherHelper* aHelper)
2908 {
2909   if ( aMesh.NbFaces() == 0 )
2910     return error( COMPERR_BAD_INPUT_MESH, "2D elements are missing" );
2911
2912   context_t *ctx = context_new();
2913   if (!ctx) return error("Pb in context_new()");
2914
2915   BLSURF_Cleaner cleaner( ctx );
2916
2917   message_cb_user_data mcud;
2918   mcud._error     = & this->SMESH_Algo::_comment;
2919   mcud._progress  = & this->SMESH_Algo::_progress;
2920   mcud._verbosity =
2921     _hypothesis ? _hypothesis->GetVerbosity() : BLSURFPlugin_Hypothesis::GetDefaultVerbosity();
2922   meshgems_status_t ret = context_set_message_callback(ctx, message_cb, &mcud);
2923   if (ret != STATUS_OK) return error("Pb. in context_set_message_callback() ");
2924
2925   cadsurf_session_t * css = cadsurf_session_new(ctx);
2926   if(!css) return error( "Pb. in cadsurf_session_new() " );
2927   cleaner._css = css;
2928
2929
2930   // Fill an input mesh
2931
2932   mesh_t * msh = meshgems_mesh_new_in_memory( ctx );
2933   if ( !msh ) return error("Pb. in meshgems_mesh_new_in_memory()"); 
2934
2935   // mark nodes used by 2D elements
2936   SMESHDS_Mesh* meshDS = aMesh.GetMeshDS();
2937   SMDS_NodeIteratorPtr nodeIt = meshDS->nodesIterator();
2938   while ( nodeIt->more() )
2939   {
2940     const SMDS_MeshNode* n = nodeIt->next();
2941     n->setIsMarked( n->NbInverseElements( SMDSAbs_Face ));
2942   }
2943   meshgems_mesh_set_vertex_count( msh, meshDS->NbNodes() );
2944
2945   // set node coordinates
2946   if ( meshDS->NbNodes() != meshDS->MaxNodeID() )
2947   {
2948     meshDS->compactMesh();
2949   }
2950   SMESH_NodeXYZ nXYZ;
2951   nodeIt = meshDS->nodesIterator();
2952   meshgems_integer i;
2953   for ( i = 1; nodeIt->more(); ++i )
2954   {
2955     nXYZ.Set( nodeIt->next() );
2956     meshgems_mesh_set_vertex_coordinates( msh, i, nXYZ.ChangeData() );
2957   }
2958
2959   // set nodes of faces
2960   meshgems_mesh_set_triangle_count  ( msh, meshDS->GetMeshInfo().NbTriangles() );
2961   meshgems_mesh_set_quadrangle_count( msh, meshDS->GetMeshInfo().NbQuadrangles() );
2962   meshgems_integer nodeIDs[4];
2963   meshgems_integer iT = 1, iQ = 1;
2964   SMDS_FaceIteratorPtr faceIt = meshDS->facesIterator();
2965   while ( faceIt->more() )
2966   {
2967     const SMDS_MeshElement* face = faceIt->next();
2968     meshgems_integer nbNodes = face->NbCornerNodes();
2969     if ( nbNodes > 4 || face->IsPoly() ) continue;
2970
2971     for ( i = 0; i < nbNodes; ++i )
2972       nodeIDs[i] = face->GetNode( i )->GetID();
2973     if ( nbNodes == 3 )
2974       meshgems_mesh_set_triangle_vertices  ( msh, iT++, nodeIDs );
2975     else
2976       meshgems_mesh_set_quadrangle_vertices( msh, iQ++, nodeIDs );
2977   }
2978
2979   ret = cadsurf_set_mesh(css, msh);
2980   if ( ret != STATUS_OK ) return error("Pb in cadsurf_set_mesh()");
2981
2982
2983   // Compute the mesh
2984
2985   SetParameters(_hypothesis, css, aMesh.GetShapeToMesh() );
2986
2987   ret = cadsurf_compute_mesh(css);
2988   if ( ret != STATUS_OK ) return false;
2989
2990   mesh_t *omsh = 0;
2991   cadsurf_get_mesh(css, &omsh);
2992   if ( !omsh ) return error( "Pb. in cadsurf_get_mesh()" );
2993
2994
2995   // Update SALOME mesh
2996
2997   // remove quadrangles and triangles
2998   for ( faceIt = meshDS->facesIterator(); faceIt->more();  )
2999   {
3000     const SMDS_MeshElement* face = faceIt->next();
3001     if ( !face->IsPoly() )
3002       meshDS->RemoveFreeElement( face, /*sm=*/0, /*fromGroups=*/true );
3003   }
3004   // remove edges that bound the just removed faces
3005   for ( SMDS_EdgeIteratorPtr edgeIt = meshDS->edgesIterator(); edgeIt->more(); )
3006   {
3007     const SMDS_MeshElement* edge = edgeIt->next();
3008     const SMDS_MeshNode* n0 = edge->GetNode(0);
3009     const SMDS_MeshNode* n1 = edge->GetNode(1);
3010     if ( n0->isMarked() &&
3011          n1->isMarked() &&
3012          n0->NbInverseElements( SMDSAbs_Volume ) == 0 &&
3013          n1->NbInverseElements( SMDSAbs_Volume ) == 0 )
3014       meshDS->RemoveFreeElement( edge, /*sm=*/0, /*fromGroups=*/true );
3015   }
3016   // remove nodes that just became free
3017   for ( nodeIt = meshDS->nodesIterator(); nodeIt->more(); )
3018   {
3019     const SMDS_MeshNode* n = nodeIt->next();
3020     if ( n->isMarked() && n->NbInverseElements() == 0 )
3021       meshDS->RemoveFreeNode( n, /*sm=*/0, /*fromGroups=*/true );
3022   }
3023
3024   // add nodes
3025   meshgems_integer nbvtx = 0, nodeID;
3026   meshgems_mesh_get_vertex_count( omsh, &nbvtx );
3027   meshgems_real xyz[3];
3028   for ( i = 1; i <= nbvtx; ++i )
3029   {
3030     meshgems_mesh_get_vertex_coordinates( omsh, i, xyz );
3031     SMDS_MeshNode* n = meshDS->AddNode( xyz[0], xyz[1], xyz[2] );
3032     nodeID = n->GetID();
3033     meshgems_mesh_set_vertex_tag( omsh, i, &nodeID ); // save mapping of IDs in MG and SALOME meshes
3034   }
3035
3036   // add triangles
3037   meshgems_integer nbtri = 0;
3038   meshgems_mesh_get_triangle_count( omsh, &nbtri );
3039   const SMDS_MeshNode* nodes[3];
3040   for ( i = 1; i <= nbtri; ++i )
3041   {
3042     meshgems_mesh_get_triangle_vertices( omsh, i, nodeIDs );
3043     for ( int j = 0; j < 3; ++j )
3044     {
3045       meshgems_mesh_get_vertex_tag( omsh, nodeIDs[j], &nodeID );
3046       nodes[j] = meshDS->FindNode( nodeID );
3047     }
3048     meshDS->AddFace( nodes[0], nodes[1], nodes[2] );
3049   }
3050
3051   cadsurf_regain_mesh(css, omsh);
3052
3053   // as we don't assign the new triangles to a shape (the pseudo-shape),
3054   // we mark the shape as always computed to avoid the error messages
3055   // that no elements assigned to the shape
3056   aMesh.GetSubMesh( aHelper->GetSubShape() )->SetIsAlwaysComputed( true );
3057
3058   return true;
3059 }
3060
3061 //================================================================================
3062 /*!
3063  * \brief Terminates computation
3064  */
3065 //================================================================================
3066
3067 void BLSURFPlugin_BLSURF::CancelCompute()
3068 {
3069   _compute_canceled = true;
3070 }
3071
3072 //=============================================================================
3073 /*!
3074  *  SetNodeOnEdge
3075  */
3076 //=============================================================================
3077
3078 void BLSURFPlugin_BLSURF::Set_NodeOnEdge(SMESHDS_Mesh*        meshDS,
3079                                          const SMDS_MeshNode* node,
3080                                          const TopoDS_Shape&  ed)
3081 {
3082   const TopoDS_Edge edge = TopoDS::Edge(ed);
3083
3084   gp_Pnt pnt(node->X(), node->Y(), node->Z());
3085
3086   Standard_Real p0 = 0.0;
3087   Standard_Real p1 = 1.0;
3088   TopLoc_Location loc;
3089   Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, loc, p0, p1);
3090   if ( curve.IsNull() )
3091   {
3092     // issue 22499. Node at a sphere apex
3093     meshDS->SetNodeOnEdge(node, edge, p0);
3094     return;
3095   }
3096
3097   if ( !loc.IsIdentity() ) pnt.Transform( loc.Transformation().Inverted() );
3098   GeomAPI_ProjectPointOnCurve proj(pnt, curve, p0, p1);
3099
3100   double pa = 0.;
3101   if ( proj.NbPoints() > 0 )
3102   {
3103     pa = (double)proj.LowerDistanceParameter();
3104     // Issue 0020656. Move node if it is too far from edge
3105     gp_Pnt curve_pnt = curve->Value( pa );
3106     double dist2     = pnt.SquareDistance( curve_pnt );
3107     double tol       = BRep_Tool::Tolerance( edge );
3108     if ( 1e-14 < dist2 && dist2 <= 1000*tol ) // large enough and within tolerance
3109     {
3110       curve_pnt.Transform( loc );
3111       meshDS->MoveNode( node, curve_pnt.X(), curve_pnt.Y(), curve_pnt.Z() );
3112     }
3113   }
3114
3115   meshDS->SetNodeOnEdge(node, edge, pa);
3116 }
3117
3118 /* Curve definition function See cad_curv_t in file meshgems/cad.h for
3119  * more information.
3120  * NOTE : if when your CAD systems evaluates second
3121  * order derivatives it also computes first order derivatives and
3122  * function evaluation, you can optimize this example by making only
3123  * one CAD call and filling the necessary uv, dt, dtt arrays.
3124  */
3125 status_t curv_fun(real t, real *uv, real *dt, real *dtt, void *user_data)
3126 {
3127   /* t is given. It contains the t (time) 1D parametric coordintaes
3128      of the point PreCAD/MG-CADSurf is querying on the curve */
3129
3130   /* user_data identifies the edge PreCAD/MG-CADSurf is querying
3131    * (see cad_edge_new later in this example) */
3132   const Geom2d_Curve*pargeo = (const Geom2d_Curve*) user_data;
3133
3134   if (uv){
3135    /* MG-CADSurf is querying the function evaluation */
3136     gp_Pnt2d P;
3137     P=pargeo->Value(t);
3138     uv[0]=P.X(); uv[1]=P.Y();
3139   }
3140
3141   if(dt) {
3142    /* query for the first order derivatives */
3143     gp_Vec2d V1;
3144     V1=pargeo->DN(t,1);
3145     dt[0]=V1.X(); dt[1]=V1.Y();
3146   }
3147
3148   if(dtt){
3149     /* query for the second order derivatives */
3150     gp_Vec2d V2;
3151     V2=pargeo->DN(t,2);
3152     dtt[0]=V2.X(); dtt[1]=V2.Y();
3153   }
3154
3155   return STATUS_OK;
3156 }
3157
3158 /* Surface definition function.
3159  * See cad_surf_t in file meshgems/cad.h for more information.
3160  * NOTE : if when your CAD systems evaluates second order derivatives it also
3161  * computes first order derivatives and function evaluation, you can optimize
3162  * this example by making only one CAD call and filling the necessary xyz, du, dv, etc..
3163  * arrays.
3164  */
3165 status_t surf_fun(real *uv, real *xyz, real*du, real *dv,
3166                   real *duu, real *duv, real *dvv, void *user_data)
3167 {
3168   /* uv[2] is given. It contains the u,v coordinates of the point
3169    * PreCAD/MG-CADSurf is querying on the surface */
3170
3171   /* user_data identifies the face PreCAD/MG-CADSurf is querying (see
3172    * cad_face_new later in this example)*/
3173   const Geom_Surface* geometry = (const Geom_Surface*) user_data;
3174
3175   if(xyz){
3176    gp_Pnt P;
3177    P=geometry->Value(uv[0],uv[1]);   // S.D0(U,V,P);
3178    xyz[0]=P.X(); xyz[1]=P.Y(); xyz[2]=P.Z();
3179   }
3180
3181   if(du && dv){
3182     gp_Pnt P;
3183     gp_Vec D1U,D1V;
3184
3185     geometry->D1(uv[0],uv[1],P,D1U,D1V);
3186     du[0]=D1U.X(); du[1]=D1U.Y(); du[2]=D1U.Z();
3187     dv[0]=D1V.X(); dv[1]=D1V.Y(); dv[2]=D1V.Z();
3188   }
3189
3190   if(duu && duv && dvv){
3191
3192     gp_Pnt P;
3193     gp_Vec D1U,D1V;
3194     gp_Vec D2U,D2V,D2UV;
3195
3196     geometry->D2(uv[0],uv[1],P,D1U,D1V,D2U,D2V,D2UV);
3197     duu[0]=D2U.X(); duu[1]=D2U.Y(); duu[2]=D2U.Z();
3198     duv[0]=D2UV.X(); duv[1]=D2UV.Y(); duv[2]=D2UV.Z();
3199     dvv[0]=D2V.X(); dvv[1]=D2V.Y(); dvv[2]=D2V.Z();
3200   }
3201
3202   return STATUS_OK;
3203 }
3204
3205
3206 status_t size_on_surface(integer face_id, real *uv, real *size, void *user_data)
3207 {
3208   TId2ClsAttractorVec::iterator f2attVec;
3209   if (FaceId2PythonSmp.count(face_id) != 0) {
3210     assert(Py_IsInitialized());
3211     PyGILState_STATE gstate;
3212     gstate = PyGILState_Ensure();
3213     PyObject* pyresult = PyObject_CallFunction(FaceId2PythonSmp[face_id],(char*)"(f,f)",uv[0],uv[1]);
3214     real result;
3215     if ( pyresult != NULL) {
3216       result = PyFloat_AsDouble(pyresult);
3217       Py_DECREF(pyresult);
3218       //       *size = result;
3219     }
3220     else{
3221       fflush(stderr);
3222       string err_description="";
3223       PyObject* new_stderr = newPyStdOut(err_description);
3224       PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3225       Py_INCREF(old_stderr);
3226       PySys_SetObject((char*)"stderr", new_stderr);
3227       PyErr_Print();
3228       PySys_SetObject((char*)"stderr", old_stderr);
3229       Py_DECREF(new_stderr);
3230       MESSAGE("Can't evaluate f(" << uv[0] << "," << uv[1] << ")" << " error is " << err_description);
3231       result = *((real*)user_data);
3232     }
3233     *size = result;
3234     PyGILState_Release(gstate);
3235   }
3236   else if (( f2attVec = FaceIndex2ClassAttractor.find(face_id)) != FaceIndex2ClassAttractor.end() && !f2attVec->second.empty())
3237   {
3238     real result = 0;
3239     result = 1e100;
3240     std::vector< BLSURFPlugin_Attractor* > & attVec = f2attVec->second;
3241     for ( size_t i = 0; i < attVec.size(); ++i )
3242     {
3243       //result += attVec[i]->GetSize(uv[0],uv[1]);
3244       result = Min( result, attVec[i]->GetSize(uv[0],uv[1]));
3245     }
3246     //*size = result / attVec.size(); // mean of sizes defined by all attractors
3247     *size = result;
3248   }
3249   else {
3250     *size = *((real*)user_data);
3251   }
3252   //   std::cout << "Size_on_surface sur la face " << face_id << " donne une size de: " << *size << std::endl;
3253   return STATUS_OK;
3254 }
3255
3256 status_t size_on_edge(integer edge_id, real t, real *size, void *user_data)
3257 {
3258   if (EdgeId2PythonSmp.count(edge_id) != 0){
3259     assert(Py_IsInitialized());
3260     PyGILState_STATE gstate;
3261     gstate = PyGILState_Ensure();
3262     PyObject* pyresult = PyObject_CallFunction(EdgeId2PythonSmp[edge_id],(char*)"(f)",t);
3263     real result;
3264     if ( pyresult != NULL) {
3265       result = PyFloat_AsDouble(pyresult);
3266       Py_DECREF(pyresult);
3267 //       *size = result;
3268     }
3269     else{
3270       fflush(stderr);
3271       string err_description="";
3272       PyObject* new_stderr = newPyStdOut(err_description);
3273       PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3274       Py_INCREF(old_stderr);
3275       PySys_SetObject((char*)"stderr", new_stderr);
3276       PyErr_Print();
3277       PySys_SetObject((char*)"stderr", old_stderr);
3278       Py_DECREF(new_stderr);
3279       MESSAGE("Can't evaluate f(" << t << ")" << " error is " << err_description);
3280       result = *((real*)user_data);
3281     }
3282     *size = result;
3283     PyGILState_Release(gstate);
3284   }
3285   else {
3286     *size = *((real*)user_data);
3287   }
3288   return STATUS_OK;
3289 }
3290
3291 status_t size_on_vertex(integer point_id, real *size, void *user_data)
3292 {
3293   if (VertexId2PythonSmp.count(point_id) != 0){
3294     assert(Py_IsInitialized());
3295     PyGILState_STATE gstate;
3296     gstate = PyGILState_Ensure();
3297     PyObject* pyresult = PyObject_CallFunction(VertexId2PythonSmp[point_id],(char*)"");
3298     real result;
3299     if ( pyresult != NULL) {
3300       result = PyFloat_AsDouble(pyresult);
3301       Py_DECREF(pyresult);
3302 //       *size = result;
3303     }
3304     else {
3305       fflush(stderr);
3306       string err_description="";
3307       PyObject* new_stderr = newPyStdOut(err_description);
3308       PyObject* old_stderr = PySys_GetObject((char*)"stderr");
3309       Py_INCREF(old_stderr);
3310       PySys_SetObject((char*)"stderr", new_stderr);
3311       PyErr_Print();
3312       PySys_SetObject((char*)"stderr", old_stderr);
3313       Py_DECREF(new_stderr);
3314       MESSAGE("Can't evaluate f()" << " error is " << err_description);
3315       result = *((real*)user_data);
3316     }
3317     *size = result;
3318     PyGILState_Release(gstate);
3319   }
3320   else {
3321     *size = *((real*)user_data);
3322   }
3323  return STATUS_OK;
3324 }
3325
3326 /*
3327  * The following function will be called for PreCAD/MG-CADSurf message
3328  * printing.  See context_set_message_callback (later in this
3329  * template) for how to set user_data.
3330  */
3331 status_t message_cb(message_t *msg, void *user_data)
3332 {
3333   integer errnumber = 0;
3334   char *desc;
3335   message_get_number(msg, &errnumber);
3336   message_get_description(msg, &desc);
3337   string err( desc );
3338   message_cb_user_data * mcud = (message_cb_user_data*)user_data;
3339   // Get all the error message and some warning messages related to license and periodicity
3340   if ( errnumber < 0 ||
3341        err.find("license"    ) != string::npos ||
3342        err.find("periodicity") != string::npos )
3343   {
3344     // remove ^A from the tail
3345     int len = strlen( desc );
3346     while (len > 0 && desc[len-1] != '\n')
3347       len--;
3348     mcud->_error->append( desc, len );
3349   }
3350   else {
3351     if ( errnumber == 3009001 )
3352       * mcud->_progress = atof( desc + 11 ) / 100.;
3353     if ( mcud->_verbosity > 0 )
3354       std::cout << desc << std::endl;
3355   }
3356   return STATUS_OK;
3357 }
3358
3359 /* This is the interrupt callback. PreCAD/MG-CADSurf will call this
3360  * function regularily. See the file meshgems/interrupt.h
3361  */
3362 status_t interrupt_cb(integer *interrupt_status, void *user_data)
3363 {
3364   integer you_want_to_continue = 1;
3365   BLSURFPlugin_BLSURF* tmp = (BLSURFPlugin_BLSURF*)user_data;
3366   you_want_to_continue = !tmp->computeCanceled();
3367
3368   if(you_want_to_continue)
3369   {
3370     *interrupt_status = INTERRUPT_CONTINUE;
3371     return STATUS_OK;
3372   }
3373   else /* you want to stop MG-CADSurf */
3374   {
3375     *interrupt_status = INTERRUPT_STOP;
3376     return STATUS_ERROR;
3377   }
3378 }
3379
3380 //=============================================================================
3381 /*!
3382  *
3383  */
3384 //=============================================================================
3385 bool BLSURFPlugin_BLSURF::Evaluate(SMESH_Mesh&         aMesh,
3386                                    const TopoDS_Shape& aShape,
3387                                    MapShapeNbElems&    aResMap)
3388 {
3389   double diagonal       = aMesh.GetShapeDiagonalSize();
3390   double bbSegmentation = _gen->GetBoundaryBoxSegmentation();
3391   int    _physicalMesh  = BLSURFPlugin_Hypothesis::GetDefaultPhysicalMesh();
3392   double _phySize       = BLSURFPlugin_Hypothesis::GetDefaultPhySize(diagonal, bbSegmentation);
3393   bool   _phySizeRel    = BLSURFPlugin_Hypothesis::GetDefaultPhySizeRel();
3394   //int    _geometricMesh = BLSURFPlugin_Hypothesis::GetDefaultGeometricMesh();
3395   double _angleMesh     = BLSURFPlugin_Hypothesis::GetDefaultAngleMesh();
3396   BLSURFPlugin_Hypothesis::ElementType   _elementType   = BLSURFPlugin_Hypothesis::GetDefaultElementType();
3397   if(_hypothesis) {
3398     _physicalMesh  = (int) _hypothesis->GetPhysicalMesh();
3399     _phySizeRel         = _hypothesis->IsPhySizeRel();
3400     if ( _hypothesis->GetPhySize() > 0)
3401       _phySize          = _phySizeRel ? diagonal*_hypothesis->GetPhySize() : _hypothesis->GetPhySize();
3402     //_geometricMesh = (int) hyp->GetGeometricMesh();
3403     if (_hypothesis->GetAngleMesh() > 0)
3404       _angleMesh        = _hypothesis->GetAngleMesh();
3405     _elementType        = _hypothesis->GetElementType();
3406   } else {
3407     //0020968: EDF1545 SMESH: Problem in the creation of a mesh group on geometry
3408     // GetDefaultPhySize() sometimes leads to computation failure
3409     _phySize = aMesh.GetShapeDiagonalSize() / _gen->GetBoundaryBoxSegmentation();
3410   }
3411
3412   bool IsQuadratic = _quadraticMesh;
3413
3414   // ----------------
3415   // evaluate 1D
3416   // ----------------
3417   TopTools_DataMapOfShapeInteger EdgesMap;
3418   double fullLen = 0.0;
3419   double fullNbSeg = 0;
3420   for (TopExp_Explorer exp(aShape, TopAbs_EDGE); exp.More(); exp.Next()) {
3421     TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3422     if( EdgesMap.IsBound(E) )
3423       continue;
3424     SMESH_subMesh *sm = aMesh.GetSubMesh(E);
3425     double aLen = SMESH_Algo::EdgeLength(E);
3426     fullLen += aLen;
3427     int nb1d = 0;
3428     if(_physicalMesh==1) {
3429        nb1d = (int)( aLen/_phySize + 1 );
3430     }
3431     else {
3432       // use geometry
3433       double f,l;
3434       Handle(Geom_Curve) C = BRep_Tool::Curve(E,f,l);
3435       double fullAng = 0.0;
3436       double dp = (l-f)/200;
3437       gp_Pnt P1,P2,P3;
3438       C->D0(f,P1);
3439       C->D0(f+dp,P2);
3440       gp_Vec V1(P1,P2);
3441       for(int j=2; j<=200; j++) {
3442         C->D0(f+dp*j,P3);
3443         gp_Vec V2(P2,P3);
3444         fullAng += fabs(V1.Angle(V2));
3445         V1 = V2;
3446         P2 = P3;
3447       }
3448       nb1d = (int)( fullAng/_angleMesh + 1 );
3449     }
3450     fullNbSeg += nb1d;
3451     std::vector<int> aVec(SMDSEntity_Last);
3452     for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3453     if( IsQuadratic > 0 ) {
3454       aVec[SMDSEntity_Node] = 2*nb1d - 1;
3455       aVec[SMDSEntity_Quad_Edge] = nb1d;
3456     }
3457     else {
3458       aVec[SMDSEntity_Node] = nb1d - 1;
3459       aVec[SMDSEntity_Edge] = nb1d;
3460     }
3461     aResMap.insert(std::make_pair(sm,aVec));
3462     EdgesMap.Bind(E,nb1d);
3463   }
3464   double ELen = fullLen/fullNbSeg;
3465   // ----------------
3466   // evaluate 2D
3467   // ----------------
3468   // try to evaluate as in MEFISTO
3469   for (TopExp_Explorer exp(aShape, TopAbs_FACE); exp.More(); exp.Next()) {
3470     TopoDS_Face F = TopoDS::Face( exp.Current() );
3471     SMESH_subMesh *sm = aMesh.GetSubMesh(F);
3472     GProp_GProps G;
3473     BRepGProp::SurfaceProperties(F,G);
3474     double anArea = G.Mass();
3475     int nb1d = 0;
3476     std::vector<int> nb1dVec;
3477     for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) {
3478       int nbSeg = EdgesMap.Find(exp1.Current());
3479       nb1d += nbSeg;
3480       nb1dVec.push_back( nbSeg );
3481     }
3482     int nbQuad = 0;
3483     int nbTria = (int) ( anArea/( ELen*ELen*sqrt(3.) / 4 ) );
3484     int nbNodes = (int) ( ( nbTria*3 - (nb1d-1)*2 ) / 6 + 1 );
3485     if ( _elementType != BLSURFPlugin_Hypothesis::Quadrangles )
3486     {
3487       if ( nb1dVec.size() == 4 ) // quadrangle geom face
3488       {
3489         int n1 = nb1dVec[0], n2 = nb1dVec[ nb1dVec[1] == nb1dVec[0] ? 2 : 1 ];
3490         nbQuad = n1 * n2;
3491         nbNodes = (n1 + 1) * (n2 + 1);
3492         nbTria = 0;
3493       }
3494       else
3495       {
3496         nbTria = nbQuad = nbTria / 3 + 1;
3497       }
3498     }
3499     std::vector<int> aVec(SMDSEntity_Last,0);
3500     if( IsQuadratic ) {
3501       int nb1d_in = (nbTria*3 - nb1d) / 2;
3502       aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3503       aVec[SMDSEntity_Quad_Triangle] = nbTria;
3504       aVec[SMDSEntity_Quad_Quadrangle] = nbQuad;
3505     }
3506     else {
3507       aVec[SMDSEntity_Node] = nbNodes;
3508       aVec[SMDSEntity_Triangle] = nbTria;
3509       aVec[SMDSEntity_Quadrangle] = nbQuad;
3510     }
3511     aResMap.insert(std::make_pair(sm,aVec));
3512   }
3513
3514   // ----------------
3515   // evaluate 3D
3516   // ----------------
3517   GProp_GProps G;
3518   BRepGProp::VolumeProperties(aShape,G);
3519   double aVolume = G.Mass();
3520   double tetrVol = 0.1179*ELen*ELen*ELen;
3521   int nbVols  = int(aVolume/tetrVol);
3522   int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3523   std::vector<int> aVec(SMDSEntity_Last);
3524   for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aVec[i]=0;
3525   if( IsQuadratic ) {
3526     aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3527     aVec[SMDSEntity_Quad_Tetra] = nbVols;
3528   }
3529   else {
3530     aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3531     aVec[SMDSEntity_Tetra] = nbVols;
3532   }
3533   SMESH_subMesh *sm = aMesh.GetSubMesh(aShape);
3534   aResMap.insert(std::make_pair(sm,aVec));
3535
3536   return true;
3537 }