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