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