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